# Drop-in Web

## Introduction

The embedded checkout supports embedding PayKKa's checkout payment component into your checkout page to collect consumer payment information.

You can create your own checkout flow through the PayKKa Checkout UI component. The payment information entered by consumers is only transmitted within the component, which can reduce your PCI-DSS compliance costs.

To integrate Component/Drop-in, you need to provide your domain name to remove cross-origin restrictions

## Supported Payment Methods

- Visa
- MasterCard
- JCB
- American Express
- Discover
- Diners Club
- Apple Pay
- Google Pay
- WechatPay
- Alipay+
- Alipay
- AlipayHK
- GCash
- Maya (Paymaya)
- ShopeePay
- GrabPay
- Zalopay
- VietQR


## Payment Process

1. Customers visit your checkout page, enter customer shipping and billing information, and click the payment button
2. You initiate a payment request from the server to create a checkout, and you will receive the checkout ID(session_id) for loading the checkout page later
3. You use the checkout ID(`session_id`) and Client key(`client_key`) to load the embedded checkout page within the current page
4. The embedded checkout page will dynamically display supported payment methods. After the customer selects a payment method, click the payment button
5. After submitting the payment, we will process all possible additional operations, such as 3DS authentication or third-party redirect pages
6. After the payment is processed, the component callback function will be triggered, and you can handle the payment result here (the component callback function supports multiple callback events, it is recommended to at least integrate onSuccess, onExpired, onError events)
7. Your webhook address will receive the payment result notification (it is recommended that you integrate transaction query to get the payment result)


## Integration Process

1. Get your transaction key
2. Get your Client key
3. Prepare your notification webhook address, provide it in the request parameters or set in the background, and notifications will be sent to the merchant at key payment nodes
4. Prepare your redirect address, provide it in the request parameters, and it will redirect after checkout payment is completed
5. Initiate the request: [Create Session](/payments/apis/payments/openapi/session/session-opl_1) interface to create checkout, return checkout page URL
6. For frontend component integration method, see [PayKKa Checkout UI Component](/payments/docs/developer-resources/checkout-ui-component)
7. Merchants can integrate the [Query Session](/payments/apis/payments/openapi/session/session-query-opl_2) interface to get checkout results, or directly integrate the [Query Transaction](/payments/apis/payments/openapi/transaction/payments-query-opl_1) interface to get order results (if there is no final result, it means the consumer did not initiate a transaction)


PayKKa's checkout(identifier:session_id) represents a payment intention in page form, and the final payment result is determined by the transaction(identifier: `order_id` ) result. Therefore, you need to focus on the final status of the order to determine the payment result.

Checkout Query: Used to query the status and payment result of the checkout. If the consumer has not initiated payment, no transaction order will be generated.

Transaction Query: Used to query the payment result of the transaction order. After the order reaches its final state, it will be notified through webhook.

Default component style

### Create Checkout

When the customer is ready to pay, send a server-side request to create a Session and corresponding link, and initiate a payment request through the Session

Request Example
[Create Session](/payments/apis/payments/openapi/session/session-opl_1)

```json
{
  "merchant_id": "YOUR_MERCHANT_ID",
  "payment_type": "PURCHASE",
  "authorisation_type": "FINAL_AUTH",
  "capture_method": "AUTOMATIC",
  "trans_id": "m3246749195217",
  "expire_time": "2025-05-05T17:17:24+08:00",
  "session_mode": "DROP_IN",  # Checkout mode, HOSTED: hosted, DROP_IN: embedded, COMPONENT: component
  "display_locale": "fr-FR",
  "currency": "HKD",
  "amount": "800",
  "return_url": "https://url", 
  "payment": {
    "store_payment_method": true,  # Whether to store card information and tokenize, will get token; true: store, false: do not store
    "token_usage": "CARD_ON_FILE" 
    "shopper_reference": "854f5baaf0a735139c583c4cea14d14c" 
  },
  "goods": [
    // Product information
  ],
  "bill": {
    // Billing information
  },
  "shipping": {
    // Shipping information, required for physical goods
  },
  "customer": {
    // Consumer/customer information
  }
}
```

Response Example

```json
{
    "ret_code": "000000",
    "ret_msg": "Success",
    "data": {
        "merchant_id": "YOUR_MERCHANT_ID",
        "trans_id": "m3246749195217",
        "session_id": "CS_order_id",
        "session_mode": "DROP_IN",
        "status": "PROCESSING",
        "currency": "HKD",
        "amount": "800",
        "expire_time": "2025-05-05T17:17:24+08:00",
        "authorisation_type": "FINAL_AUTH",
        "capture_method": "AUTOMATIC"
    }
}
```

