Order Complete Integration Guide

Create the customer, products, categories and the order in a single request (POST /orders/complete). A step-by-step guide for marketplace scenarios.

# MyVoipCRM External API — Order Creation (Complete) Integration Guide

**Version:** 1.0
**Last updated:** June 2026
**Audience:** external system developers (e-commerce, marketplace and production integrations)

---

## 1. Purpose

This document explains how an external system submits an order to MyVoipCRM with a **single API request**. The request carries:

- the **customer** (buyer) details,
- **product/service** lines,
- **delivery and billing addresses**,
- the **order** header

all together. The API checks whether each record already exists in the CRM; it creates the ones that do not, reuses the ones that do, and opens the order.

> **Important:** this endpoint does not require you to communicate with the customer directly. Orders arrive in the CRM in their final form; production and operations run on the CRM side.

---

## 2. Basics

| Property | Value |
|---------|-------|
| **Base URL** | `https://externalapi.myvoipcrm.com/api/external/v1` |
| **Endpoint** | `POST /orders/complete` |
| **Content-Type** | `application/json` |
| **Authentication** | `X-Api-Key` header (required) |
| **Character encoding** | UTF-8 |

### 2.1 Obtaining an API key

The API key is obtained once, during initial setup, with admin user credentials:

```http
POST /api/external/v1/auth/company-api-key
Content-Type: application/json

{
  "userName": "[email protected]",
  "password": "sifreniz"
}
```

**Successful response:**

```json
{
  "success": true,
  "message": "API anahtarı getirildi.",
  "data": {
    "companyName": "Firma Adı Ltd. Şti.",
    "apiKey": "crm_xxxxxxxx"
  }
}
```

Header for every subsequent request:

```http
X-Api-Key: crm_xxxxxxxx
```

### 2.2 Allowed IPs (required)

External API requests are accepted only from the **allowed IP addresses** defined in the CRM. If the list is left empty or no IP is defined, **all requests are rejected** (`403`, `IP_NOT_ALLOWED`).

- CRM → **Developer API Settings** → Allowed IP Addresses
- Format: comma, semicolon or one per line (e.g. `203.0.113.10,198.51.100.22`)
- The `*` wildcard is not supported

Before integrating, send your server's outbound IP to your CRM administrator.

---

## 3. Workflow

```
┌─────────────────────────────────────────────────────────────┐
│  External system (you)                                      │
│  POST /orders/complete                                      │
│  • Customer details + externalId                            │
│  • Delivery / billing address                               │
│  • Product lines + description (e.g. name on the plate)     │
│  • orderNo, source, status                                  │
└──────────────────────────┬──────────────────────────────────┘
                           │
                           ▼
┌─────────────────────────────────────────────────────────────┐
│  MyVoipCRM External API                                     │
│  1. Look up the customer → find or create                   │
│  2. Look up the product on each line → find or create       │
│  3. Write the delivery address onto the customer record     │
│  4. Store the addresses in the order JSON                   │
│  5. Create the order (transaction — rolled back on error)   │
└──────────────────────────┬──────────────────────────────────┘
                           │
                           ▼
┌─────────────────────────────────────────────────────────────┐
│  Response: order + customer + products (with wasCreated)    │
└─────────────────────────────────────────────────────────────┘
```

Every step runs inside a **single transaction**. If any step fails, nothing is written permanently.

---

## 4. Request Body

### 4.1 Required fields

| Field | Type | Description |
|------|-----|----------|
| `invoiceFormDate` | datetime (ISO 8601) | Order issue date |
| `dueDate` | datetime | Due date (cannot be earlier than `invoiceFormDate`) |
| `lines` | array | At least **1** line |
| `customer` or `customerId` | object / int | Customer details (see below) |

### 4.2 The customer (`customer`)

Either of two methods can be used:

**A) Existing customer ID**

```json
"customerId": 12345
```

When `customerId` > 0 is sent, the `customer` object is ignored.

**B) Customer resolution object (recommended)**

```json
"customer": {
  "externalId": "sahibinden-kullanici-12345",
  "create": {
    "fullName": "AHMET YILMAZ",
    "phoneNumber1": "5321234567",
    "dialCode1": "90",
    "countryCode1": "TR",
    "email": "[email protected]"
  }
}
```

#### Customer lookup order

The API looks for an existing customer in this order:

1. `customerId` or `customer.id` (> 0)
2. `customer.externalId` — the external system's user ID (e.g. the marketplace userId)
3. `customer.create.email`
4. `customer.create.phoneNumber1`

If no record is **found**, a new customer is created from `customer.create`.

#### Required fields for a new customer (`create`)

