> ## Documentation Index
> Fetch the complete documentation index at: https://docs.mypopup.shop/llms.txt
> Use this file to discover all available pages before exploring further.

# Create Order

> Create a new order for a customer

## Endpoint

```
POST https://your-project.supabase.co/functions/v1/create-order
```

## Headers

<ParamField header="Authorization" type="string" required>
  Bearer token with `anon` or `service_role` key
</ParamField>

<ParamField header="Content-Type" type="string" default="application/json">
  Request body format
</ParamField>

## Request Body

<ParamField body="storeId" type="string" required>
  UUID of the store placing the order
</ParamField>

<ParamField body="buyerEmail" type="string" required>
  Customer's email address for order confirmation
</ParamField>

<ParamField body="buyerName" type="string" required>
  Customer's full name
</ParamField>

<ParamField body="buyerPhone" type="string" required>
  Customer's phone number (with country code)
</ParamField>

<ParamField body="shippingAddress" type="object" required>
  Customer's shipping address

  <Expandable title="properties">
    <ParamField body="line1" type="string" required>
      Address line 1
    </ParamField>

    <ParamField body="line2" type="string">
      Address line 2 (optional)
    </ParamField>

    <ParamField body="city" type="string" required>
      City name
    </ParamField>

    <ParamField body="state" type="string" required>
      State/Province
    </ParamField>

    <ParamField body="postalCode" type="string" required>
      ZIP/Postal code
    </ParamField>

    <ParamField body="country" type="string" required>
      Country (ISO 3166-1 alpha-2 code, e.g., "IN", "US")
    </ParamField>
  </Expandable>
</ParamField>

<ParamField body="items" type="array" required>
  Array of order items

  <Expandable title="properties">
    <ParamField body="productId" type="string" required>
      UUID of the product
    </ParamField>

    <ParamField body="variantId" type="string">
      UUID of the product variant (if applicable)
    </ParamField>

    <ParamField body="quantity" type="integer" required>
      Quantity ordered (must be > 0)
    </ParamField>

    <ParamField body="price" type="number" required>
      Price per unit at the time of order
    </ParamField>
  </Expandable>
</ParamField>

<ParamField body="paymentMethod" type="string" required>
  Payment method selected by customer

  Options: `upi_direct`, `razorpay`
</ParamField>

<ParamField body="paymentProofUrl" type="string">
  URL of payment proof image (required if `paymentMethod` is `upi_direct`)
</ParamField>

## Response

<ResponseField name="success" type="boolean">
  Indicates if the order was created successfully
</ResponseField>

<ResponseField name="orderId" type="string">
  UUID of the newly created order
</ResponseField>

<ResponseField name="orderNumber" type="string">
  Human-readable order number (e.g., "ORD-2024-001")
</ResponseField>

<ResponseField name="totalAmount" type="number">
  Total order amount in the store's currency
</ResponseField>

<ResponseField name="checkoutFee" type="number">
  Platform fee charged for this payment method
</ResponseField>

<ResponseField name="finalAmount" type="number">
  Total amount + checkout fee
</ResponseField>

<ResponseField name="status" type="string">
  Initial order status

  Options: `pending`, `payment_pending`, `paid`, `processing`, `shipped`, `delivered`, `cancelled`
</ResponseField>

## Example Request

