> For the complete documentation index, see [llms.txt](https://docs.easypay.sa/easypay/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.easypay.sa/easypay/payment-integration-guide/payment-in-app-integration.md).

# Payment In-App Integration

## Purchase

**Important:** The `amount` should be entered without decimals. For example, `100` represents `1.00 SAR`, and `1455` represents `14.55 SAR`. The maximum length is 12 digits, including the exponent (e.g., `123456789012` equals `1,234,567,890.12 SAR`).

**Reference ID:** You may pass a `Reference ID` in the `customerReferenceNumber` field to attach it to the transaction. Otherwise, set it to `null`.

### **Processing a Purchase Request Using In-App Integration**

To initiate a payment using the In-App Integration method, follow the steps below. This method leverages the `window.inAppPurchase` handler to communicate directly within Easypay app.

**Example Code:**

```javascript
// Function to make a payment using In-App Integration
async function makePaymentInApp(amount, customerReferenceNumber) {
    // Check if the In-App Purchase handler is available
    if (window.inAppEasypay) {
        const paymentData = [
            {
                method: "PURCHASE",
                amount: amount, // [Required] Amount to set (e.g., 100 represents 1.00 SAR)
                customerReferenceNumber: customerReferenceNumber || null // [Optional] Any string as a reference number
            }
        ];

        try {
            // Call the In-App Purchase handler with the payment data
            const responseJson = await window.inAppEasypay.callHandler('Purchase', ...paymentData);

            // Simplified Error Handling
            if (responseJson === "false" || responseJson === null) {
                console.error("Payment failed: Invalid response from handler.");
                // Optionally, notify the user about the failure
                return;
            } else {
                const paymentResult = JSON.parse(responseJson);

                if (paymentResult.is_approved) {
                    console.log("Payment Successful:", paymentResult);
                    // Optionally, proceed with post-payment actions
                } else {
                    console.warn("Payment Rejected:", paymentResult);
                    // Optionally, notify the user about the rejection
                }
            }
        } catch (error) {
            console.error("Exception during In-App Payment:", error);
            // Optionally, implement retry logic or notify the user
        }
    } else {
        console.error("In-App Purchase handler is not available.");
        // Optionally, fallback to WebSocket Integration or notify the user
    }
}

// Example usage:
makePaymentInApp(100, "1234");
```

Find Payment Sample Response model [here](/easypay/models.md#payment-sample-response-json)

## Refund

To process a refund, provide the `transactionUuid` of the original transaction you wish to refund.

### **Processing a Refund Using In-App Integration**

To initiate a refund using the In-App Integration method, follow the steps below. This method leverages the `window.inAppRefund` handler to communicate directly within Easpay app.

**Example Code:**

```javascript
// Function to process a refund using In-App Integration
async function processRefundInApp(transactionUuid, amount, customerReferenceNumber) {
    // Check if the In-App Refund handler is available
    if (window.inAppEasypay) {
        const refundData = [
            {
                method: "REFUND",
                transactionUuid: transactionUuid, // [Required] Original transaction UUID.
                amount: amount, // [Required] Amount to refund.
                customerReferenceNumber: customerReferenceNumber || null // [Optional] Any string as a reference number.
            }
        ];

        try {
            // Call the In-App Refund handler with the refund data
            const responseJson = await window.inAppEasypay.callHandler('Refund', ...refundData);

            // Simplified Error Handling
            if (responseJson === "false" || responseJson === null) {
                console.error("Refund failed: Invalid response from handler.");
                // Optionally, notify the user about the failure
                return;
            } else {
                const refundResult = JSON.parse(responseJson);

                if (refundResult.is_approved) {
                    console.log("Refund Successful:", refundResult);
                    // Optionally, proceed with post-refund actions
                } else {
                    console.warn("Refund Rejected:", refundResult);
                    // Optionally, notify the user about the rejection
                }
            }
        } catch (error) {
            console.error("Exception during In-App Refund:", error);
            // Optionally, implement retry logic or notify the user
        }
    } else {
        console.error("In-App Refund handler is not available.");
        // Optionally, fallback to WebSocket Integration or notify the user
    }
}

// Example usage:
processRefundInApp("f5079b9d-b61c-4180-8a4d-9780f7a9cd8f", 100, "ORDER1234");
```

Find Payment Sample Response model [here](/easypay/models.md#payment-sample-response-json)

## Reconciliation

### **Processing a** Reconcile **Using In-App Integration**

To initiate a reconciliation using the In-App Integration method, follow the steps below. This method leverages the `window.inAppRefund` handler to communicate directly within Easpay app.

**Example Code:**

```javascript
// Function to reconcile transactions using In-App Integration
async function reconcileInApp() {
    // Check if the In-App Reconcile handler is available
    if (window.inAppEasypay) {
        const data = {
            "method": "reconcile"
        };

        try {
            // Call the In-App Reconcile handler with the reconcile data
            const responseData = await window.inAppEasypay.callHandler('Reconciliation', data);

            // Simplified Error Handling
            if (responseData seJson === "false" || responseData === null) {
                console.error("Reconciliation failed: Invalid response from handler.");
                // Optionally, notify the user about the failure
                return;
            } else {
                if (responseData .is_balanced !== undefined && responseData .is_balanced.value) {
                    console.log("Reconciliation Successful:", responseData);
                    // Optionally, proceed with post-reconciliation actions
                } else {
                    console.warn("Reconciliation Failed:", responseData);
                    // Optionally, notify the user about the failure
                }
            }
        } catch (error) {
            console.error("Exception during In-App Reconciliation:", error);
            // Optionally, implement retry logic or notify the user
        }
    } else {
        console.error("In-App Reconcile handler is not available.");
        // Optionally, fallback to WebSocket Integration or notify the user
    }
}

// Example usage:
reconcileInApp();
```

## **Receipt Management**

**Printing the Last Transaction Receipt**

```javascript
// Function to print the last transaction receipt using In-App Integration
function printLastReceiptInApp() {
    // Check if the PrintLastResult handler is available
    if (window.PrintLastResult) {
        const message = JSON.stringify({ method: "PrintLastResult" });
        try {
            // Send the print request to Easypay
            window.PrintLastResult.postMessage(message);
            console.log("Print request sent to Easypay.");
        } catch (error) {
            console.error("Failed to send print request:", error);
            // Optionally, notify the user about the failure
        }
    } else {
        console.error("PrintLastResult handler is not available.");
        // Optionally, fallback to WebSocket Integration or notify the user
    }
}

// Example usage:
printLastReceiptInApp();
```

### Summary of Core Functionalities In-App Integration

<table><thead><tr><th width="248">Functionality</th><th>In-App Integration</th></tr></thead><tbody><tr><td><strong>Making a Payment</strong></td><td>- Uses <code>window.inAppPurchase.postMessage</code> with spread arguments<br>- User confirms payment via popup</td></tr><tr><td><strong>Processing a Refund</strong></td><td>- Uses <code>window.inAppRefund.postMessage</code> with spread arguments<br>- User confirms refund via popup</td></tr><tr><td><strong>Printing Last Receipt</strong></td><td>- Uses <code>window.PrintLastResult.postMessage</code><br>- User confirms print via popup</td></tr><tr><td><strong>Opening the Cash Drawer</strong></td><td>- Uses <code>window.OpenDrawer.postMessage</code><br>- User initiates drawer opening via popup</td></tr></tbody></table>