| Field | Required | Description |
|------|---------|----------|
| `fullName` | Yes | Full name |
| `phoneNumber1` | Yes | Primary phone |

#### Optional customer fields (`create`)

| Field | Description |
|------|----------|
| `dialCode1`, `countryCode1` | Phone country code (default: `90` / `tr`) |
| `phoneNumber2`, `dialCode2`, `countryCode2` | Second phone |
| `email` | Email |
| `whatsappNumber`, `dialCodeWhatsapp`, `countryCodeWhatsapp` | WhatsApp |
| `tckn` | Turkish ID number (11 digits) |
| `country`, `city`, `district`, `neighborhood`, `street`, `address`, `postalCode` | Address (a delivery address can also be sent separately) |
| `gender` | 0=Male, 1=Female, 2=Other |
| `status` | 0=Active, 1=Passive, 2=Blacklist |
| `priority` | 1–5 (default: 3, Medium) |
| `description` | Notes |

---

### 4.3 Order header

| Field | Required | Description |
|------|---------|----------|
| `orderNo` | Recommended | Your external order number (should be unique) |
| `orderDate` | No | Order date |
| `description` | No | Order notes |
| `status` | No | Order stage 0–8 (default: 0) |
| `source` | Recommended | Source channel (enum, see §6) |
| `paymentStatus` | No | 0=Collected, 1=To be collected |
| `subTotal`, `kdvTotal`, `discountTotal`, `grossTotal`, `total`, `totalTl` | No | Amount fields (strings) |
| `invoiceOrderNo`, `invoiceSerialNo` | No | Invoice serial/sequence number |

---

### 4.4 Addresses

#### `deliveryAddress` — delivery address

| Field | Description |
|------|----------|
| `country` | Country |
| `city` | Province |
| `district` | District |
| `neighborhood` | Neighbourhood |
| `street` | Street |
| `address` | Full address |
| `postalCode` | Postal code |

- Stored as JSON on the order record (`addresses.delivery`).
- Also written to the **customer record's address fields** (for shipping/production).

#### `billingAddress` — billing address

Same structure as `deliveryAddress`. Stored only as JSON on the order record (`addresses.billing`); not written to the customer record.

---

### 4.5 Order lines (`lines[]`)

Each line is one order item.

#### Product resolution (`product`)

**A) Existing product ID**

```json
"serviceAndProductId": 10
```

When `serviceAndProductId` > 0, the `product` object is ignored.

**B) Product resolution object (recommended)**

```json
"product": {
  "name": "Plakalık",
  "stockCode": "PLAKALIK-STANDART",
  "create": {
    "name": "Plakalık",
    "category": {
      "title": "Plakalık Ürünleri",
      "create": {
        "title": "Plakalık Ürünleri",
        "description": "Sahibinden plakalık siparişleri"
      }
    },
    "stockCode": "PLAKALIK-STANDART",
    "taxRate": 18
  }
}
```

#### Product lookup order

1. `serviceAndProductId` or `product.id` (> 0)
2. `product.externalId` (external ID — where supported in your environment)
3. `product.stockCode` (stock code)
4. `product.barcodeNumber` (barcode)
5. `product.name` or `product.create.name` (case-insensitive exact match)

If no record is **found**, a new product is created from `product.create`.

#### Required fields for a new product (`product.create`)

| Field | Required | Description |
|------|---------|----------|
| `name` | Yes | Product/service name |
| `serviceAndProductCategoryId` **or** `category` | Yes | Category ID (> 0) **or** a category resolution object |

#### Category resolution (`category`)

When creating a product, the category does not have to exist in the CRM in advance. Instead of sending `serviceAndProductCategoryId`, a `category` object can be used:

```json
"category": {
  "title": "Plakalık Ürünleri",
  "externalId": "sahibinden-kategori-plakalik",
  "create": {
    "title": "Plakalık Ürünleri",
    "description": "Sahibinden plakalık siparişleri"
  }
}
```

**Category lookup order:**

1. `serviceAndProductCategoryId` (> 0) — direct ID
2. `category.id` (> 0)
3. `category.externalId` (external category ID)
4. `category.title` or `category.create.title` (case-insensitive exact match)

If no record is **found**, a new category is created from `category.create`.

> Alternative: if you already know the category ID, list them with `GET /service-and-product-categories` or send `serviceAndProductCategoryId`.

#### Line fields

| Field | Required | Description |
|------|---------|----------|
| `quantity` | No | Quantity (default: 1; **do not send 0**) |
| `unitPrice` | No | Unit price |
| `taxRate` | No | VAT %: 0, 1, 8, 10, 18, 20 |
| `lineTotal` | No | Line total |
| `discount` | No | Discount |
| `description` | No | **Line note** (e.g. the name to print on the plate) |
| `lineDescription` | No | Same as `description` (backwards-compatible alias) |
| `measurementUnit` | No | Unit code (0=Piece) |

