npm package: @hesabe-pay/direct-apple-pay
Description: Apple Pay integration library for Hesabe payment gateway
Author: salmanhesabe
Latest version: 1.0.15

# Hesabe Apple Pay Direct

A lightweight, framework-agnostic JavaScript library for Apple Pay integration through the Hesabe payment gateway. Works
with React, Vue, Angular, or vanilla JavaScript.

> Before implementing Apple Pay, make sure Hesabe allowlisted your domain in Apple and Hesabe integration settings.

## Installation

### NPM

```bash
npm i @hesabe-pay/direct-apple-pay
```

### CDN

```html

<script src="https://unpkg.com/@hesabe-pay/direct-apple-pay@latest/cdn/hesabe-apple-pay.min.js"></script>
```

## Usage

#### Steps

1. Request Checkout API in Hesabe (Follow the normal steps)
2. After decrypting the string, In response, you will get `data`, pass it as `requestData` in the `HesabeApplePay`
   constructor.
3. Initialize the library with `init()` method
4. Call `processPayment(paymentTypeId)` when user clicks your custom payment button

### CDN (Vanilla JavaScript)

#### Simplified Configuration (Recommended)

With the new automatic configuration, you only need `requestData` and `env`:

```html

<head>
    <script src="https://unpkg.com/@hesabe-pay/direct-apple-pay@latest/cdn/hesabe-apple-pay.min.js"></script>
</head>
<body>
<!-- Your custom Apple Pay button -->
<button id="apple-pay-btn" onclick="handleApplePayClick()">
    Pay with Apple Pay
</button>
</body>
<script>
    const config = {
        requestData: 'encrypted-data-from-checkout-api',
        env: 'sandbox', // or 'production'
        debug: true,
        paymentAttemptedCallback: (result) => {
            console.log('Payment result:', result);
        },
        paymentCancelledCallback: () => {
            console.log('Payment cancelled by user');
        }
    };

    const applePay = new HesabeApplePay(config);
    // Call when the app is loaded and ready to use
    applePay.init();

    // Handle button click
    function handleApplePayClick() {
        try {
            applePay.processPayment(9); // 9 is MPGS Apple Pay, may vary based on payment you enabled , refer bottom table
        } catch (error) {
            console.error('Payment error:', error.message);
        }
    }
</script>
```

---

### ES Modules (React/Vue/Angular)

#### React Example (Simplified Configuration)

```jsx
import {useEffect, useState} from 'react';
import HesabeApplePay from '@hesabe-pay/direct-apple-pay';

function ApplePayButton() {
    const [applePay, setApplePay] = useState(null);

    useEffect(() => {
        const config = {
            requestData: 'encrypted-data-from-checkout-api',
            env: 'sandbox', // or 'production'
            debug: true,
            paymentAttemptedCallback: (result) => {
                console.log('Payment result:', result);
            },
            paymentCancelledCallback: () => {
                console.log('Payment cancelled');
            }
        };

        const applePayInstance = new HesabeApplePay(config);
        try {
            // Call when the app is loaded and ready to use
            applePayInstance.init();
            setApplePay(applePayInstance);
        } catch (error) {
            console.error('Apple Pay initialization failed:', error);
        }
    }, []);

    const handleApplePayClick = () => {
        if (applePay) {
            try {
                applePay.processPayment(9); // 9 is MPGS Apple Pay, may vary based on payment you enabled , refer bottom table
            } catch (error) {
                console.error('Payment error:', error.message);
            }
        }
    };

    return (
        <div>
            <button onClick={handleApplePayClick}>
                Pay with Apple Pay
            </button>
        </div>
    );
}
```

#### Vue Example

```vue

<template>
  <div>
    <button @click="handleApplePayClick">
      Pay with Apple Pay
    </button>
  </div>
</template>

<script>
  import HesabeApplePay from '@hesabe-pay/direct-apple-pay';

  export default {
    data() {
      return {
        applePay: null
      };
    },
    async mounted() {
      const config = {
        requestData: 'encrypted-data-from-checkout-api',
        env: 'sandbox', // or 'production'
        debug: true,
        paymentAttemptedCallback: (result) => {
          console.log('Payment result:', result);
        },
        paymentCancelledCallback: () => {
          console.log('Payment cancelled');
        }
      };

      this.applePay = new HesabeApplePay(config);
      this.applePay.init();
    },
    methods: {
      handleApplePayClick() {
        if (this.applePay) {
          try {
            this.applePay.processPayment(9); // 9 is MPGS Apple Pay, may vary based on payment you enabled, refer bottom table
          } catch (error) {
            console.error('Payment error:', error.message);
          }
        }
      }
    }
  };
</script>
```

---

## Configuration

| Option                     | Type     | Required | Description                                                                   |
|----------------------------|----------|----------|-------------------------------------------------------------------------------|
| `requestData`              | string   | ✓        | `data` in decrypted response of checkout request from Hesabe checkout API     |
| `env`                      | string   | ✓        | Environment: `'sandbox'` or `'production'`                                    |
| `debug`                    | boolean  |          | Enable debug logging (default: `false`)                                       |
| `paymentAttemptedCallback` | function |          | Optional callback for successful payment. Not required if redirection is used |
| `paymentCancelledCallback` | function |          | Optional callback for payment cancellation                                    |

