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

# Cancel Order

> Cancel an order with a specified reason

## Overview

Cancels an order at any status (except already completed/canceled) with a mandatory cancellation reason.

## Path Parameters

<ParamField path="order_id" type="string" required>
  Order's `payment_key` (UUID)
</ParamField>

## Headers

<ParamField header="Access-Token" type="string" required>
  Your API access token
</ParamField>

<ParamField header="Content-Type" type="string" required>
  Must be `application/json`
</ParamField>

## Body Parameters

<ParamField body="reason_id" type="integer" required>
  Cancellation reason ID (1-8) - see [Cancel Reasons](/api-reference/orders/cancel-reasons)
</ParamField>

## Cancel Reasons

| ID | Reason                                              |
| -- | --------------------------------------------------- |
| 1  | Ürün tükendi (Product out of stock)                 |
| 2  | Adres bulunamıyor (Address not found)               |
| 3  | Yoğunluk nedeniyle (Due to congestion)              |
| 4  | Müşteri iptal etti (Customer canceled)              |
| 5  | Teknik sorun (Technical issue)                      |
| 6  | Çok uzak teslimat adresi (Delivery address too far) |
| 7  | Ödeme problemi (Payment problem)                    |
| 8  | Diğer (Other)                                       |

## Response

<ResponseField name="status" type="boolean">
  `true` if successful
</ResponseField>

<ResponseField name="data" type="string">
  `"OK"` on success
</ResponseField>

## Examples

<CodeGroup>
  ```bash cURL theme={null}
  curl -X PUT https://www.xn--dkkango-n2a.com/api/integrations/orders/cancel/3e9caf87-5cb7-4c4e-adcb-fc2ec54cf24e \
    -H 'Access-Token: your-access-token' \
    -H 'Content-Type: application/json' \
    -d '{"reason_id": 3}'
  ```

  ```javascript JavaScript theme={null}
  const paymentKey = '3e9caf87-5cb7-4c4e-adcb-fc2ec54cf24e';

  const response = await fetch(
    `https://www.xn--dkkango-n2a.com/api/integrations/orders/cancel/${paymentKey}`,
    {
      method: 'PUT',
      headers: {
        'Access-Token': 'your-access-token',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        reason_id: 3  // Due to congestion
      })
    }
  );

  const data = await response.json();
  // Order is now CANCELED
  ```

  ```python Python theme={null}
  import requests

  payment_key = '3e9caf87-5cb7-4c4e-adcb-fc2ec54cf24e'

  response = requests.put(
      f'https://www.xn--dkkango-n2a.com/api/integrations/orders/cancel/{payment_key}',
      headers={
          'Access-Token': 'your-access-token',
          'Content-Type': 'application/json'
      },
      json={'reason_id': 3}  # Due to congestion
  )

  data = response.json()
  # Order is now CANCELED
  ```

  ```php PHP theme={null}
  <?php
  $paymentKey = '3e9caf87-5cb7-4c4e-adcb-fc2ec54cf24e';
  $url = "https://www.xn--dkkango-n2a.com/api/integrations/orders/cancel/{$paymentKey}";

  $data = json_encode(['reason_id' => 3]); // Due to congestion

  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
  curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_HTTPHEADER, array(
      'Access-Token: your-access-token',
      'Content-Type: application/json'
  ));
  $response = curl_exec($ch);
  curl_close($ch);
  // Order is now CANCELED
  ?>
  ```
</CodeGroup>

## Success Response (200)

```json theme={null}
{
  "status": true,
  "data": "OK"
}
```

## Error Responses

<ResponseExample>
  ```json Missing Field (422) theme={null}
  {
    "status": false,
    "error": "eksik alan",
    "message": "reason_id is required"
  }
  ```

  ```json Invalid Reason (422) theme={null}
  {
    "status": false,
    "error": "eksik alan",
    "message": "Invalid reason_id"
  }
  ```

  ```json Authentication Error (401) theme={null}
  {
    "status": false,
    "error": "yetkisiz erişim"
  }
  ```

  ```json Not Found (404) theme={null}
  {
    "status": false,
    "error": "sipariş bulunamadı"
  }
  ```
</ResponseExample>

## When to Cancel

<AccordionGroup>
  <Accordion title="1. Product Out of Stock (reason_id: 1)">
    Key ingredient or menu item is unavailable.

    ```javascript theme={null}
    async function cancelOutOfStock(order, missingItem) {
      await cancelOrder(order.payment_key, 1);
      
      await notifyCustomer(
        order.customer.phone,
        `Sorry, ${missingItem} is out of stock. Order canceled.`
      );
      
      // Deactivate item to prevent future orders
      await deactivateFood(missingItem.id);
    }
    ```
  </Accordion>

  <Accordion title="2. Address Not Found (reason_id: 2)">
    Delivery address is invalid or cannot be located.

    ```javascript theme={null}
    async function cancelInvalidAddress(order) {
      await cancelOrder(order.payment_key, 2);
      
      await requestAddressCorrection(order.customer.phone);
    }
    ```
  </Accordion>

  <Accordion title="3. Too Busy (reason_id: 3)">
    Restaurant is overwhelmed and cannot fulfill order.

    ```javascript theme={null}
    async function cancelDueToBusyness(order) {
      await cancelOrder(order.payment_key, 3);
      
      // Consider closing restaurant temporarily
      const activeOrders = await getActiveOrderCount();
      if (activeOrders > 20) {
        await closeRestaurant(restaurantId);
      }
    }
    ```
  </Accordion>

  <Accordion title="4. Customer Canceled (reason_id: 4)">
    Customer requested cancellation.

    ```javascript theme={null}
    async function handleCustomerCancellation(order) {
      const confirmed = await confirmWithStaff(
        `Customer wants to cancel order ${order.id}. Proceed?`
      );
      
      if (confirmed) {
        await cancelOrder(order.payment_key, 4);
      }
    }
    ```
  </Accordion>

  <Accordion title="5. Technical Issue (reason_id: 5)">
    POS system or equipment failure.

    ```javascript theme={null}
    async function cancelTechnical(order, issue) {
      await cancelOrder(order.payment_key, 5);
      
      await logTechnicalIssue({
        orderId: order.id,
        issue: issue,
        timestamp: new Date()
      });
      
      await notifyTechSupport(issue);
    }
    ```
  </Accordion>

  <Accordion title="6. Address Too Far (reason_id: 6)">
    Delivery address is outside service area.

    ```javascript theme={null}
    async function cancelTooFar(order) {
      const distance = await calculateDistance(
        restaurantAddress,
        order.address
      );
      
      if (distance > MAX_DELIVERY_DISTANCE) {
        await cancelOrder(order.payment_key, 6);
        
        await notifyCustomer(
          order.customer.phone,
          'Sorry, your address is outside our delivery area.'
        );
      }
    }
    ```
  </Accordion>

  <Accordion title="7. Payment Problem (reason_id: 7)">
    Payment verification failed.

    ```javascript theme={null}
    async function cancelPaymentIssue(order) {
      await cancelOrder(order.payment_key, 7);
      
      await requestPaymentUpdate(order.customer.phone);
    }
    ```
  </Accordion>

  <Accordion title="8. Other (reason_id: 8)">
    Any other reason not covered above.

    ```javascript theme={null}
    async function cancelOther(order, customReason) {
      await cancelOrder(order.payment_key, 8);
      
      await logCancellationReason(order.id, customReason);
    }
    ```
  </Accordion>
</AccordionGroup>

## Status Transition

```
ANY STATUS (except COMPLETE/CANCELED)
    ↓
