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

# Release Payment Request

> Release or cancel a payment request that is no longer needed

# Overview

Release or cancel a payment request that is no longer needed. This endpoint allows you to free up resources and prevent further processing of payment requests that should not be completed.

## API Endpoint

```
GET /payment-requests/release/{id}
```

## Authentication

* **HTTP Header**: `X-API-Key` with your API key obtained from the dashboard
* **Content Type**: `application/json`

## Path Parameters

| Parameter | Description                           | Type            | Required |
| --------- | ------------------------------------- | --------------- | -------- |
| `id`      | Payment request identifier to release | integer (int64) | YES      |

## Use Cases

### Order Cancellation

* **Customer Cancellation**: Customer cancels order before payment
* **Inventory Issues**: Product out of stock after payment request created
* **Pricing Errors**: Incorrect pricing requires payment request cancellation
* **Duplicate Orders**: Remove duplicate payment requests

### System Management

* **Expired Requests**: Clean up expired payment requests
* **Failed Validation**: Release requests that fail business validation
* **Maintenance**: System maintenance requiring payment request cleanup
* **Resource Management**: Free up system resources

## Response

Returns release confirmation including:

### Release Information

* **Status**: Release operation status
* **Released At**: Timestamp when request was released
* **Reason**: Release reason (if provided)
* **Refund Status**: Refund processing status (if payment was captured)

### Impact Assessment

* **Transactions Affected**: List of related transactions
* **Refunds Initiated**: Automatic refunds triggered
* **Notifications Sent**: Customer notifications dispatched

## Example Request

```bash theme={null}
curl -X GET \
  "https://apay.caibo.digital/payment-requests/release/12345" \
  -H "X-API-Key: your-api-key" \
  -H "Content-Type: application/json"
```

## Example Response

```json theme={null}
{
  "status": "released",
  "paymentRequestId": 12345,
  "releasedAt": "2024-01-15T10:45:00Z",
  "previousStatus": "pending",
  "reason": "Customer cancellation",
  "impact": {
    "transactionsAffected": [],
    "refundsInitiated": [],
    "notificationsSent": [
      {
        "type": "customer_notification",
        "recipient": "customer@example.com",
        "status": "sent"
      },
      {
        "type": "merchant_notification", 
        "recipient": "merchant@example.com",
        "status": "sent"
      }
    ]
  },
  "metadata": {
    "originalAmount": 100.50,
    "currency": "USD",
    "createdAt": "2024-01-15T10:30:00Z"
  }
}
```

## Response Status Codes

| Code  | Description                                                       |
| ----- | ----------------------------------------------------------------- |
| `200` | OK - Payment request released successfully                        |
| `400` | Bad Request - Invalid request format                              |
| `404` | Not Found - Payment request not found                             |
| `409` | Conflict - Payment request cannot be released (already processed) |
| `500` | Internal Server Error - Release operation failed                  |

## Error Response Examples

### Payment Request Not Found

```json theme={null}
{
  "error": {
    "code": "PAYMENT_REQUEST_NOT_FOUND",
    "message": "Payment request with ID 12345 not found",
    "details": {
      "requestId": "req_abc123",
      "timestamp": "2024-01-15T10:45:00Z"
    }
  }
}
```

### Cannot Release Processed Payment

```json theme={null}
{
  "error": {
    "code": "PAYMENT_ALREADY_PROCESSED",
    "message": "Cannot release payment request that has already been processed",
    "details": {
      "currentStatus": "completed",
      "transactionId": "txn_def456",
      "processedAt": "2024-01-15T10:35:00Z"
    }
  }
}
```

### Release Operation Failed

```json theme={null}
{
  "error": {
    "code": "RELEASE_OPERATION_FAILED",
    "message": "Failed to release payment request due to system error",
    "details": {
      "retryAfter": 300,
      "supportReference": "SUP-789123"
    }
  }
}
```

## Release States and Conditions

### Releasable States

* **Pending**: Payment request created but not processed
* **Waiting**: Awaiting customer action
* **Expired**: Payment request has expired
* **Failed**: Payment processing failed

### Non-Releasable States

* **Processing**: Payment currently being processed
* **Completed**: Payment successfully completed
* **Refunded**: Payment already refunded
* **Cancelled**: Payment request already cancelled

## Implementation Examples

### JavaScript/Node.js

```javascript theme={null}
async function releasePaymentRequest(paymentId, apiKey, reason = null) {
  try {
    const response = await fetch(
      `https://apay.caibo.digital/payment-requests/release/${paymentId}`,
      {
        method: 'GET',
        headers: {
          'X-API-Key': apiKey,
          'Content-Type': 'application/json'
        }
      }
    );
    
    if (!response.ok) {
      const error = await response.json();
      throw new Error(`Release failed: ${error.message}`);
    }
    
    const result = await response.json();
    
    // Log release confirmation
    console.log(`Payment request ${paymentId} released successfully`);
    console.log('Release details:', result);
    
    // Handle notifications
    if (result.impact.notificationsSent.length > 0) {
      console.log('Notifications sent:', result.impact.notificationsSent);
    }
    
    return result;
    
  } catch (error) {
    console.error('Error releasing payment request:', error);
    throw error;
  }
}