> **Note**: All payment configuration (token, amount, availablePaymentGateways, merchantIdentifier, currencyCode) is
> automatically fetched from the checkout details API when `requestData` is provided.

## API Methods

### `init()`

Initializes the Apple Pay SDK and sets up the library. Call this method after creating the instance.

```javascript
const applePay = new HesabeApplePay(config);

// Call when the app is loaded and ready to use
applePay.init();
```

### `processPayment(paymentTypeId)`

Processes Apple Pay payment for the specified payment type ID. This method validates the payment type and initiates the
Apple Pay flow.

```javascript
applePay.processPayment(9); // MPGS_APPLE_PAY
```

**Parameters:**

- `paymentTypeId` (number): The payment type ID from the available Apple Pay types

**Throws:**

- Error if payment type is invalid or not supported
- Error if Apple Pay is not available in the browser
- Error if payment type is not in availablePaymentGateways

### Payment Callback

You can provide an optional callback function to handle payment completion instead of browser redirection:

```javascript
paymentAttemptedCallback: (result) => {
    if (result.success) {
        // Payment was successful
        console.log('Transaction details:', result.data);
        // result.data contains the transaction enquiry response with status, amount, etc.
    } else {
        // Payment failed
        console.log('Payment error:', result.error);
    }
}
```

**Enquiry API Response Examples:**

### `result` in `paymentAttemptedCallback`

**Successful Transaction:**

```json
{
  "status": true,
  "message": "Transaction found",
  "data": {
    "data": [
      {
        "token": "<TOKEN>",
        "amount": "9.000",
        "reference_number": "<REFERENCE_NUMBER>",
        "status": "SUCCESSFUL",
        "TransactionID": "<TRANSACTION_ID>",
        "Id": "<ID>",
        "PaymentID": "<PAYMENT_ID>",
        "Terminal": "<TERMINAL_ID>",
        "TrackID": "<TRACK_ID>",
        "payment_type": "<TYPE_NAME>",
        "service_type": "<SERVICE_TYPE>",
        "customerName": "",
        "customerEmail": "",
        "customerMobile": "",
        "customerCardType": "-NA-",
        "customerCard": "-NA-",
        "datetime": "2025-02-12 16:13:58"
      }
    ]
  }
}
```

**Failed Transaction:**

```json
{
  "status": true,
  "message": "Transaction found",
  "data": {
    "data": [
      {
        "token": "<TOKEN>",
        "amount": "33.000",
        "reference_number": "<REFERENCE_NUMBER>",
        "status": "FAILED",
        "TransactionID": "<TRANSACTION_ID>",
        "Id": "<ID>",
        "PaymentID": "<PAYMENT_ID>",
        "Terminal": "<TERMINAL_ID>",
        "TrackID": "<TRACK_ID>",
        "payment_type": "<TYPE_NAME>",
        "service_type": "<SERVICE_TYPE>",
        "customerName": null,
        "customerEmail": null,
        "customerMobile": null,
        "customerCardType": "-NA-",
        "customerCard": "-NA-",
        "datetime": "2025-07-01 17:33:25"
      }
    ]
  }
}
```

**Transaction Not Found:**

```json
{
  "status": false,
  "message": "Transaction not found",
  "data": null
}
```

**Error Occured:**

```json
{
  "status": false,
  "message": "<error_message>"
}
```

### Payment Cancellation Callback

This callback is triggered when the user cancels the Apple Pay session before completing the payment.

```javascript
config.paymentCancelledCallback = () => {
    console.log('User cancelled the payment');
    // Handle cancellation logic here
}
```

## Payment Types for Apple Pay

> Make sure Apple Pay is enabled in your Hesabe account for the required payment methods.

- `MPGS_APPLE_PAY` (9) - MPGS Apple Pay
- `CYBERSOURCE_APPLE_PAY` (10) - CyberSource Apple Pay
- `KNET_DEBIT` (11) - KNET Debit cards
- `KNET_CREDIT` (12) - KNET Credit cards
- `KNET_INTERNATIONAL_APPLE_PAY` (13) - KNET International Apple Pay
- `AMEX_APPLE_PAY` (14) - American Express Apple Pay

## Testing Environment:

- Use request data from the Hesabe sandbox environment.
- Make sure environment is set to `sandbox` for testing purposes.
- Enable debug mode by setting `debug: true` in the configuration to see detailed logs in the console.

## Going Live

- Ensure you have a valid merchant enabled "Apple Pay" payment method for live account.
- Set the `env` to `production` in the configuration.
- Set the `debug` to `false` in the configuration.
- Make sure checkout request data is valid for production.
- Test thoroughly in the sandbox environment before switching to production.

## Browser Support

- Safari 11.1+
- iOS Safari 11.3+
- Other browsers with Apple Pay JS support