[/orders/cancel called]
    ↓
CANCELED (status_id: 6)
```

## Complete Workflow

```javascript theme={null}
class OrderCancellation {
  async cancel(order, reasonId, additionalNotes = '') {
    try {
      // 1. Validate reason
      if (reasonId < 1 || reasonId > 8) {
        throw new Error('Invalid reason_id');
      }
      
      // 2. Confirm with staff
      const confirmed = await this.confirmCancellation(order, reasonId);
      if (!confirmed) return false;
      
      // 3. Call API
      await this.cancelOrder(order.payment_key, reasonId);
      
      // 4. Update local database
      await database.updateOrderStatus(order.id, 'CANCELED');
      await database.logCancellation({
        orderId: order.id,
        reasonId: reasonId,
        notes: additionalNotes,
        canceledBy: currentUser.id,
        timestamp: new Date()
      });
      
      // 5. Notify stakeholders
      await this.notifyCustomer(order);
      await this.notifyKitchen(order);
      
      // 6. Process refund (if applicable)
      if (order.payment_type === 'CREDIT_CARD') {
        await this.processRefund(order);
      }
      
      // 7. Update metrics
      analytics.track('order_canceled', {
        orderId: order.id,
        reasonId: reasonId,
        orderValue: order.total
      });
      
      return true;
      
    } catch (error) {
      console.error('Cancellation failed:', error);
      throw error;
    }
  }
}
```

## Best Practices

<Tabs>
  <Tab title="Always Use Correct Reason">
    ```javascript theme={null}
    // ✅ Good: Use specific reason
    await cancelOrder(order.payment_key, 1); // Out of stock

    // ❌ Bad: Always using "Other"
    await cancelOrder(order.payment_key, 8); // Don't default to "Other"
    ```
  </Tab>

  <Tab title="Confirm Before Canceling">
    ```javascript theme={null}
    async function safeCancelOrder(order, reasonId) {
      const reason = getCancelReasonText(reasonId);
      
      const confirmed = await confirmDialog(
        'Cancel Order?',
        `Order: ${order.id}\nReason: ${reason}\n\nThis cannot be undone.`
      );
      
      if (confirmed) {
        await cancelOrder(order.payment_key, reasonId);
      }
    }
    ```
  </Tab>

  <Tab title="Notify Customer">
    ```javascript theme={null}
    async function cancelWithNotification(order, reasonId) {
      await cancelOrder(order.payment_key, reasonId);
      
      const message = getCancellationMessage(reasonId);
      await sendSMS(order.customer.phone, message);
    }
    ```
  </Tab>
</Tabs>

## Related Endpoints

<CardGroup cols={2}>
  <Card title="Get Cancel Reasons" icon="list" href="/api-reference/orders/cancel-reasons">
    Fetch available cancellation reasons
  </Card>

  <Card title="Get Current Orders" icon="shopping-cart" href="/api-reference/orders/get-current">
    View orders to cancel
  </Card>
</CardGroup>