### Adding Drop-in

You can install the PayKKa Checkout UI npm package or embed it into HTML via CDN:

npm (Recommended)
Install `@paykka/card-checkout-ui`:

npm
```bash
npm i @paykka/card-checkout-ui
```

pnpm
```bash
pnpm i @paykka/card-checkout-ui
```

yarn
```bash
yarn add @paykka/card-checkout-ui
```

To properly display the component, you need to import the styles globally:

```typescript
import '@paykka/card-checkout-ui/style.css'
```

CDN Import
Import PayKKa Checkout UI styles and scripts in HTML via CDN links. It is recommended to use the CDN link for the corresponding region:

Europe
```html
<link href="https://checkout.eu.paykka.com/cp/style.css" rel="stylesheet" />
<script src="https://checkout.eu.paykka.com/cp/card-checkout-ui.js"></script>
```

Hong Kong
```html
<link href="https://checkout.aq.paykka.com/cp/style.css" rel="stylesheet" />
<script src="https://checkout.aq.paykka.com/cp/card-checkout-ui.js"></script>
```

Sandbox
```html
<link href="https://checkout-sandbox.aq.paykka.com/cp/style.css" rel="stylesheet"/>
<script src="https://checkout-sandbox.aq.paykka.com/cp/card-checkout-ui.js"></script>
```

#### Creating a PayKKaCheckout Instance

##### PayKKaCheckout Constructor Parameters

Parameters and events that can be passed when creating a `PayKKaCheckout` instance:

Required parameters are marked with *.

| **Name**  | **Description**  | **Type**  |
|  --- | --- | --- |
| *sessionId | Checkout ID, used to create the checkout. | `string` |
| *clientKey | Client key. | `string` |
| *env | Environment configuration.- `eu` for European merchants.
- `hk` for Hong Kong merchants.
- `sandbox` for sandbox environment merchants.

 |  |
| locale | Checkout text display language.- If not provided, browser language will be used. If browser language is not supported, `en-GB` will be used by default.
- Currently supports the following 11 international languages, displayed in IETF BCP 47 format:
  - `de-DE`: German (Germany)
  - `en-GB`: English (United Kingdom)
  - `es-ES`: Spanish (Spain)
  - `fr-FR`: French (France)
  - `ja-JP`: Japanese (Japan)
  - `ko-KR`: Korean (South Korea)
  - `pt-PT`: Portuguese (Portugal)
  - `ru-RU`: Russian (Russia)
  - `zh-CN`: Chinese (China)
  - `zh-HK`: Chinese (Hong Kong)
  - `zh-TW`: Chinese (Taiwan)

 | `string` |
| hidePaymentButton | Whether to hide the payment button, defaults to `false`.- If the payment button is hidden, you need to manually call the component's `payment` method to make a payment.

 | `boolean` |
| threeDSFrame | 3DS configuration object, containing the following parameters:- `modalWidth`: 3DS popup width, defaults to adaptive if not provided. Pass `number` for units in `px`, pass `string` for custom units, minimum width is `350px`.
- `modalHeight`: 3DS popup height, defaults to adaptive if not provided. Pass `number` for units in `px`, pass `string` for custom units, minimum height is `500px`.

 | `ThreeDSFrameConfig` |
| onPaymentMethodsReady | Triggered when the checkout has obtained available payment methods.- `methods` is the list of available payment methods.
- If an empty array is returned, it means no payment methods are available, and the component will not be displayed.
- When the checkout status is success or expired, an empty array will also be returned.
- Currently supports the following 8 payment methods:
  - `APPLE_PAY`: Apple Pay
  - `GOOGLE_PAY`: Google Pay
  - `VISA`: Visa
  - `MASTER_CARD`: Master Card
  - `JCB`: JCB
  - `AMEX`: AMEX
  - `DINERS_CLUB`: Diners Club
  - `DISCOVER`: Discover

 | `(methods: PaymentMethod[]) => void` |