// Usage examples
await releasePaymentRequest(12345, 'your-api-key');
```

### Batch Release Operations

```javascript theme={null}
async function batchReleasePaymentRequests(paymentIds, apiKey) {
  const results = [];
  const errors = [];
  
  for (const paymentId of paymentIds) {
    try {
      const result = await releasePaymentRequest(paymentId, apiKey);
      results.push({ paymentId, status: 'released', result });
    } catch (error) {
      errors.push({ paymentId, status: 'failed', error: error.message });
    }
  }
  
  return { 
    successful: results, 
    failed: errors,
    summary: {
      total: paymentIds.length,
      released: results.length,
      failed: errors.length
    }
  };
}

// Usage
const paymentIds = [12345, 12346, 12347];
const batchResult = await batchReleasePaymentRequests(paymentIds, 'your-api-key');
console.log('Batch release summary:', batchResult.summary);
```

### PHP Implementation

```php theme={null}
<?php
function releasePaymentRequest($paymentId, $apiKey) {
    $url = "https://apay.caibo.digital/payment-requests/release/" . $paymentId;
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'X-API-Key: ' . $apiKey,
        'Content-Type: application/json'
    ]);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($httpCode === 200) {
        return json_decode($response, true);
    } else {
        $error = json_decode($response, true);
        throw new Exception("Release failed: " . $error['error']['message']);
    }
}

// Usage
try {
    $result = releasePaymentRequest(12345, 'your-api-key');
    echo "Payment request released: " . $result['status'];
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}
?>
```

## Integration Patterns

### Order Management Integration

```javascript theme={null}
class OrderManager {
  async cancelOrder(orderId, reason) {
    try {
      // Get payment request ID from order
      const order = await this.getOrder(orderId);
      
      if (order.paymentRequestId) {
        // Release payment request
        await releasePaymentRequest(order.paymentRequestId, this.apiKey);
      }
      
      // Update order status
      await this.updateOrderStatus(orderId, 'cancelled', reason);
      
      // Send customer notification
      await this.notifyCustomer(order.customerId, 'order_cancelled', {
        orderId,
        reason,
        refundInfo: 'Refund will be processed within 3-5 business days'
      });
      
    } catch (error) {
      console.error('Order cancellation failed:', error);
      throw error;
    }
  }
}
```

### Automated Cleanup

```javascript theme={null}
async function cleanupExpiredPaymentRequests(apiKey) {
  try {
    // Get expired payment requests (implement based on your system)
    const expiredRequests = await getExpiredPaymentRequests();
    
    const results = [];
    for (const request of expiredRequests) {
      try {
        await releasePaymentRequest(request.id, apiKey);
        results.push({ id: request.id, status: 'released' });
      } catch (error) {
        results.push({ id: request.id, status: 'failed', error: error.message });
      }
    }
    
    // Log cleanup results
    console.log('Cleanup completed:', {
      total: expiredRequests.length,
      released: results.filter(r => r.status === 'released').length,
      failed: results.filter(r => r.status === 'failed').length
    });
    
    return results;
  } catch (error) {
    console.error('Cleanup operation failed:', error);
    throw error;
  }
}

// Schedule cleanup (example with cron)
// 0 2 * * * node cleanup-expired-payments.js
```

## Best Practices

### When to Release

* **Order Cancellation**: Always release when orders are cancelled
* **Inventory Issues**: Release immediately when products become unavailable
* **Expired Requests**: Regularly clean up expired payment requests
* **System Maintenance**: Release pending requests before maintenance

### Error Handling

* **Retry Logic**: Implement retry for transient failures
* **Logging**: Log all release operations for audit trails
* **Monitoring**: Monitor release success rates
* **Alerting**: Alert on high failure rates

### Customer Communication

* **Immediate Notification**: Notify customers of cancellations immediately
* **Clear Messaging**: Explain why payment request was cancelled
* **Refund Timeline**: Provide clear refund expectations
* **Support Contact**: Offer support contact for questions

### System Integration

* **Order Management**: Integrate with order management systems
* **Inventory Systems**: Connect to inventory management
* **Customer Service**: Provide tools for support teams
* **Reporting**: Include release metrics in reporting

## Related Endpoints

* **[Get Payment Request](/ipg/get-payment-request)**: Retrieve payment request details
* **[Handle Payment Request](/ipg/handle-payment-request)**: Process payment with specific method
* **[Payment Status Check](/ipg/payment-status-check)**: Check payment status
* **[Create Payment Request](/ipg/payment-request)**: Create new payment requests


## OpenAPI

````yaml api GET /payment-requests/release/{id}
openapi: 3.0.4
info:
  title: FinHub API
  description: >-
    FinHub API provides services for the Caibo platform to support client's
    applications
  version: v1
servers:
  - url: https://apay.caibo.digital
    description: Caibo APay server (Test and Production share base; method IDs differ)
security: []
paths: {}

````