> ## 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.

# Handle Payment Request

> Process a payment request using a specific payment method

# Overview

Process a payment request using a specific payment method. This endpoint allows you to handle payment requests with different payment methods like credit cards, digital wallets, or alternative payment options.

## API Endpoint

```
GET /payment-requests/handle/{id}/{paymentMethod}
```

## 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           | integer (int64)    | YES      |
| `paymentMethod` | Payment method to use for processing | PaymentMethod enum | YES      |

## Payment Methods

The following payment methods are supported:

| Method           | Description                | Use Case                 |
| ---------------- | -------------------------- | ------------------------ |
| `CREDIT_CARD`    | Credit/debit card payments | Standard card processing |
| `APPLE_PAY`      | Apple Pay digital wallet   | iOS/Safari payments      |
| `GOOGLE_PAY`     | Google Pay digital wallet  | Android/Chrome payments  |
| `UPI`            | Unified Payments Interface | Indian market payments   |
| `BANK_TRANSFER`  | Direct bank transfers      | ACH/wire transfers       |
| `CRYPTOCURRENCY` | Digital currency payments  | Bitcoin, Ethereum, etc.  |
| `PAYPAL`         | PayPal wallet payments     | PayPal account holders   |

## Response

Returns payment handling result including:

### Processing Information

* **Status**: Payment processing status
* **Transaction ID**: Generated transaction identifier
* **Redirect URL**: URL for customer to complete payment (if required)
* **Processing Time**: Estimated processing duration

### Payment Details

* **Method Used**: Confirmed payment method
* **Amount**: Transaction amount and currency
* **Fees**: Processing fees (if applicable)
* **Exchange Rate**: Currency conversion rate (if applicable)

## Example Request

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

## Example Response

```json theme={null}
{
  "status": "processing",
  "transactionId": "txn_abc123def456",
  "paymentMethod": "CREDIT_CARD",
  "redirectUrl": "https://secure.caibo.io/payment/complete/txn_abc123def456",
  "estimatedProcessingTime": "2-5 minutes",
  "amount": {
    "value": 100.50,
    "currency": "USD"
  },
  "fees": {
    "processingFee": 2.50,
    "currency": "USD"
  },
  "expiresAt": "2024-01-15T11:30:00Z",
  "nextSteps": {
    "action": "redirect_customer",
    "description": "Redirect customer to complete 3D Secure authentication",
    "timeout": 900
  }
}
```

## Response Status Codes

| Code  | Description                                                           |
| ----- | --------------------------------------------------------------------- |
| `200` | OK - Payment handling initiated successfully                          |
| `400` | Bad Request - Invalid payment method or request                       |
| `404` | Not Found - Payment request not found                                 |
| `422` | Unprocessable Content - Payment method not supported for this request |
| `500` | Internal Server Error - Processing error occurred                     |

## Error Response Examples

### Invalid Payment Method

```json theme={null}
{
  "error": {
    "code": "INVALID_PAYMENT_METHOD",
    "message": "Payment method 'INVALID_METHOD' is not supported",
    "supportedMethods": ["CREDIT_CARD", "APPLE_PAY", "GOOGLE_PAY", "UPI"]
  }
}
```

### Payment Request Not Found

```json theme={null}
{
  "error": {
    "code": "PAYMENT_REQUEST_NOT_FOUND",
    "message": "Payment request with ID 12345 not found or expired"
  }
}
```

### Unprocessable Payment Method

```json theme={null}
{
  "error": {
    "code": "PAYMENT_METHOD_NOT_AVAILABLE",
    "message": "APPLE_PAY is not available for this payment request",
    "reason": "Customer device does not support Apple Pay"
  }
}
```

## Payment Method Specific Handling

### Credit Card Processing

```bash theme={null}
GET /payment-requests/handle/12345/CREDIT_CARD
```

* Initiates 3D Secure authentication if required
* Returns redirect URL for card verification
* Processes payment immediately for non-3DS cards

### Digital Wallet Processing

```bash theme={null}
GET /payment-requests/handle/12345/APPLE_PAY
```

* Validates wallet availability on customer device
* Initiates biometric authentication flow
* Returns wallet-specific payment session

### UPI Processing

```bash theme={null}
GET /payment-requests/handle/12345/UPI
```

* Validates UPI ID format and availability
* Generates UPI payment link
* Supports QR code generation for mobile apps

## Implementation Examples

### JavaScript/Node.js