---

## 5. Response

### 5.1 Successful response (HTTP 200)

```json
{
  "success": true,
  "message": "Order created successfully with resolved dependencies.",
  "data": {
    "order": {
      "id": 8842,
      "customerId": 501,
      "customerFullName": "AHMET YILMAZ",
      "orderNo": "SB-8842",
      "invoiceFormDate": "2026-06-19T00:00:00Z",
      "dueDate": "2026-06-26T00:00:00Z",
      "status": 0,
      "statusDisplayName": "Yeni Sipariş",
      "source": 4,
      "sourceDisplayName": "Sahibinden",
      "total": "590.00",
      "addresses": {
        "delivery": {
          "city": "İstanbul",
          "district": "Kadıköy",
          "neighborhood": "Caferağa",
          "address": "Moda Caddesi No:12"
        },
        "billing": {
          "city": "İstanbul",
          "district": "Üsküdar",
          "address": "Barış Sokak No:8"
        }
      },
      "lines": [
        {
          "id": 12001,
          "serviceAndProductId": 10,
          "quantity": 1,
          "description": "MEHMET YILMAZ",
          "lineTotal": "590.00"
        }
      ]
    },
    "customer": {
      "id": 501,
      "wasCreated": true,
      "externalId": "sahibinden-kullanici-12345"
    },
    "products": [
      {
        "lineIndex": 0,
        "id": 10,
        "wasCreated": false,
        "stockCode": "PLAKALIK-STANDART",
        "serviceAndProductCategoryId": 2,
        "categoryWasCreated": false
      }
    ]
  }
}
```

#### The `wasCreated` field

| Value | Meaning |
|-------|-------|
| `true` | A new record was created by this request |
| `false` | An existing CRM record was reused |

The `products[].categoryWasCreated` field shows whether the category on that line was created by this request.

Store `order.id` in your own system to track the order later.

### 5.2 Error response

```json
{
  "success": false,
  "message": "PhoneNumber1 is required and must be valid.",
  "code": "PHONE_REQUIRED"
}
```

---

## 6. Enum Reference

### 6.1 `source` — order source

| Value | Source |
|------:|--------|
| `0` | CRM |
| `1` | Mobile |
| `2` | Website |
| `3` | Trendyol |
| `4` | **Sahibinden** |
| `5` | Ticimax |
| `6` | Ideasoft |
| `7` | N11 |
| `8` | Hepsiburada |
| `9` | Amazon |
| `99` | Other |

### 6.2 `status` — order stage

| Value | Description |
|------:|----------|
| `0` | New order (default) |
| `1` | Awaiting approval |
| `2` | Approved |
| `3` | In preparation |
| `4` | Ready to ship |
| `5` | Shipped |
| `6` | Delivered |
| `7` | Completed |
| `8` | Cancelled |

### 6.3 `paymentStatus`

| Value | Description |
|------:|----------|
| `0` | Collected |
| `1` | To be collected |
| `2` | Partially collected |

---

## 7. Full Example Request (Plate Holder / Marketplace Scenario)

```http
POST /api/external/v1/orders/complete
Content-Type: application/json
X-Api-Key: crm_xxxxxxxx

{
  "customer": {
    "externalId": "sahibinden-user-987654",
    "create": {
      "fullName": "AHMET YILMAZ",
      "phoneNumber1": "5321234567",
      "dialCode1": "90",
      "countryCode1": "TR",
      "email": "[email protected]"
    }
  },
  "source": 4,
  "orderNo": "SB-2026-8842",
  "invoiceFormDate": "2026-06-19T10:00:00Z",
  "dueDate": "2026-06-26T10:00:00Z",
  "status": 0,
  "subTotal": "500.00",
  "kdvTotal": "90.00",
  "discountTotal": "0.00",
  "grossTotal": "590.00",
  "total": "590.00",
  "totalTl": "590.00",
  "deliveryAddress": {
    "city": "İstanbul",
    "district": "Kadıköy",
    "neighborhood": "Caferağa Mah.",
    "address": "Moda Caddesi No:12 Daire:5"
  },
  "billingAddress": {
    "city": "İstanbul",
    "district": "Üsküdar",
    "neighborhood": "Altunizade Mah.",
    "address": "Barış Sokak No:8"
  },
  "lines": [
    {
      "product": {
        "name": "Plakalık",
        "stockCode": "PLAKALIK-STANDART",
        "create": {
          "name": "Plakalık",
          "category": {
            "title": "Plakalık Ürünleri",
            "create": { "title": "Plakalık Ürünleri" }
          },
          "stockCode": "PLAKALIK-STANDART",
          "taxRate": 18
        }
      },
      "quantity": 1,
      "unitPrice": 500,
      "taxRate": 18,
      "lineTotal": "590.00",
      "description": "MEHMET YILMAZ"
    }
  ]
}
```