| onInitError | Triggered when checkout initialization fails.- `error` is a `PayKKaError` instance, typically containing the following properties:
  - `type`: Error type.
  - `message`: Error message.
  - `code`: Error code, when an API error occurs, it will return a specific [error code](#error-codes).
- This callback will also be triggered when reinitializing after checkout status is success or expired.

 | `(error: PayKKaError) => void` |
| onSubmit | **Global event** triggered when submitting the form.- `formValidateError` is the form validation error information.
- Can be overridden by the same-named event defined in the Component.

 | `(formValidateError?: Record<string, FormValidateError[]>) => void` |
| onSuccess | **Global event** triggered after successful payment.- `returnUrl` is the link to redirect to after payment is completed.
- Can be overridden by the same-named event defined in the Component.

 | `({returnUrl?: string}) => void` |
| onTimeout | **Global event** triggered when payment times out.- Users can resubmit the form to make a payment.
- Can be overridden by the same-named event defined in the Component.

 | `() => void` |
| onExpired | **Global event** triggered when the session expires or becomes invalid, or when the component is called again after successful payment.- Can be overridden by the same-named event defined in the Component.

 | `() => void` |
| onError | **Global event** triggered after payment failure.- `error` is a `PayKKaError` instance, typically containing the following properties:
  - `type`: Error type.
  - `message`: Error message.
  - `code`: Error code, when an API error occurs, it will return a specific [error code](#error-codes).
- Users can resubmit the form to make a payment.
- Can be overridden by the same-named event defined in the Component.

 | `(error: PayKKaError) => void` |


Here's a usage example:

npm
```javascript
import { PayKKaCheckout } from '@paykka/card-checkout-ui'
// Create PayKKaCheckout instance
const paykkaCheckout = new PayKKaCheckout({
  sessionId: 'xxx',
  clientKey: 'xxx',
  env: 'hk',
  locale: 'en-GB',
  hidePaymentButton: false,
  threeDSFrame: {
    modalWidth: '350px',
    modalHeight: '500px',
  },
  onPaymentMethodsReady: (methods) => {
    console.log('Supported payment methods', methods)
  },
  onInitError: (error) => {
    console.log('Initialization error', error)
  },
  onSubmit: (formValidateError) => {
    console.log('Form submission global event', formValidateError)
  },
  onSuccess: ({ returnUrl }) => {
    console.log('Payment success global event', returnUrl)
  },
  onTimeout: () => {
    console.log('Payment timeout global event')
  },
  onExpired: () => {
    console.log('Session expired or invalid global event')
  },
  onError: () => {
    console.log('Payment failure global event')
  }
})

// Wait for the checkout to finish initialization before performing subsequent operations
paykkaCheckout.init().then(() => {
  // ...subsequent operations
})
```

CDN
```javascript
const { PayKKaCheckout } = PayKKaCardCheckoutUI
// Create PayKKaCheckout instance
const paykkaCheckout = new PayKKaCheckout({
  sessionId: 'xxx',
  clientKey: 'xxx',
  env: 'hk',
  locale: 'en-GB',
  hidePaymentButton: false,
  threeDSFrame: {
    modalWidth: '350px',
    modalHeight: '500px',
  },
  onPaymentMethodsReady: (methods) => {
    console.log('Supported payment methods', methods)
  },
  onInitError: (error) => {
    console.log('Initialization error', error)
  },
  onSubmit: (formValidateError) => {
    console.log('Form submission global event', formValidateError)
  },
  onSuccess: ({ returnUrl }) => {
    console.log('Payment success global event', returnUrl)
  },
  onTimeout: () => {
    console.log('Payment timeout global event')
  },
  onExpired: () => {
    console.log('Session expired or invalid global event')
  },
  onError: () => {
    console.log('Payment failure global event')
  }
})

// Wait for the checkout to finish initialization before performing subsequent operations
paykkaCheckout.init().then(() => {
  // ...subsequent operations
})
```

#### Creating a Drop-in Instance

##### Drop-in Constructor Parameters

Parameters and events that can be passed when creating a `DropIn` instance:

| Name  | Description  | Type  |
|  --- | --- | --- |
| paymentMethods | Parameters for building various payment methods. The final displayed payment methods are determined by the checkout creation request response, not by this parameter. Contains the following properties:- `card`: Card component construction parameters.
- `applePay`: ApplePay component construction parameters.
- `googlePay`: GooglePay component construction parameters.

 | `PaymentMethodsConfig` |
| layout | Layout, `accordion` indicates using accordion layout. Tab-switching layout is not currently supported. | `'accordion'` |
| onSubmit | Event triggered when submitting the form.- `formValidateError` is the form validation error information.

 | `(formValidateError?: Record<string, FormValidateError[]>) => void` |
| onSuccess | Event triggered after successful payment.- `returnUrl` is the link to redirect to after payment is completed.

 | `({returnUrl?: string}) => void` |
| onTimeout | Event triggered when payment times out.- Users can resubmit the form to make a payment.

 | `() => void` |
| onExpired | Event triggered when the session expires or becomes invalid, or when the component is called again after successful payment. | `() => void` |
| onError | Event triggered after payment failure.- `error` is a `PayKKaError` instance, typically containing the following properties:
  - `type`: Error type.
  - `message`: Error message.
  - `code`: Error code, when an API error occurs, it will return a specific [error code](#error-codes).
- Users can resubmit the form to make a payment.

 | `(error: PayKKaError) => void` |


##### Step 1: Create DOM Element

Create a DOM element in your checkout page that will be used to render the Drop-in.

```html
<div id="drop-in-container"></div>
```

It is strongly recommended not to create this DOM element inside an iframe element, as this may prevent the checkout from functioning properly.

##### Step 2: Import DropIn and Create Instance

```javascript
import { PayKKaCheckout, DropIn } from '@paykka/card-checkout-ui'

// Steps to create PayKKaCheckout instance omitted here

const checkoutDropIn = paykkaCheckout.create(DropIn, {
  paymentMethods: {
    card: {
      /** Card component constructor parameters */
    },
    applePay: {
      /** ：ApplePay component constructor parameters */
    },
    googlePay: {
      /** ：GooglePay component constructor parameters */
    }
  },
  layout: 'accordion',
  onSubmit: formValidateError => {
    console.log('Form submission event', formValidateError)
  },
  onSuccess: ({ returnUrl }) => {
    console.log('Payment success event', returnUrl)
  },
  onTimeout: () => {
    console.log('Payment timeout event')
  },
  onExpired: () => {
    console.log('Session expired or invalid event')
  },
  onError: () => {
    console.log('Payment failure event')
  }
})
```

##### Step 3: Mount Component

```javascript
const container = document.querySelector('#drop-in-container')
checkoutDropIn.mount(container)
```

If you are using JavaScript frameworks such as Angular, Vue, React, etc., please ensure that the DOM has been rendered before mounting, and do not re-render the element.

### Checkout Query

Query checkout status by checkout ID(`session_id`)

Request Example
[Query Session](/payments/apis/payments/openapi/session/session-query-opl_2)

```json
{
  "merchant_id": "YOUR_MERCHANT_ID",
  "trans_id": "m3246749195217",  # trans_id/session_id two choose one
  "session_id": "CS_order_id"
}
```

Response Example

Processing
```json
{
  "ret_code": "000000",
  "ret_msg": "Success",
  "data": {
    "merchant_id": "YOUR_MERCHANT_ID",
    "trans_id": "m3246749195217",
    "session_id": "CS_order_id",
    "session_mode": "DROP_IN",
    "status": "PROCESSING",
    "amount": "800",
    "currency": "HKD",
    "expire_time": "2025-05-05T17:17:24+08:00",
    "authorisation_type": "FINAL_AUTH",
    "capture_method": "AUTOMATIC"
  }
}
```

Success
```json
{
  "ret_code": "000000",
  "ret_msg": "Success",
  "data": {
    "merchant_id": "YOUR_MERCHANT_ID",
    "trans_id": "m3246749195217",
    "session_id": "CS_order_id",
    "session_mode": "DROP_IN",
    "status": "SUCCESS",  # Checkout status
    "order_status": "SUCCESS",  # Transaction status
    "error_code": "0000", # Transaction error code
    "error_description": "request success",
    "order_id": "GW_order_id", # Transaction order number
    "amount": "800",
    "currency": "HKD",
    "expire_time": "2025-05-05T17:17:24+08:00",
    "authorisation_type": "FINAL_AUTH",
    "capture_method": "AUTOMATIC"
  }
}
```

Expired
```json
Payment not initiated before expiration
{
  "ret_code": "000000",
  "ret_msg": "Success",
  "data": {
    "merchant_id": "YOUR_MERCHANT_ID",
    "trans_id": "m3246749195217",
    "session_id": "CS_order_id",
    "session_mode": "DROP_IN",
    "status": "EXPIRED",  # Checkout status
    "amount": "800",
    "currency": "HKD",
    "expire_time": "2025-05-05T17:17:24+08:00"
  }
}

Payment failed
{
  "ret_code": "000000",
  "ret_msg": "Success",
  "data": {
    "merchant_id": "YOUR_MERCHANT_ID",
    "trans_id": "m3246749195217",
    "session_id": "CS_order_id",
    "session_mode": "DROP_IN",
    "status": "EXPIRED",  # Checkout status
    "amount": "800",
    "currency": "HKD",
    "order_status": "FAILURE",  # Transaction status
    "error_code": "0000", # Transaction error code
    "error_description": "request success",
    "order_id": "GW_order_id", # Transaction order number
    "expire_time": "2025-05-05T17:17:24+08:00"
  }
}
```

### Transaction Query

Query transaction status by transaction ID(`order_id`)

Request Example
[Query Transaction](/payments/apis/payments/openapi/transaction/payments-query-opl_1)

```json
{
  "merchant_id": "YOUR_MERCHANT_ID",
  "trans_id": "m3246749195217",    # session_id/order_id/trans_id three choose one
  "session_id": "CS_order_id",
  "order_id": "GW_order_id"
}
```

Response Example

```json
{
  "ret_code": "000000",
  "ret_msg": "Success",
  "data": {
    "merchant_id": "YOUR_MERCHANT_ID",
    "trans_id": "m3246749195217",
    "order_id": "GW_order_id",
    "session_id": "CS_order_id",
    "status": "SUCCESS", # Transaction status
    "error_code": "0000", # Transaction error code
    "error_description": "request success",
    "amount": "800",
    "currency": "HKD",
    "pay_finish_time": "2025-05-05T17:17:24+08:00"
  }
}
```

## Purchase and Recurring

If your payment requirements involve recurring charges from customers' bank cards or e-wallets at regular intervals (such as monthly, yearly, or custom time intervals) without requiring manual authorization each time, you can use PayKKa's recurring payment feature.

### Integration Method

1. Currently, PayKKa's recurring payment feature requires the merchant to initiate it periodically
2. For the first recurring payment, PayKKa needs to store the card information of the cardholder, and subsequent recurring payments only need to provide the cardholder's token
3. For subsequent recurring payments, only the cardholder's token needs to be provided, without repeating card information


First recurring request example
[Create Session](/payments/apis/payments/openapi/session/session-opl_1)

```json
{
  "merchant_id": "YOUR_MERCHANT_ID",
  "payment_type": "RECURRING",
  "authorisation_type": "FINAL_AUTH",
  "capture_method": "AUTOMATIC",
  "trans_id": "m3246749195217",
  "expire_time": "2025-05-05T17:17:24+08:00",
  "session_mode": "COMPONENT",
  "display_locale": "fr-FR",
  "currency": "HKD",
  "amount": "800",
  "return_url": "https://url",
  "mit": false,
  "payment": {
    "store_payment_method": true,
    "token_usage": "SUBSCRIPTION",
    "shopper_reference": "854f5baaf0a735139c583c4cea14d14c"
  },
  "goods": [
    // Product information
  ],
  "bill": {
    // Billing information
  },
  "shipping": {
    // Shipping information, required for physical goods
  },
  "customer": {
    // Consumer/customer information
  }
}
```

Subsequent recurring request example
[Initiate Transaction](/payments/apis/payments/openapi/transaction/payments-opl_1)

```json
{
  "merchant_id": "YOUR_MERCHANT_ID",
  "payment_type": "RECURRING",
  "authorisation_type": "FINAL_AUTH",
  "capture_method": "AUTOMATIC",
  "trans_id": "m3246749195217",
  "currency": "HKD",
  "amount": "800",
  "mit": true,
  "recurring_agreement_id": "RA4264524535435435",
  "payment": {
    "payment_method": "BANKCARD",
    "shopper_reference": "558b5cb1b8cbcc8496062155c69cf2ab",
    "token": "TK20231435132143229"
  }
}
```

## 3DS Processing

The checkout product does not require you to handle 3DS authentication. PayKKa will automatically perform intelligent security detection and processing of payments. You only need to focus on the payment results.

## Validity Period

The maximum validity period for the checkout is 24 hours. After expiration, payment cannot be continued. The Drop-in component will receive the callback event `onExpired`, and you can prompt the user that the payment has expired and guide the user to initiate payment again in this event.

If payment is not initiated before expiration, there will be no notification. Querying the checkout status will return `status=EXPIRED`, and querying the transaction status will return `ret_msg=the order doesn't exist`

## Error Code

See [Transaction Error Code](/payments/docs/developer-resources/transaction-error-code)

## Result Notification

Reference [Webhook](/payments/docs/developer-resources/webhook)