```javascript theme={null}
async function handlePaymentRequest(paymentId, paymentMethod, apiKey) {
  try {
    const response = await fetch(
      `https://apay.caibo.digital/payment-requests/handle/${paymentId}/${paymentMethod}`,
      {
        method: 'GET',
        headers: {
          'X-API-Key': apiKey,
          'Content-Type': 'application/json'
        }
      }
    );
    
    if (!response.ok) {
      const error = await response.json();
      throw new Error(`Payment handling failed: ${error.message}`);
    }
    
    const result = await response.json();
    
    // Handle different response types
    if (result.redirectUrl) {
      // Redirect customer to complete payment
      window.location.href = result.redirectUrl;
    } else if (result.status === 'completed') {
      // Payment completed immediately
      console.log('Payment completed:', result.transactionId);
    }
    
    return result;
    
  } catch (error) {
    console.error('Error handling payment:', error);
    throw error;
  }
}

// Usage examples
await handlePaymentRequest(12345, 'CREDIT_CARD', 'your-api-key');
await handlePaymentRequest(12345, 'APPLE_PAY', 'your-api-key');
await handlePaymentRequest(12345, 'UPI', 'your-api-key');
```

### Payment Method Selection

```javascript theme={null}
function selectPaymentMethod(availableMethods, customerPreference) {
  const methodPriority = {
    'APPLE_PAY': 1,
    'GOOGLE_PAY': 2,
    'CREDIT_CARD': 3,
    'UPI': 4,
    'BANK_TRANSFER': 5
  };
  
  // Filter available methods by customer device/preference
  const supportedMethods = availableMethods.filter(method => {
    switch (method) {
      case 'APPLE_PAY':
        return window.ApplePaySession && ApplePaySession.canMakePayments();
      case 'GOOGLE_PAY':
        return window.google && window.google.payments;
      case 'UPI':
        return customerPreference.country === 'IN';
      default:
        return true;
    }
  });
  
  // Sort by priority and return best option
  return supportedMethods.sort((a, b) => 
    methodPriority[a] - methodPriority[b]
  )[0];
}
```

## Integration Patterns

### Progressive Enhancement

1. **Start with Basic**: Begin with credit card as fallback
2. **Detect Capabilities**: Check for wallet/UPI support
3. **Offer Options**: Present available payment methods
4. **Handle Gracefully**: Fall back if preferred method fails

### Mobile Optimization

* **Wallet Priority**: Prioritize digital wallets on mobile
* **UPI for India**: Offer UPI as primary option in Indian market
* **Touch/Face ID**: Leverage biometric authentication
* **App Deep Links**: Support payment app integration

## Best Practices

### Payment Method Selection

* **Device Detection**: Choose methods based on customer device
* **Geographic Optimization**: Offer region-appropriate methods
* **Fallback Strategy**: Always provide alternative payment options
* **User Preference**: Remember customer's preferred methods

### Error Handling

* **Graceful Degradation**: Fall back to alternative methods
* **Clear Messaging**: Provide helpful error messages
* **Retry Logic**: Implement appropriate retry mechanisms
* **Support Integration**: Link to customer support for complex issues

### Security

* **Method Validation**: Verify payment method availability before processing
* **Timeout Handling**: Implement appropriate timeouts for each method
* **Fraud Detection**: Monitor for suspicious payment method patterns
* **Compliance**: Ensure compliance with payment method regulations

## Related Endpoints

* **[Get Payment Request](/ipg/get-payment-request)**: Retrieve payment request details
* **[Payment Status Check](/ipg/payment-status-check)**: Check payment status
* **[Release Payment Request](/ipg/release-payment-request)**: Release payment request
* **[Create Payment Request](/ipg/payment-request)**: Create new payment requests


## OpenAPI

````yaml api GET /payment-requests/handle/{id}/{paymentMethod}
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:
  /payment-requests/handle/{id}/{paymentMethod}:
    get:
      tags:
        - PaymentRequests
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: integer
            format: int64
        - name: paymentMethod
          in: path
          required: true
          schema:
            $ref: '#/components/schemas/PaymentMethod'
      responses:
        '200':
          description: OK
        '400':
          description: Bad Request
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ProblemDetails'
        '404':
          description: Not Found
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ProblemDetails'
        '422':
          description: Unprocessable Content
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ProblemDetails'
components:
  schemas:
    PaymentMethod:
      enum:
        - 0
        - 1
        - 2
        - 3
        - 4
        - 5
        - 6
        - 7
        - 8
        - 9
        - 10
        - 11
        - 13
        - 14
        - 15
        - 16
        - 17
        - 18
        - 19
        - 20
      type: integer
      format: int32
    ProblemDetails:
      type: object
      properties:
        type:
          type: string
          nullable: true
        title:
          type: string
          nullable: true
        status:
          type: integer
          format: int32
          nullable: true
        detail:
          type: string
          nullable: true
        instance:
          type: string
          nullable: true
      additionalProperties: {}

````