### Field mapping (marketplace → API)

| Marketplace data | API field |
|------------------|-----------|
| Order number | `orderNo` |
| Buyer userId | `customer.externalId` |
| Buyer full name | `customer.create.fullName` |
| Buyer email | `customer.create.email` |
| Buyer phone | `customer.create.phoneNumber1` |
| Delivery province/district/neighbourhood/address | `deliveryAddress.*` |
| Billing province/district/neighbourhood/address | `billingAddress.*` |
| Name on the plate | `lines[].description` |
| Quantity | `lines[].quantity` |
| Source | `source: 4` (Sahibinden) |

---

## 8. HTTP Status Codes

| Code | Meaning |
|-----|-------|
| `200` | Success |
| `400` | Invalid request / validation error |
| `401` | Invalid or missing API key |
| `403` | IP address is not on the allow-list |
| `404` | Record not found |
| `409` | Conflict (a customer with the same email/phone already exists) |
| `429` | Rate limit exceeded |
| `500` | Unexpected server error |

---

## 9. Common Error Codes

| `code` | Description | Fix |
|--------|----------|-------|
| `INVALID_API_KEY` | The API key is invalid | Check the key |
| `IP_NOT_ALLOWED` | The IP is not allowed, or no allow-list is defined | Add your integration server's outbound IP in the CRM |
| `VALIDATION_FAILED` | General validation error | Read the `message` field |
| `FULL_NAME_REQUIRED` | The customer name is missing | Send `customer.create.fullName` |
| `PHONE_REQUIRED` | The phone is missing/invalid | Send `customer.create.phoneNumber1` |
| `DUPLICATE_EMAIL` | A customer with the same email exists | The existing customer is reused; match with `externalId` |
| `DUPLICATE_PHONE` | A customer with the same phone exists | The existing customer is reused |
| `CUSTOMER_NOT_FOUND` | The given customerId was not found | Check the ID |
| `PRODUCT_NOT_FOUND` | The product was not found and `create` is missing | Add `product.create` |
| `CATEGORY_NOT_FOUND` | The category ID is invalid | Get the correct ID with `GET /service-and-product-categories` |
| `LINE_ITEMS_REQUIRED` | No lines | Send at least 1 element in `lines` |
| `DUE_DATE_INVALID` | Due date < issue date | `dueDate` must be >= `invoiceFormDate` |

---

## 10. Integration Recommendations

### 10.1 Idempotency (repeated requests)

- Fill `orderNo` with **the unique order number from your own system**.
- Check the order's state in your own system before sending, so the same order is not submitted twice.
- Fill `customer.externalId` with the marketplace user ID; repeated orders will not create the customer again.

### 10.2 Minimal payload

The minimum field set that is usually sufficient for production integrations:

```json
{
  "customer": {
    "externalId": "...",
    "create": { "fullName": "...", "phoneNumber1": "...", "email": "..." }
  },
  "source": 4,
  "orderNo": "...",
  "invoiceFormDate": "...",
  "dueDate": "...",
  "deliveryAddress": { "city": "...", "district": "...", "address": "..." },
  "billingAddress": { "city": "...", "district": "...", "address": "..." },
  "lines": [
    {
      "product": { "name": "Plakalık", "create": { "name": "Plakalık", "category": { "title": "Plakalık Ürünleri", "create": { "title": "Plakalık Ürünleri" } } } },
      "quantity": 1,
      "description": "PLAKA ÜSTÜ İSİM"
    }
  ]
}
```

### 10.3 Test environment

- Contact your CRM administrator for a test API key and base URL.
- Swagger UI: `{base-url}/swagger`

### 10.4 Out of scope (not done by this endpoint)

- Automatic warehouse stock deduction
- Creating collection / till movements
- Shipping tracking number feedback (requires a separate integration)
- SMS/email notifications to the customer

---

## 11. Related Endpoints

| Endpoint | Description |
|----------|----------|
| `POST /orders` | Order only (customer and product IDs must be known in advance) |
| `GET /orders/{id}` | Order detail |
| `PATCH /orders/{id}/status` | Update the order stage only |
| `GET /customers` | Customer list |
| `GET /service-and-products` | Product list |
| `GET /service-and-product-categories` | Category list |

---

## 12. Support

For technical questions and API key / IP allow-list requests, contact your CRM administrator.

**General API documentation:** `MyVoipCRM.ExternalAPI/README.md`