<CodeGroup>
  ```typescript TypeScript theme={null}
  const response = await fetch(
    'https://your-project.supabase.co/functions/v1/create-order',
    {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${SUPABASE_ANON_KEY}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        storeId: 'a1b2c3d4-e5f6-7890-abcd-ef1234567890',
        buyerEmail: 'customer@example.com',
        buyerName: 'John Doe',
        buyerPhone: '+919876543210',
        shippingAddress: {
          line1: '123 Main Street',
          line2: 'Apt 4B',
          city: 'Mumbai',
          state: 'Maharashtra',
          postalCode: '400001',
          country: 'IN'
        },
        items: [
          {
            productId: 'prod-123',
            variantId: 'var-456',
            quantity: 2,
            price: 1299.00
          }
        ],
        paymentMethod: 'upi_direct',
        paymentProofUrl: 'https://storage.supabase.co/bucket/proof.jpg'
      })
    }
  );

  const data = await response.json();
  console.log('Order created:', data.orderId);
  ```

  ```swift iOS theme={null}
  import Foundation

  struct CreateOrderRequest: Codable {
      let storeId: String
      let buyerEmail: String
      let buyerName: String
      let buyerPhone: String
      let shippingAddress: ShippingAddress
      let items: [OrderItem]
      let paymentMethod: String
      let paymentProofUrl: String?
  }

  let request = CreateOrderRequest(
      storeId: "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
      buyerEmail: "customer@example.com",
      buyerName: "John Doe",
      buyerPhone: "+919876543210",
      shippingAddress: ShippingAddress(
          line1: "123 Main Street",
          line2: "Apt 4B",
          city: "Mumbai",
          state: "Maharashtra",
          postalCode: "400001",
          country: "IN"
      ),
      items: [
          OrderItem(
              productId: "prod-123",
              variantId: "var-456",
              quantity: 2,
              price: 1299.00
          )
      ],
      paymentMethod: "upi_direct",
      paymentProofUrl: "https://storage.supabase.co/bucket/proof.jpg"
  )

  let response = try await supabase.functions.invoke(
      "create-order",
      options: FunctionInvokeOptions(body: request)
  )

  let order = try JSONDecoder().decode(OrderResponse.self, from: response.data)
  print("Order created: \(order.orderId)")
  ```

  ```bash cURL theme={null}
  curl -X POST https://your-project.supabase.co/functions/v1/create-order \
    -H "Authorization: Bearer YOUR_ANON_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "storeId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
      "buyerEmail": "customer@example.com",
      "buyerName": "John Doe",
      "buyerPhone": "+919876543210",
      "shippingAddress": {
        "line1": "123 Main Street",
        "line2": "Apt 4B",
        "city": "Mumbai",
        "state": "Maharashtra",
        "postalCode": "400001",
        "country": "IN"
      },
      "items": [
        {
          "productId": "prod-123",
          "variantId": "var-456",
          "quantity": 2,
          "price": 1299.00
        }
      ],
      "paymentMethod": "upi_direct",
      "paymentProofUrl": "https://storage.supabase.co/bucket/proof.jpg"
    }'
  ```
</CodeGroup>

## Example Response

```json theme={null}
{
  "success": true,
  "orderId": "ord-789-xyz",
  "orderNumber": "ORD-2024-001234",
  "totalAmount": 2598.00,
  "checkoutFee": 0.00,
  "finalAmount": 2598.00,
  "status": "payment_pending"
}
```

## Status Codes

<ResponseField name="200" type="Success">
  Order created successfully
</ResponseField>

<ResponseField name="400" type="Bad Request">
  Invalid request body or missing required fields
</ResponseField>

<ResponseField name="401" type="Unauthorized">
  Invalid or missing authorization token
</ResponseField>

<ResponseField name="404" type="Not Found">
  Store or product not found
</ResponseField>

<ResponseField name="500" type="Server Error">
  Internal server error
</ResponseField>

## Business Logic

<AccordionGroup>
  <Accordion title="Checkout Fee Calculation">
    **UPI Direct**: 0% fee (2% discount offered)

    **Razorpay**: 2-3% fee depending on payment method

    * Credit/Debit Card: 2.5%
    * UPI via Razorpay: 2%
    * Wallets: 2%

    The fee is added to `totalAmount` to calculate `finalAmount`.
  </Accordion>

  <Accordion title="Email Notifications">
    Two emails are sent automatically:

    1. **Buyer Confirmation Email**
       * Order summary with items
       * Shipping address
       * Payment method
       * Order tracking link

    2. **Seller Notification Email**
       * New order alert
       * Customer details
       * Items to fulfill
       * Payment proof (if UPI Direct)
  </Accordion>

  <Accordion title="Order Status Lifecycle">
    ```
    payment_pending → paid → processing → shipped → delivered
                       ↓
                   cancelled (any time before shipped)
    ```

    * **payment\_pending**: Order created, awaiting payment confirmation
    * **paid**: Payment verified (auto for Razorpay, manual for UPI)
    * **processing**: Seller is preparing the order
    * **shipped**: Order dispatched with tracking
    * **delivered**: Order received by customer
    * **cancelled**: Order cancelled by seller or customer
  </Accordion>
</AccordionGroup>

## Error Handling

<CodeGroup>
  ```typescript TypeScript theme={null}
  try {
    const response = await createOrder(orderData);

    if (!response.success) {
      throw new Error('Order creation failed');
    }

    console.log('Order created:', response.orderId);
  } catch (error) {
    if (error.message.includes('Invalid store')) {
      alert('Store not found. Please try again.');
    } else if (error.message.includes('Product not available')) {
      alert('One or more products are out of stock.');
    } else {
      alert('Something went wrong. Please contact support.');
    }
  }
  ```

  ```swift iOS theme={null}
  do {
      let order = try await OrderService.create(request)
      print("Order created: \(order.id)")
  } catch let error as APIError {
      switch error {
      case .invalidStore:
          showAlert("Store not found")
      case .productUnavailable:
          showAlert("Product out of stock")
      default:
          showAlert("Something went wrong")
      }
  }
  ```
</CodeGroup>

<Info>
  **Need help?** Check out the [Order Management Guide](/seller/order-fulfillment) or reach out on [GitHub Discussions](https://github.com/unfinished-bizness/getpopup-store/discussions)
</Info>
