﻿# Create Subscription

After customers select a plan, you can create a subscription using the corresponding `priceId` and activate the service for the customer once the activation conditions are met.

This article describes the complete integration flow for creating a subscription, including obtaining the Price ID, calling the create subscription API, activating the subscription plan, obtaining the activation result, and handling subsequent automatic deductions.

## 1. Before You Start

Please complete the following preparations:

- Products and prices for subscriptions have been configured in the PayerMax Merchant Backend, and the corresponding `priceId` has been obtained (refer to the "Product and Price Management" document);

- The customer to whom this subscription belongs has been determined and can be associated with a user or organization in your system (i.e., `userId` in the API);

- Server-side authentication information (`appId`, `merchantNo`, signing keys, etc.) is ready;

- Callback notifications for subscription status and deduction results have been integrated, and the latest subscription status can be obtained through the query API;

- If the first subscription requires immediate deduction, the corresponding payment/checkout flow is ready.

The selected price should be applicable to recurring billing scenarios. Before creation, please confirm that its amount, currency, billing cycle, and sellable status are consistent with the customer's selection.

## 2. Integration Flow Overview

Creating a subscription is generally divided into three stages: **Create Product and Price**, **Initial Payment (Create and Activate)**, and **Subsequent Automatic Deductions**.

```mermaid
%%{init: {
  'theme': 'base',
  'themeVariables': {
    'primaryColor': '#e6f0ff',
    'primaryTextColor': '#333',
    'primaryBorderColor': '#5b9bd5',
    'lineColor': '#888',
    'actorMargin': 40,
    'noteBkgColor': '#0056b3',
    'noteTextColor': '#ffffff',
    'noteBorderColor': '#004a99'
  }
}}%%
sequenceDiagram
    participant User as User
    participant MServer as Merchant Server
    participant PM as PayerMax

    rect rgb(235, 245, 255)
        Note over User, PM: Create Product and Price
        MServer->>PM: 1. Create product and price in the Merchant Management Platform
        PM-->>MServer: Obtain Price ID
    end

    rect rgb(235, 245, 255)
        Note over User, PM: Initial Payment
        User->>MServer: 1. User confirms the subscription plan and initiates a payment request
        MServer->>PM: 2. Merchant initiates a create subscription plan request to PayerMax (specify Price ID and quantity)
        PM-->>MServer: Return Subscription ID
        MServer->>PM: 3. Activate subscription
        PM-->>MServer: PayerMax completes payment or binding and returns payment and binding success information
        MServer->>User: 4. Notify user of payment or binding success; subscription plan activated successfully
    end

    rect rgb(235, 245, 255)
        Note over User, PM: Subsequent Payments
        PM->>MServer: 1. PayerMax periodically deducts payment according to the subscription plan and returns payment success information
        MServer->>User: 2. Notify user of payment success
    end
```

| Step                            | Description                                                                                                             |
| ------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
| 1. Obtain Price ID              | Determine the corresponding `priceId` based on the plan and billing cycle selected by the customer                      |
| 2. Create Subscription          | Call the create subscription API, passing `priceId`, `quantity`, customer information, etc.                             |
| 3. Activate Subscription        | Guide the user to complete the initial payment/card binding, changing the subscription plan from `INACTIVE` to `ACTIVE` |
| 4. Obtain Activation Result     | Confirm whether activation is successful through a synchronous response or asynchronous callback                        |
| 5. Handle Subsequent Deductions | Receive automatic deduction notifications periodically initiated by PayerMax and maintain user service entitlements     |

## 3. Create Product and Price

Display plans and billing cycles on your website or app, and associate each purchasable option with a Price ID created in PayerMax.

For example, the same "Pro" product can have two prices:

| Customer Selection   | Price Used           |
| -------------------- | -------------------- |
| Pro, monthly payment | Pro Monthly Price ID |
| Pro, annual payment  | Pro Annual Price ID  |

Please use the **Price ID** corresponding to the selected option, not the Product ID. The product identifies the purchase content, and the price identifies the charging rules used for this subscription.

## 4. Create Subscription Plan

>Call the create subscription API (`subscriptionCreate`), and pass the customer-selected `priceId` and `quantity` in `data.subscriptionPlan.prices`.

- Production environment: https://pay-gate.payermax.com/aggregate-pay/api/gateway/subscriptionCreate

- Test environment: https://pay-gate-uat.payermax.com/aggregate-pay/api/gateway/subscriptionCreate

### 4.1 API Request

#### 4.1.1 Create a Regular Subscription Plan

Specify the `prices` configuration in the input object `subscriptionPlan`.

```json
{
  "version": "1.5",
  "keyVersion": "1",
  "requestTime": "2025-02-26T05:00:00+00:00",
  "appId": "<your-app-id>",
  "merchantNo": "<your-merchant-no>",
  "data": {
    "callbackUrl": "https://your-domain.com/notify/subscription",
    "language": "en",
    "subscriptionRequestId": "subReqId_20250226_0001",
    "userId": "user_10001",
    "subscriptionPlan": {
      "description": "Pro Plan Monthly Subscription",
      "subject": "Pro Plan",
      "totalPeriods": 24,
      "prices": [
        {
          "priceId": "PRICE0008177683958028904930003",
          "quantity": 1
        }
      ]
    }
  }
}
```

#### 4.1.2 Create a Trial Period Subscription Plan

Specify the `trialConfig+prices` configuration in the input object `subscriptionPlan`.

```json
{
  "version": "1.5",
  "keyVersion": "1",
  "requestTime": "2025-02-26T05:00:00+00:00",
  "appId": "<your-app-id>",
  "merchantNo": "<your-merchant-no>",
  "data": {
    "callbackUrl": "https://your-domain.com/notify/subscription",
    "language": "en",
    "subscriptionRequestId": "subReqId_20250226_0001",
    "userId": "user_10001",
    "subscriptionPlan": {
      "description": "Pro Plan Monthly Subscription",
      "subject": "Pro Plan",
      "totalPeriods": 24,
      "prices": [
        {
          "priceId": "PRICE0008177683958028904930003",
          "quantity": 2
        }
      ],
      "trialConfig": {
        "trialDays": 3,
        "trialAmount": {
          "amount": 0,
          "currency": "SAR"
        }
      }
    }
  }
}
```

#### 4.1.3 Create a Discount Period Subscription Plan

Specify the `trialPeriodConfig+prices` configuration in the input object `subscriptionPlan`.

```json
{
  "version": "1.5",
  "keyVersion": "1",
  "requestTime": "2025-02-26T05:00:00+00:00",
  "appId": "<your-app-id>",
  "merchantNo": "<your-merchant-no>",
  "data": {
    "callbackUrl": "https://your-domain.com/notify/subscription",
    "language": "en",
    "subscriptionRequestId": "subReqId_20250226_0001",
    "userId": "user_10001",
    "subscriptionPlan": {
      "description": "Pro Plan Monthly Subscription",
      "subject": "Pro Plan",
      "totalPeriods": 24,
      "prices": [
        {
          "priceId": "PRICE0008177683958028904930003",
          "quantity": 2
        }
      ],
      "trialPeriodConfig": {
        "trialPeriodCount": 1,
        "trialPeriodAmount": {
          "amount": 10,
          "currency": "SAR"
        }
      }
    }
  }
}
```

#### 4.1.4 Create a Trial + Discount Period Subscription Plan

Specify the `trialConfig` and `trialPeriodConfig+prices` configurations in the input object `subscriptionPlan`.

```json
{
  "version": "1.5",
  "keyVersion": "1",
  "requestTime": "2025-02-26T05:00:00+00:00",
  "appId": "<your-app-id>",
  "merchantNo": "<your-merchant-no>",
  "data": {
    "callbackUrl": "https://your-domain.com/notify/subscription",
    "language": "en",
    "subscriptionRequestId": "subReqId_20250226_0001",
    "userId": "user_10001",
    "subscriptionPlan": {
      "description": "Pro Plan Monthly Subscription",
      "subject": "Pro Plan",
      "totalPeriods": 24,
      "prices": [
        {
          "priceId": "PRICE0008177683958028904930003",
          "quantity": 2
        }
      ],
      "trialConfig": {
        "trialDays": 3,
        "trialAmount": {
          "amount": 0,
          "currency": "SAR"
        }
      },
      "trialPeriodConfig": {
        "trialPeriodCount": 1,
        "trialPeriodAmount": {
          "amount": 10,
          "currency": "SAR"
        }
      }
    }
  }
}
```

#### 4.1.5 Per-Seat Subscription

`quantity` represents the purchased quantity, i.e., the number of seats.

For per-seat subscriptions:

- `trialAmount` represents the amount of the entire order during the trial period, and is no longer multiplied by the number of seats.

- `trialPeriodAmount` represents the amount of the entire order during the discount period, and is no longer multiplied by the number of seats.

- The normal billing cycle is calculated as "price per seat × number of seats".

```json
{
  "version": "1.5",
  "keyVersion": "1",
  "requestTime": "2025-02-26T05:00:00+00:00",
  "appId": "<your-app-id>",
  "merchantNo": "<your-merchant-no>",
  "data": {
    "callbackUrl": "https://your-domain.com/notify/subscription",
    "language": "en",
    "subscriptionRequestId": "subReqId_20250226_0001",
    "userId": "user_10001",
    "subscriptionPlan": {
      "description": "Pro Plan Monthly Subscription",
      "subject": "Pro Plan",
      "totalPeriods": 24,
      "prices": [
        {
          "priceId": "PRICE0008177683958028904930003",
          "quantity": 5  // 按固定金额订阅，quantity指定为 1 即可；按席位订阅，quantity指定为对应的席位数量
        }
      ]
    }
  }
}
```

The above example indicates that the user subscribes to `price_pro_monthly` and purchases 5 seats.

`quantity` should meet the following requirements:

- Only positive integers are supported;

- The minimum value is `1`, and the maximum value is `9999`;

- Currently only applicable to recurring Prices.

If `quantity` is a decimal, zero, negative, or exceeds the allowed range, the API will return a parameter error.

### 4.2 API Response

`periodRule` and `periodAmount` are calculated and returned by the API based on the selected `priceId` and `quantity`. They are only used to confirm the billing result; the creation request itself does not need to pass these two fields.

**Response Example:**

```json
{
    "msg": "",
    "code": "APPLY_SUCCESS",
    "data": {
        "subscriptionRequestId": "subReqId_20250226_0001",
        "subscriptionPlan": {
            "subject": "Pro Plan",
            "description": "Pro Plan Monthly Subscription",
            "totalPeriods": 24,
            "subscriptionStatus": "INACTIVE",
            "subscriptionNo": "SUB261029024910886889000001A04",
            "periodRule": {
                "periodCount": 1,
                "periodUnit": "M"
            },
            "periodAmount": {
                "amount": 40.00,
                "currency": "SAR"
            },
            "prices": [
                {
                    "priceId": "PRICE0008177683958028904930003",
                    "quantity": 2
                }
            ],
            "trialConfig": {
                "trialDays": 3,
                "trialAmount": {
                    "amount": 0,
                    "currency": "SAR"
                }
            },
            "trialPeriodConfig": {
                "trialPeriodCount": 1,
                "trialPeriodAmount": {
                    "amount": 10,
                    "currency": "SAR"
                }
            }
        }
    }
}
```

## 5. Activate Subscription Plan

After the subscription plan is created, its status is `INACTIVE`, and you need to guide the user to complete activation:

- For subscriptions that require an initial payment, guide the user to complete the payment to trigger activation;

- For subscriptions that require binding a payment method (such as card binding) before deduction, guide the user to complete the binding to trigger activation.

**Activation Time Limit:**

- The user should complete activation within **24 hours** after the subscription is created.

- Subscription plans that are still not activated after 24 hours will automatically enter the `EXPIRED` status, and PayerMax will send an `EXPIRED` status notification to `callbackUrl`. The subscription plan can no longer be activated. If the user still needs to subscribe, they should be guided to create a new one.

PayerMax provides three activation integration modes: `Hosted Checkout Mode`, `Drop-in Component Mode`, and `API Mode` to complete the initial payment or authorization. For detailed descriptions of activation API fields, please refer to the official API documentation. Merchants can choose different integration modes based on integration cost and experience requirements. The supported modes vary slightly by payment method, but all ultimately complete activation through the `orderAndPay` API. The request addresses for each mode are as follows:

- **Prod Request URL**: https://pay-gate.payermax.com/aggregate-pay/api/gateway/orderAndPay

- **Test Request URL**: https://pay-gate-uat.payermax.com/aggregate-pay/api/gateway/orderAndPay

Regardless of the payment method or integration mode used, the following rules must be followed when calling the activation API (`orderAndPay`):

| Field                           | Rule                                                                                                                                                                                                                                                                                                                       |
| ------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| subscriptionPlan.subscriptionNo | Required. Use the subscription number returned by the create subscription API.                                                                                                                                                                                                                                             |
| totalAmount                     | Must match the amount for the corresponding period in the subscription plan:          • For trial period subscriptions, pass the trial period amount;          • For discount period subscriptions, pass the discount period amount;          • For regular subscriptions, pass the normal deduction amount per period. |
| currency                        | Must match the currency of the subscription plan                                                                                                                                                                                                                                                                           |
| userId                          | Must match the userId of the subscription plan                                                                                                                                                                                                                                                                             |
| subject                         | Must match the subject of the subscription plan                                                                                                                                                                                                                                                                            |
| paymentDetail.mitType           | Required. Fixed value SCHEDULED (recurring merchant-initiated transaction scenario).                                                                                                                                                                                                                                       |
| paymentDetail.tokenForFutureUse | Required. Fixed value true, used to generate the paymentTokenID required for subsequent deductions.                                                                                                                                                                                                                        |
| paymentDetail.merchantInitiated | Required. In the activation scenario, the fixed value is false, indicating that the user is involved and this is not initiated by the merchant.                                                                                                                                                                            |

>If any of the above fields is inconsistent with the subscription plan, activation will fail.

### 5.1 Card Activation for Subscription Plan

#### 5.1.1 Hosted Checkout Mode

The user is redirected to the PayerMax Checkout to enter card information and complete 3DS verification. PayerMax handles the entire payment interaction. For detailed descriptions of API request fields, please refer to [Casher payment - Order API](https://docs.payermax.com/api.html?docName=New%20Version&docVer=v1.0&docLang=cn#/paths/aggregate-pay-api-gateway-orderAndPay/post).

```mermaid
%%{init: {
  'theme': 'base',
  'themeVariables': {
    'primaryColor': '#e6f0ff',
    'primaryTextColor': '#333',
    'primaryBorderColor': '#5b9bd5',
    'lineColor': '#888',
    'actorMargin': 40,
    'noteBkgColor': '#0056b3',
    'noteTextColor': '#ffffff',
    'noteBorderColor': '#004a99'
  }
}}%%
sequenceDiagram
    participant Client as Merchant Client
    participant MServer as Merchant Server
    participant Checkout as PayerMax Checkout
    participant PMServer as PayerMax Server

    %% 1. Order and Plan Initialization
    Client->>MServer: 1.1 Select subscription product and place order
    MServer->>PMServer: 1.2 Create subscription plan
    PMServer-->>MServer: 1.3 Return subscription number
    MServer->>PMServer: 1.4 Activate subscription plan
    PMServer-->>MServer: 1.5 Return PayerMax Checkout URL
    MServer-->>Client: 1.6 Return Checkout URL

    %% 2. Checkout Interaction and Payment
    Client->>Checkout: 2.1 Redirect to PayerMax Checkout
    Checkout->>Checkout: 2.2 User enters subscription payment details
    Checkout->>PMServer: 2.3 Obtain 3DS challenge URL
    PMServer-->>Checkout: 2.4 Return 3DS challenge
    Checkout->>Checkout: 2.5 User completes 3DS challenge
    Checkout->>PMServer: 2.6 Confirm subscription/payment
    PMServer-->>Checkout: 2.7 Return payment result
    Checkout-->>Client: 2.8 Redirect to merchant subscription result page

    %% 3. Asynchronous Notification
    PMServer->>MServer: 3.1 Asynchronously notify merchant of subscription result and payment result
    MServer-->>PMServer: 3.2 Merchant responds that the result was received successfully
```

orderAndPay Request Example:

```json
{
  "version": "1.5",
  "keyVersion": "1",
  "requestTime": "2022-01-17T09:05:52.194+00:00",
  "appId": "<your-app-id>",
  "merchantNo": "<your-merchant-no>",
  "data": {
    "outTradeNo": "APIFOXDEV1745388079422", // Merchant order unique number
    "subject": "Subscription plan title", // Keep consistent with the subscription plan subject
    "totalAmount": 10, // Keep consistent with the subscription amount: [n-day trial] amount is the trial period amount; [first n periods discount] amount is the discount period amount; [regular subscription] amount is the deduction amount per period
    "currency": "USD", // Keep consistent with the subscription currency
    "userId": "test1111", // Keep consistent with the subscription plan userId
    "language": "en",
    "reference": "test subscription",
    "frontCallbackUrl": "https://[your domain name]/[your callback URL]",
    "notifyUrl": "https://[your domain name]/[your notify URL]",
    "integrate": "Hosted_Checkout", // Fixed value during activation: Hosted_Checkout
    "expireTime": "1800",
    "subscriptionPlan": { // Subscription information
        "subscriptionNo": "SUB250226033538900000020A04" // Subscription number to be activated
    },
    "paymentDetail": {
      "paymentMethodType": "CARD", // Optional during activation; value can be CARD

      "mitType": "SCHEDULED", // Required. MIT type. SCHEDULED for recurring deductions, UNSCHEDULED for non-recurring deductions.
      "tokenForFutureUse": true, // Required. Value true, generates paymentTokenID for subsequent deductions.
      "merchantInitiated": false, // Required. false indicates it is not initiated by the merchant and the user is involved; true indicates it is initiated by the merchant and no user involvement is required.
      "buyerInfo": {
          "firstName": "Dxxh",
          "lastName": "Swxx",
          "email": "buyer@example.com",
          "phoneNo": "123456",
          "address": "Test Address",
          "city": "Holden Hill",
          "region": "SA",
          "zipCode": "5088",
          "clientIp": "<buyer-client-ip>",
          "userAgent": "Mozilla/5.0"
      }
    }
  }
}
```

orderAndPay Response Example:

```json
{
    "msg": "Success.",
    "code": "APPLY_SUCCESS",
    "data": {
        "redirectUrl": "https://cashier-n-uat.payermax.com/...",
        "outTradeNo": "ORDER20250117090552001",
        "tradeToken": "T2025011709052902000001",
        "status": "PENDING"
    }
}
```

>When `status` is `PENDING`, guide the user to visit `redirectUrl` to complete the subsequent payment; the final result is subject to the asynchronous notification or query API.

#### 5.1.2 API Mode

The merchant directly collects card information and calls `orderAndPay`. PayerMax returns the 3DS challenge URL as needed.

```mermaid
%%{init: {
  'theme': 'base',
  'themeVariables': {
    'primaryColor': '#e6f0ff',
    'primaryTextColor': '#333',
    'primaryBorderColor': '#5b9bd5',
    'lineColor': '#888',
    'actorMargin': 40,
    'noteBkgColor': '#0056b3',
    'noteTextColor': '#ffffff',
    'noteBorderColor': '#004a99'
  }
}}%%
sequenceDiagram
    participant Client as Merchant Client
    participant MServer as Merchant Server
    participant H5 as PayerMax H5
    participant PMServer as PayerMax Server

    %% 1. Order and Plan Activation
    Client->>MServer: 1.1 Select subscription product and place order
    MServer->>PMServer: 1.2 Create subscription plan
    PMServer-->>MServer: 1.3 Return subscription number
    MServer->>PMServer: 1.4 Activate subscription plan
    PMServer-->>MServer: 1.5 Return 3DS challenge URL
    MServer-->>Client: 1.6 Return 3DS challenge URL

    %% 2. 3DS Challenge and Payment
    Client->>H5: 2.1 Redirect to 3DS challenge page
    H5->>H5: 2.2 User completes 3DS challenge
    H5->>PMServer: 2.3 3DS passed, complete payment
    PMServer-->>H5: 2.4 Return payment result
    H5-->>Client: 2.5 Redirect to merchant subscription result page

    %% 3. Result Notification
    PMServer->>MServer: 3.1 Asynchronously notify merchant of subscription result and payment result
    MServer-->>PMServer: 3.2 Merchant responds that the result was received successfully
```

orderAndPay Request Example:

```json
{
  "version": "1.5",
  "keyVersion": "1",
  "requestTime": "2022-01-17T09:05:52.194+00:00",
  "appId": "bbd8d2639a7c4dfd8df7d005294390df",
  "merchantNo": "020113838535952",
  "data": {
    "outTradeNo": "APIFOXDEV1745388079422", // Merchant order unique number
    "subject": "Subscription plan title", // Keep consistent with the subscription plan subject
    "totalAmount": 10, // Keep consistent with the subscription amount: [n-day trial] amount is the trial period amount; [first n periods discount] amount is the discount period amount; [regular subscription] amount is the deduction amount per period
    "currency": "USD", // Keep consistent with the subscription currency
    "userId": "test1111", // Keep consistent with the subscription plan userId
    "language": "en",
    "reference": "test subscription",
    "frontCallbackUrl": "https://[your domain name]/[your callback URL]",
    "notifyUrl": "https://[your domain name]/[your notify URL]",
    "integrate": "Direct_Payment", // Fixed value during activation: Direct_Payment
    "expireTime": "1800",
    "subscriptionPlan": { // Subscription information
        "subscriptionNo": "SUB25022603353890000002003" // Subscription number to be activated
    },
    "terminalType": "WEB", // Terminal type: WEB, WAP or APP
    "osType": "ANDROID", // Operating system type: ANDROID or IOS
    "paymentDetail": {
      "paymentMethodType": "CARD", // Required. Value CARD.
      "mitType": "SCHEDULED", // Required. MIT type. SCHEDULED for recurring subscriptions, UNSCHEDULED for non-recurring deductions.
      "tokenForFutureUse": true, // Required. Value true, generates paymentTokenID for subsequent deductions.
      "merchantInitiated": false, // false indicates user parameters are required; true indicates merchant-initiated deduction without user involvement.
      "cardInfo": { // Required. Card information.
        "cardIdentifierNo": "4001563861135570",
        "cardHolderFullName": "James Smith",
        "cardExpirationMonth": "05",
        "cardExpirationYear": "25",
        "cvv": "123"
      },
      "buyerInfo": {
        "firstName": "Deborah",
        "lastName": "Swinstead",
        "email": "your@gmail.com",
        "phoneNo": "0609 031 114",
        "address": "Test Address",
        "city": "Holden Hill",
        "region": "SA",
        "zipCode": "5088",
        "clientIp": "211.52.321.225",
        "userAgent": "Mozilla/5.0"
        }
      }
    }
}
```

orderAndPay Response Example:

```json
{
    "msg": "Success.",
    "code": "APPLY_SUCCESS",
    "data": {
        // 3DS challenge page URL
        "redirectUrl": "https://cashier-n-uat.payermax.com/static/processApiV2.html?tradeToken=T2025042306527802000033&integrate=DIRECT_API&country=UN&payRequestNo=20250423060120EP4366527897000250005&merchantId=010213834784554&merchantAppId=6666c8b036a24579974497c2f9a33333&token=902170aeaadb4621af8d9530398d0efa&orderLan=en&countryLan=en&strategyLan=LUBCO&pmaxLinkV=1",
        "outTradeNo": "APIFOXDEV1745388079422",
        "tradeToken": "T2025042306527802000033",
        "status": "PENDING"
    }
}
```

#### 5.1.3 Drop-in Component Mode

The merchant embeds the PayerMax-provided frontend component in its own page to collect card information, and calls the API in two steps: first apply for a component session, then carry the session information to call the activation API.

```mermaid
%%{init: {
  'theme': 'base',
  'themeVariables': {
    'primaryColor': '#e6f0ff',
    'primaryTextColor': '#333',
    'primaryBorderColor': '#5b9bd5',
    'lineColor': '#888',
    'actorMargin': 40,
    'noteBkgColor': '#0056b3',
    'noteTextColor': '#ffffff',
    'noteBorderColor': '#004a99'
  }
}}%%
sequenceDiagram
    participant Client as Merchant Client
    participant MServer as Merchant Server
    participant H5 as PayerMax H5
    participant PMServer as PayerMax Server

    %% 1. Initialization and Obtain Token
    Client->>MServer: 1.1 Obtain component information
    MServer->>PMServer: 1.2 Request applyDropinSession
    PMServer-->>MServer: 1.3 Return clientKey and sessionKey
    MServer-->>Client: 1.4 Return clientKey and sessionKey
    Client->>Client: 1.5 Render component and call canMakePayment to obtain payment Token

    %% 2. Create and Activate Subscription
    Client->>MServer: 2.1 User selects subscription product and places order
    MServer->>PMServer: 2.2 Create subscription plan, call createSubscription
    PMServer-->>MServer: 2.3 Return subscription number
    MServer->>PMServer: 2.4 Activate subscription plan, call orderAndPay
    PMServer-->>MServer: 2.5 Return 3DS challenge page URL
    MServer-->>Client: 2.6 Return 3DS challenge page URL

    %% 3. 3DS Challenge and Redirect
    Client->>H5: 3. Redirect to 3DS challenge page
    H5->>H5: 3.1 User completes 3DS challenge
    H5->>PMServer: 3.2 3DS passed, complete payment
    PMServer-->>H5: 3.3 Return payment result
    H5-->>Client: 3.4 Redirect to merchant result page

    %% 4. Asynchronous Notification
    PMServer->>MServer: 4.1 Asynchronously notify merchant of subscription result and payment result
    MServer-->>PMServer: 4.2 Merchant responds that the result was received successfully
```

**Step 1: Apply for Drop-in Component Session**

- Prod Request URL: https://pay-gate.payermax.com/aggregate-pay/api/gateway/applyDropinSession

- Test Request URL: https://pay-gate-uat.payermax.com/aggregate-pay/api/gateway/applyDropinSession

applyDropinSession Request Example:

```json
{
  "version": "1.5",
  "keyVersion": "1",
  "requestTime": "2022-01-17T09:05:52.194+00:00",
  "appId": "3b242b56a8b64274bcc37dac281120e3",
  "merchantNo": "020213827212251",
  "data": {
    "totalAmount": "10", // Keep consistent with the subscription amount: for [n-day trial] and [n-day trial + first n periods discount], the amount is the trial period amount; for [first n periods discount], the amount is the discount period amount; for [regular subscription], the amount is the deduction amount per period; can also be left blank
    "mitType": "SCHEDULED", // Required. When PayerMax manages the subscription plan, the value is SCHEDULED.
    "currency": "USD", // Required
    "country": "SA", // Optional
    "userId": "U10001", // Required. User ID.
    "componentList": [ // Required. Payment methods supported by the component.
      "CARD"
    ]
  }
}
```

applyDropinSession Response Example:

```json
{
  "code": "APPLY_SUCCESS",
  "msg": "Success.",
  "data": {
    "clientKey": "37114858239eur2384237r810482390",
    "sessionKey": "bdsf8982348974hhf82934bf8239424"
  }
}
```

**Step 2: Render Component && Obtain paymentToken**

The frontend code example is as follows:

```javascript

// Initialize card component
const card = PMdropin.create('card', {
  clientKey: "Client Public Key", 
  sessionKey: "Session Token", 
  sandbox: false, 
  hideSaveCard: false, 
  hideCardBrands: false, 
});
// Mount instance
card.mount('.frame-card'); // Will mount to the first matched DOM element
// Component load completion timing
card.on('ready', () => {
    // Remove custom loading               
})

card.on('form-check', (res) => {
  // res.isFormValid is the form status. Values are false/true
  // true means form validation passed and payment can be made; false means validation failed, payment cannot be made, and the payment button cannot be clicked.
  console.log('[dropin][form-check]:', res)
})

// User clicks the payment button to submit payment
function goPay(){
    card.emit('setDisabled', true) // Freeze the form after clicking the payment button to prevent duplicate payment submissions
    card.emit('canMakePayment')
      .then(res => {
        if (res.code === 'APPLY_SUCCESS') {
          const paymentToken = res.data.paymentToken // Payment token, used for payment API
          // Call PayerMax createSubscription API to create a subscription plan
           createSubscription()
          
          // Initiate payment API
          // Merchant requests their own backend API to place an order, 
          // Merchant constructs request parameters using params, must include paymentToken
            _postapi('orderAndPay',params).then(res =>{
              const code = (res || {}).code
              // Merchant returns payment result to the frontend
              if (code == 'APPLY_SUCCESS') {  
                  if(res.threeDSUrl){ 
                // Use PayerMax component popup to complete 3DS; or open threeDSUrl in a new browser tab to complete 3DS
                    handle3DS(threeDSUrl)
                }
                // Payment successful, display payment result
              }  else {
                  // Payment failed, display failure result
              }
        }
          card.emit('setDisabled', false) // Unfreeze form after payment API is completed
        }
      })
      .catch(err => {
        card.emit('setDisabled', false) // Unfreeze form after an exception occurs
      })
}

// If the returned url (threeDSUrl) is obtained after orderAndPay, use the handle3DS method to invoke the popup
function handle3DS(threeDSUrl) {
  card.create3DSPopup({
    // If width/height are not passed, they are automatically calculated based on the device and viewport; they can also be explicitly passed, such as '80%', '400px', etc.
    url: threeDSUrl,
    // If there is a 3DS link that does not support iframe (i.e., NOT_SUPPORTED is returned, and our popup fails to open), we by default automatically handle window.location.href = url;
    // However, if it is a webview merchant and the behavior of window.location.href = url is restricted, the merchant needs to control the jump method themselves through the jumpToUrlFn custom function.
    //jumpToUrlFn: (url) => {
    //  window.location.href = url; // Merchant handles opening the url themselves
    //}
  })
  .then(res => {
    if (res.code === '3DS_PROCESSED') {
      // 3DS process completed, continue payment process.
      console.log('3DS process completed', res.data);
      // Here the merchant needs to maintain existing logic. The merchant side should actively query the payment result to continue subsequent interactions on the merchant side
      proceedPayment(res.data);
    }
  })
  .catch(err => {
    if (err.code === 'USER_CANCEL') {
      // The merchant can also choose not to handle it, but should allow the user to continue clicking the payment button
      showMessage('You have closed the authentication window');
    } else {
      showMessage('Authentication exception occurred, please try again');
    }
  });
}

```

**Step 3: Carry Drop-in Component Result and Call orderAndPay to Activate Subscription Plan**

orderAndPay Request Example:

```json
{
  "version": "1.5",
  "keyVersion": "1",
  "requestTime": "2022-01-17T09:05:52.194+00:00",
  "appId": "bbd8d2639a7c4dfd8df7d005294390df",
  "merchantNo": "020113838535952",
  "data": {
    "outTradeNo": "P1642410680681", // Merchant order unique number
    "subject": "Subscription plan title", // Keep consistent with the subscription plan subject
    "totalAmount": 10, // Keep consistent with the subscription amount: for [n-day trial] and [n-day trial + first n periods discount], the amount is the trial period amount; for [first n periods discount], the amount is the discount period amount; for [regular subscription], the amount is the deduction amount per period
    "currency": "USD", // Keep consistent with the subscription currency
    "userId": "test1111", // Keep consistent with the subscription plan userId
    "language": "en",
    "reference": "test subscription",
    "frontCallbackUrl": "https://[your domain name]/[your callback URL]",
    "notifyUrl": "https://[your domain name]/[your notify URL]",
    "integrate": "Direct_Payment", // Fixed value during activation: Direct_Payment
    "expireTime": "1800",
    "subscriptionPlan": { // Subscription information
        "subscriptionNo": "SUB25022603353890000002003" // Subscription number to be activated
    },
    "terminalType": "WEB", // Terminal type: WEB, WAP or APP
    "osType": "ANDROID", // Operating system type: ANDROID or IOS
    "paymentDetail": {
      "paymentToken": "CPT4f200d278f3a454b9e91c81edc641e2b", // Required during activation
      "sessionKey": "bdsf8982348974hhf82934bf8239424", // Required during activation
      "mitType": "SCHEDULED", // Required. MIT type. SCHEDULED for recurring deductions, UNSCHEDULED for non-recurring deductions.
      "tokenForFutureUse": true, // Required. Value true, generates paymentTokenID for subsequent deductions.
      "merchantInitiated": false, // Required. false indicates it is not initiated by the merchant and the user is involved; true indicates it is initiated by the merchant and no user involvement is required.
      "buyerInfo": {
        "firstName": "Deborah",
        "lastName": "Swinstead",
        "email": "your@gmail.com",
        "phoneNo": "0609 031 114",
        "address": "Test Address",
        "city": "Holden Hill",
        "region": "SA",
        "zipCode": "5088",
        "clientIp": "211.52.321.225",
        "userAgent": "Mozilla/5.0"
      }
    }
  }
}
```

orderAndPay Response Example:

```json
{
  "code": "APPLY_SUCCESS",
  "msg": "",
  "data": {
      //3ds verification URL
    "redirectUrl": "https://cashier-n-uat.payermax.com/index.html#/cashier/home?merchantId=020213827212251&merchantAppId=3b242b56a8b64274bcc37dac281120e3&country=ID&tradeToken=TOKEN20220117091121294138752&language=en&token=IHjqkZ8%2F%2FFcnfDPxWTvJFOrulUAKfXFUkxHJSiTdlnjnX1G6AOuTiSl6%2BN05EzxTaJkcSsSyGh5a1q%2FACwWN0sDD%2FgwY5YdWu3ghDcH2wqm%2BJIcEh0qZqo%2BQFnXp65bvkLZnY7VO7HwZGzyrpMBlPhfRCQxwBbc6lJcSYuPf%2Fe8%3D&amount=10000¤cy=IDR&frontCallbackUrl=https%3A%2F%2Fwww.payermax.com",
    "outTradeNo": "P1642410680681",
    "tradeToken": "T2024062702289232000001",
    "status": "PENDING"
  }
}
```

### 5.2 GooglePay Activation for Subscription Plan

#### 5.2.1 Hosted Checkout Mode

>When using GooglePay to activate a subscription plan, the merchant needs to pass the subscription plan information `subscriptionPlan` to PayerMax, and also needs to send the user's subscription management URL `mitManagementUrl`, so that users can access this URL to manage the subscription plan, such as canceling the subscription;

```mermaid
%%{init: {
  'theme': 'base',
  'themeVariables': {
    'primaryColor': '#e6f0ff',
    'primaryTextColor': '#333',
    'primaryBorderColor': '#5b9bd5',
    'lineColor': '#888',
    'actorMargin': 40,
    'noteBkgColor': '#0056b3',
    'noteTextColor': '#ffffff',
    'noteBorderColor': '#004a99'
  }
}}%%
sequenceDiagram
    participant Client as Merchant Client
    participant MServer as Merchant Server
    participant Checkout as PayerMax Checkout
    participant PMServer as PayerMax Server
    participant Google as Google

    %% 1. Subscription Initialization Stage
    Client->>MServer: 1.1 User selects subscription product and places order
    MServer->>PMServer: 1.2 Create subscription plan, call create Subscription API
    PMServer-->>MServer: 1.3 Return PayerMax order ID
    MServer->>PMServer: 1.4 Activate subscription plan, call orderAndPay
    PMServer-->>MServer: 1.5 Return PayerMax Checkout URL
    MServer-->>Client: 1.6 Return PayerMax Checkout URL

    %% 2. Payment and Authorization Stage
    Client->>Checkout: 2.1 Redirect to PayerMax Checkout
    Checkout->>Checkout: 2.2 User selects GooglePay for payment
    Checkout->>Google: 2.3 Launch Google Wallet
    Google->>Google: 2.4 Display subscription plan information
    Google->>Google: 2.5 After user confirmation, complete face/fingerprint authentication
    Google-->>Checkout: 2.6 Return Google payment elements
    Checkout->>PMServer: 2.7 Initiate payment
    PMServer-->>Checkout: 2.8 Return payment result
    Checkout-->>Client: 2.9 Redirect to merchant checkout result page after payment

    %% 3. Asynchronous Notification Stage
    PMServer->>MServer: 3.1 Asynchronously notify merchant of activation result
    MServer-->>PMServer: 3.2 Return whether the notification result was received
```

Request Example:

```json
{
  "version": "1.5",
  "keyVersion": "1",
  "requestTime": "2022-01-17T09:05:52.194+00:00",
  "appId": "bbd8d2639a7c4dfd8df7d005294390df",
  "merchantNo": "020113838535952",
  "data": {
    "outTradeNo": "APIFOXDEV1745388079422", // Merchant order unique number
    "subject": "Subscription plan title", // Keep consistent with the subscription plan subject
    "totalAmount": 10, // Keep consistent with the subscription amount: [n-day trial] amount is the trial period amount; [first n periods discount] amount is the discount period amount; [regular subscription] amount is the deduction amount per period
    "country": "US",
    "currency": "USD", // Keep consistent with the subscription currency
    "userId": "test1111", // Keep consistent with the subscription plan userId
    "language": "en",
    "reference": "test subscription",
    "frontCallbackUrl": "https://[your domain name]/[your callback URL]",
    "notifyUrl": "https://[your domain name]/[your notify URL]",
    "integrate": "Hosted_Checkout", // Fixed value during activation: Hosted_Checkout
    "expireTime": "1800",
    "subscriptionPlan": { // Subscription information
        "subscriptionNo": "SUB25022603353890000002003" // Subscription number to be activated
    },
    "mitManagementUrl": "https://[your domain name]/[your subscription management URL]",
    "paymentDetail": {
      "paymentMethodType": "GOOGLEPAY", // Optional during activation; value can be GOOGLEPAY
      "mitType": "SCHEDULED", // Required. MIT type. SCHEDULED for recurring deductions, UNSCHEDULED for non-recurring deductions.
      "tokenForFutureUse": true, // Required. Value true, generates paymentTokenID for subsequent deductions.
      "merchantInitiated": false, // Required. false indicates it is not initiated by the merchant and the user is involved; true indicates it is initiated by the merchant and no user involvement is required.
      "buyerInfo": {
            "firstName": "Deborah",
            "lastName": "Swinstead",
            "email": "your@gmail.com",
            "phoneNo": "0609 031 114",
            "address": "Test Address",
            "city": "Holden Hill",
            "region": "SA",
            "zipCode": "5088",
            "clientIp": "211.52.321.225",
            "userAgent": "Mozilla/5.0 (iPad; CPU OS 18_4_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/22E252 [FBAN/FBIOS;FBAV/513.1.0.55.90;FBBV/735017191;FBDV/iPad13,16;FBMD/iPad;FBSN/iPadOS;FBSV/18.4.1;FBSS/2;FBID/tablet;FBLC/en_GB;FBOP/5;FBRV/737247184]"
        }
    }
  }
}
```

Response Example:

```json
{
    "msg": "Success.",
    "code": "APPLY_SUCCESS",
    "data": {
        // PayerMax Checkout URL
        "redirectUrl": "https://cashier-n-uat.payermax.com/static/processApiV2.html?tradeToken=T2025042306527802000033&integrate=DIRECT_API&country=UN&payRequestNo=20250423060120EP4366527897000250005&merchantId=010213834784554&merchantAppId=6666c8b036a24579974497c2f9a33333&token=902170aeaadb4621af8d9530398d0efa&orderLan=en&countryLan=en&strategyLan=LUBCO&pmaxLinkV=1",
        "outTradeNo": "APIFOXDEV1745388079422",
        "tradeToken": "T2025042306527802000033",
        "status": "PENDING"
    }
}
```

#### 5.2.2 API Mode

The merchant obtains payment elements from Google Wallet itself, decrypts them, and directly calls `orderAndPay` to complete activation. For how merchants integrate GooglePay themselves, please refer to [GooglePay Pure API Mode Integration](https://docs.payermax.com/en/202606-version/acquiring/start-integration/payment-acceptance/API/googlepay.md).

```mermaid
%%{init: {
  'theme': 'base',
  'themeVariables': {
    'primaryColor': '#e6f0ff',
    'primaryTextColor': '#333',
    'primaryBorderColor': '#5b9bd5',
    'lineColor': '#888',
    'actorMargin': 40,
    'noteBkgColor': '#0056b3',
    'noteTextColor': '#ffffff',
    'noteBorderColor': '#004a99'
  }
}}%%
sequenceDiagram
    participant Client as Merchant Client
    participant Google as Google
    participant MServer as Merchant Server
    participant PMServer as PayerMax Server

    %% 1. Client Interaction and Authorization
    Client->>Client: 1.1 User enters merchant subscription product page and selects a product
    Client->>Client: 1.2 User enters merchant checkout and selects GooglePay
    Client->>Google: 1.3 User clicks GooglePay
Launch Google Wallet
Subscription plan and subscription management URL need to be passed to Google
    Google->>Google: 1.4 User confirms information and selects a card to complete authentication
    Google-->>Client: 1.5 Google returns payment elements

    %% 2. Payment Initiation and Plan Activation
    Client->>MServer: 2.1 Initiate payment
with the user-selected subscription product and Google payment elements
    MServer->>PMServer: 2.2 Create subscription plan
    PMServer-->>MServer: 2.3 Return subscription number
    MServer->>MServer: 2.4 Decrypt Google payment elements
    MServer->>PMServer: 2.5 Activate subscription plan
with decrypted Google payment information
    PMServer-->>MServer: 2.6 Return activation result
    MServer-->>Client: 2.7 Return activation result
    Client->>Client: 2.8 Redirect to subscription result page

    %% 3. Background Notification
    PMServer->>MServer: 3.1 Asynchronously notify merchant of subscription result and payment result
    MServer-->>PMServer: 3.2 Merchant responds that the result was received successfully
```

orderAndPay Request Example:

```json
{
    "version": "1.5",
    "keyVersion": "1",
    "requestTime": "2022-01-17T09:05:52.194+00:00",
    "appId": "bbd8d2639a7c4dfd8df7d005294390df",
    "merchantNo": "020113838535952",
    "data": {
        "outTradeNo": "APIFOXDEV1745388079422", // Merchant order unique number
        "subject": "Subscription plan title", // Keep consistent with the subscription plan subject
        "totalAmount": 10, // Keep consistent with the subscription amount: [n-day trial] amount is the trial period amount; [first n periods discount] amount is the discount period amount; [regular subscription] amount is the deduction amount per period
        "country": "US",
        "currency": "USD", // Keep consistent with the subscription currency
        "userId": "test1111", // Keep consistent with the subscription plan userId
        "language": "en",
        "reference": "test subscription",
        "frontCallbackUrl": "http://www.frontCallbackUrl.com",
        "notifyUrl": "http://www.notifyUrl.com",
        "integrate": "Direct_Payment", // Fixed value during activation: Direct_Payment
        "expireTime": "1800",
        "subscriptionPlan": { // Subscription information
            "subscriptionNo": "SUB25022603353890000002003" // Subscription number to be activated
        },
        "terminalType": "WEB", // Terminal type: WEB, WAP or APP
        "osType": "ANDROID", // Operating system type: ANDROID or IOS
        "paymentDetail": {
            "paymentMethodType": "GOOGLEPAY", // Required. Value GOOGLEPAY.
            "mitType": "SCHEDULED", // Required. MIT type. SCHEDULED for recurring subscriptions, UNSCHEDULED for non-recurring deductions.
            "tokenForFutureUse": true, // Required. Value true, generates paymentTokenID for subsequent deductions.
            "merchantInitiated": false, // Required. false indicates user parameters are required; true indicates merchant-initiated deduction without user involvement.
            "googlePayDetails": { // Required. Google Pay order parameters.
                "authMethod": "PAN_ONLY", //CRYPTOGRAM_3DS 
                "pan": "4111111111111111", // Card number
                "expirationMonth": "12",
                "expirationYear": "2029",
                "cryptogram": "xxxxxxxxxxxx",
                "eciIndicator": "5",
                "description": "VISA 1234",
                "cardNetwork": "VISA",
                "cardHolderFullName": "zhangsan" // Pass for pan_only
            },
            "buyerInfo": {
                "firstName": "Deborah",
                "lastName": "Swinstead",
                "email": "your@gmail.com",
                "phoneNo": "0609 031 114",
                "address": "Test Address",
                "city": "Holden Hill",
                "region": "SA",
                "zipCode": "5088",
                "clientIp": "211.52.321.225",
                "userAgent": "Mozilla/5.0 (iPad; CPU OS 18_4_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/22E252 [FBAN/FBIOS;FBAV/513.1.0.55.90;FBBV/735017191;FBDV/iPad13,16;FBMD/iPad;FBSN/iPadOS;FBSV/18.4.1;FBSS/2;FBID/tablet;FBLC/en_GB;FBOP/5;FBRV/737247184]"
            }
        }
    }
}
```

orderAndPay Response Example:

>Note: When `paymentDetail.googlePayDetails.authMethod=PAN_ONLY`, the response parameter `redirecUrl` will return the `3DS verification URL`; when `paymentDetail.googlePayDetails.authMethod=CRYPTOGRAM_3DS`, the response parameter will not return `redirecUrl`.

```json
{
    "msg": "Success.",
    "code": "APPLY_SUCCESS",
    "data": {
        // 3DS URL
        "redirectUrl": "https://cashier-n.payermax.com/index.html#/cashier/home?merchantId=020213827212251&merchantAppId=3b242b56a8b64274bcc37dac281120e3&country=ID&tradeToken=TOKEN20220117091121294138752&language=en&token=IHjqkZ8%2F%2FFcnfDPxWTvJFOrulUAKfXFUkxHJSiTdlnjnX1G6AOuTiSl6%2BN05EzxTaJkcSsSyGh5a1q%2FACwWN0sDD%2FgwY5YdWu3ghDcH2wqm%2BJIcEh0qZqo%2BQFnXp65bvkLZnY7VO7HwZGzyrpMBlPhfRCQxwBbc6lJcSYuPf%2Fe8%3D&amount=10000¤cy=IDR&frontCallbackUrl=https%3A%2F%2Fwww.payermax.com",
        "outTradeNo": "APIFOXDEV1745388079422",
        "tradeToken": "T2025042306527802000033",
        "status": "PENDING"
    }
}
```

#### 5.2.3 Drop-in Component Mode

The merchant embeds the PayerMax Drop-in Component in its own page to render the GooglePay button. The component internally completes the Google Wallet interaction and generates a `paymentToken`. The flow and request structure are the same as the Card Drop-in Component Mode. The only differences are that `componentList` is set to `GOOGLEPAY`, `paymentDetail.sessionKey/paymentToken` come from the GooglePay component callback, and `mitManagementUrl` needs to be sent.

```mermaid
%%{init: {
  'theme': 'base',
  'themeVariables': {
    'primaryColor': '#e6f0ff',
    'primaryTextColor': '#333',
    'primaryBorderColor': '#5b9bd5',
    'lineColor': '#888',
    'actorMargin': 40,
    'noteBkgColor': '#0056b3',
    'noteTextColor': '#ffffff',
    'noteBorderColor': '#004a99'
  }
}}%%
sequenceDiagram
    participant Client as Merchant Client
    participant MServer as Merchant Server
    participant Checkout as PayerMax Checkout
    participant Google as Google
    participant PMServer as PayerMax Server

    %% 1. Initialization Stage
    Client->>Client: 1.1 User enters merchant subscription product page
    Client->>MServer: 1.2 Obtain component information
    MServer->>PMServer: 1.3 Request applyDropinSession
    PMServer-->>MServer: 1.4 Return clientKey and sessionKey
    MServer-->>Client: 1.5 Return clientKey and sessionKey
    Client->>Client: 1.6 Render PayerMax component

    %% 2. Payment Initiation Process
 rect rgb(235, 245, 255)
    Note over Client, PMServer: Payment Initiation Process
    Client->>Client: 2.1 User selects subscription product and chooses GooglePay to initiate payment
    Client->>MServer: 2.2 Create subscription
    MServer->>PMServer: 2.3 Create subscription plan, call createSubscription
    PMServer-->>MServer: 2.4 Return subscription ID
    MServer-->>Client: 2.5 Return subscription information

    Client->>Checkout: 2.6 Call component canMakePayment API, launch Google Wallet
Pass subscription information and mitManagementUrl to PayerMax component
    Checkout->>Google: 2.7 Launch Google Wallet
    Google->>Google: 2.8 Display subscription plan information
    Google->>Google: 2.9 User selects card and completes authentication
    Google-->>Checkout: 2.10 Return Google payment elements
    Checkout->>Checkout: 2.11 Generate paymentToken
    Checkout-->>Client: 2.12 Return paymentToken

    Client->>MServer: 2.13 Send paymentToken and sessionKey
    MServer->>PMServer: 2.14 Call orderAndPay to activate subscription
Send paymentToken, sessionKey, subscription ID
    PMServer-->>MServer: 2.15 Return activation result
    MServer-->>Client: 2.16 Return activation result
    end
    Client->>Client: 2.17 Redirect to subscription result page

    %% 3. Notification Stage
    PMServer->>MServer: 3.1 Asynchronously notify merchant of subscription result and payment result
    MServer-->>PMServer: 3.2 Merchant responds that the result was received successfully
```

Merchant Client Integration Example:

```javascript
// Obtain clientKey and sessionKey
const data = await post("applyDropinSession", {
    // Tell the server if it is a subscription payment?
    ...params
})
// Create googlepay view
googlepay = PMdropin.create('googlepay', {
  clientKey: data.clientKey,
  sessionKey: data.sessionKey,
  theme: yourTheme,
  payButtonStyle: data.yourPayButtonStyle,
  sandbox: data.yourFrameEnv
})
// Mount to DOM
googlepay.mount('.frame-googlepay')
// 'load' event to determine if loaded successfully
googlepay.on('load', (res = {}) => {
      const { code, msg } = res || {};
      if(code === "SUCCESS"){
        console.log('[merchant][load]success:', res)
      }else{
        console.log('[merchant][load]fail:', res)
      }
})
// Listen to the click event of the googlepay button. After the user selects a subscription plan, they can listen to it via this event when clicking the googlepay button.
googlepay.on('payButtonClick', (res) => {
    // Do not perform async/sync task processing here. It is known that the Safari browser does not allow task processing after a button click before popping up the GooglePay confirmation dialog.
    // Disable the googlepay button click status
     googlepay.emit('setDisabled', true)
     // Need to pass in subscriptionPlan and mitManagementUrl;
     googlepay.emit('canMakePayment', { 
         // subscriptionPlan is required for recurring subscriptions
          subscriptionPlan: {
            "subject": "subject",
            "description": "PMMAX first period deduction for subscription.",
            "totalPeriods": 12,
            "periodRule": {
                "periodUnit": "M", // Deduct by month (M), day (D), week (W), year (Y)
                "periodCount": 1 // // Deduct once every 1 month
            },
            "periodAmount": { // Fixed period deduction amount
                "amount": 404.35,
                "currency": "SAR"
            },
            "firstPeriodStartDate": "2025-02-26T12:00:00+00:00",
            "trialPeriodConfig": { // Trial period rules
                "trialPeriodCount": 1, // Number of trial periods
                "trialPeriodAmount": { // Trial period deduction amount
                    "amount": 10,
                    "currency": "SAR"
                }
            }
        },
        mitManagementUrl: "http://www.xxx.com"
     })
      .then(res => {
        console.log('canMakePayment', res)
        const paymentToken = res?.data?.paymentToken 
        data.paymentToken = paymentToken// Encrypted token
        if(paymentToken){
          // Call PayerMax createSubscription API to create a subscription plan
          createSubscription()
          // Call PayerMax orderAndPay API to initiate payment
          orderAndPay()
        }else{
            // If the input parameters do not match the format, an error message will be thrown here
            // Error res example: { code: "MIT_PARAMS_VALIDATION_ERROR", message: "xxx  is required" }
          _payLog(JSON.stringify(res))  
          googlepay.emit('setDisabled', false)
        }
      })
      .catch(err => {
         // If validation fails, report a clear error. TODO
        console.log('canMakePayment catch', err)
        googlepay.emit('payFail')
        googlepay.emit('setDisabled', false)
        _payLog(JSON.stringify(err))      
      })
})
```

**Step 1: Apply for Drop-in Component Session**

- Prod Request URL: https://pay-gate.payermax.com/aggregate-pay/api/gateway/applyDropinSession

- Test Request URL: https://pay-gate-uat.payermax.com/aggregate-pay/api/gateway/applyDropinSession

applyDropinSession Request Example:

```json
{
  "version": "1.5",
  "keyVersion": "1",
  "requestTime": "2022-01-17T09:05:52.194+00:00",
  "appId": "3b242b56a8b64274bcc37dac281120e3",
  "merchantNo": "020213827212251",
  "data": {
    "totalAmount": "10", // Keep consistent with the subscription amount: for [n-day trial] and [n-day trial + first n periods discount], the amount is the trial period amount; for [first n periods discount], the amount is the discount period amount; for [regular subscription], the amount is the deduction amount per period; can also be left blank
    "mitType": "SCHEDULED", // Required. When PayerMax manages the subscription plan, the value is SCHEDULED.
    "currency": "USD", // Required
    "country": "SA", // Optional
    "userId": "U10001", // Required. User ID.
    "componentList": [ // Required. Payment methods supported by the component.
      "GOOGLEPAY"
    ]
  }
}
```

applyDropinSession Response Example:

```json
{
  "code": "APPLY_SUCCESS",
  "msg": "Success.",
  "data": {
    "clientKey": "37114858239eur2384237r810482390",
    "sessionKey": "bdsf8982348974hhf82934bf8239424"
  }
}
```

**Step 2: Carry the Drop-in Component Result and Call orderAndPay to Activate the Subscription Plan**

orderAndPay Request Example:

```json
{
  "version": "1.5",
  "keyVersion": "1",
  "requestTime": "2022-01-17T09:05:52.194+00:00",
  "appId": "bbd8d2639a7c4dfd8df7d005294390df",
  "merchantNo": "020113838535952",
  "data": {
    "outTradeNo": "P1642410680681", // Merchant order unique number
    "subject": "Subscription plan title", // Keep consistent with the subscription plan subject
    "totalAmount": 10, // Keep consistent with the subscription amount: for [n-day trial] and [n-day trial + first n periods discount], the amount is the trial period amount; for [first n periods discount], the amount is the discount period amount; for [regular subscription], the amount is the deduction amount per period
    "country": "UN",
    "currency": "USD", // Keep consistent with the subscription currency
    "userId": "test1111", // Keep consistent with the subscription plan userId
    "language": "en",
    "reference": "test subscription",
    "frontCallbackUrl": "https://[your domain name]/[your callback URL]",
    "notifyUrl": "https://[your domain name]/[your notify URL]",
    "integrate": "Direct_Payment", // Fixed value during activation: Direct_Payment
    "expireTime": "1800",
    "subscriptionPlan": { // Subscription information
        "subscriptionNo": "SUB25022603353890000002003" // Subscription number to be activated
    },
    "mitManagementUrl": "http://www.xxx.com",
    "terminalType": "WEB", // Terminal type: WEB, WAP or APP
    "osType": "ANDROID", // Operating system type: ANDROID or IOS
    "paymentDetail": {
      "paymentToken": "CPT4f200d278f3a454b9e91c81edc641e2b", // Required during activation
      "sessionKey": "bdsf8982348974hhf82934bf8239424", // Required during activation
      "mitType": "SCHEDULED", // Required. MIT type. SCHEDULED for recurring deductions, UNSCHEDULED for non-recurring deductions.
      "tokenForFutureUse": true, // Required. Value true, generates paymentTokenID for subsequent deductions.
      "merchantInitiated": false, // Required. false indicates it is not initiated by the merchant and the user is involved; true indicates it is initiated by the merchant and no user involvement is required.
      "buyerInfo": {
            "firstName": "Deborah",
            "lastName": "Swinstead",
            "email": "your@gmail.com",
            "phoneNo": "0609 031 114",
            "address": "Test Address",
            "city": "Holden Hill",
            "region": "SA",
            "zipCode": "5088",
            "clientIp": "211.52.321.225",
            "userAgent": "Mozilla/5.0 (iPad; CPU OS 18_4_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/22E252 [FBAN/FBIOS;FBAV/513.1.0.55.90;FBBV/735017191;FBDV/iPad13,16;FBMD/iPad;FBSN/iPadOS;FBSV/18.4.1;FBSS/2;FBID/tablet;FBLC/en_GB;FBOP/5;FBRV/737247184]"
        }
    }
  }
}
```

orderAndPay Response Example:

```json
{
  "code": "APPLY_SUCCESS",
  "msg": "",
  "data": {
    "outTradeNo": "P1642410680681",
    "tradeToken": "T2024062702289232000001",
    "status": "SUCCESS"
  }
}
```

### 5.3 ApplePay Activation for Subscription Plan

#### 5.3.1 Hosted Checkout Mode

PayerMax Checkout is responsible for launching the Apple Wallet and completing the payment. The flow is the same as the GooglePay Hosted Checkout Mode, except that `paymentDetail.paymentMethodType` is replaced with `APPLEPAY`.

#### 5.3.2 API Mode

The merchant needs to obtain Apple payment elements from the Apple Wallet on its own checkout page. When calling the PayerMax activation API, the merchant needs to decrypt the Apple payment elements and send them to PayerMax to complete subscription activation.

For how merchants integrate ApplePay themselves, please refer to: [ApplePay - Pure API Mode Integration](https://docs.payermax.com/en/202606-version/acquiring/start-integration/payment-acceptance/API/applepay.md).

```mermaid
%%{init: {
  'theme': 'base',
  'themeVariables': {
    'primaryColor': '#e6f0ff',
    'primaryTextColor': '#333',
    'primaryBorderColor': '#5b9bd5',
    'lineColor': '#888',
    'actorMargin': 40,
    'noteBkgColor': '#0056b3',
    'noteTextColor': '#ffffff',
    'noteBorderColor': '#004a99'
  }
}}%%
sequenceDiagram
    participant Client as Merchant Client
    participant Apple as Apple
    participant MServer as Merchant Server
    participant PMServer as PayerMax Server

    %% 1. Client Interaction and Authorization
    Client->>Client: 1.1 User enters merchant subscription product page and selects a product
    Client->>Client: 1.2 User enters merchant checkout and selects ApplePay
    Client->>Apple: 1.3 User clicks ApplePay
Launch Apple Wallet
Subscription plan and
subscription management URL need to be passed to Apple
    Apple->>Apple: 1.4 User confirms information and selects a card to complete authentication
    Apple-->>Client: 1.5 Apple returns payment elements

    %% 2. Payment Initiation and Plan Activation
    Client->>MServer: 2.1 Initiate payment
with the user-selected subscription product and Apple payment elements
    MServer->>PMServer: 2.2 Create subscription plan
    PMServer-->>MServer: 2.3 Return subscription number
    MServer->>MServer: 2.4 Decrypt Apple payment elements
    MServer->>PMServer: 2.5 Activate subscription plan
with decrypted Apple payment information
    PMServer-->>MServer: 2.6 Return activation result
    MServer-->>Client: 2.7 Return activation result
    Client->>Client: 2.8 Redirect to subscription result page

    %% 3. Background Notification
    PMServer->>MServer: 3.1 Asynchronously notify merchant of subscription result and payment result
    MServer-->>PMServer: 3.2 Merchant responds that the result was received successfully
```

Request Example:

```json
{
    "version": "1.5",
    "keyVersion": "1",
    "requestTime": "2022-01-17T09:05:52.194+00:00",
    "appId": "bbd8d2639a7c4dfd8df7d005294390df",
    "merchantNo": "020113838535952",
    "data": {
        "outTradeNo": "APIFOXDEV1745388079422", // Merchant order unique number
        "subject": "Subscription plan title", // Keep consistent with the subscription plan subject
        "totalAmount": 10, // Keep consistent with the subscription amount: [n-day trial] amount is the trial period amount; [first n periods discount] amount is the discount period amount; [regular subscription] amount is the deduction amount per period
        "country": "US",
        "currency": "USD", // Keep consistent with the subscription currency
        "userId": "test1111", // Keep consistent with the subscription plan userId
        "language": "en",
        "reference": "test subscription",
        "frontCallbackUrl": "https://[your domain name]/[your callback URL]",
        "notifyUrl": "https://[your domain name]/[your notify URL]",
        "integrate": "Direct_Payment", // Fixed value during activation: Direct_Payment
        "expireTime": "1800",
        "subscriptionPlan": { // Subscription information
            "subscriptionNo": "SUB25022603353890000002003" // Subscription number to be activated
        },
        "mitManagementUrl": "xxx",
        "terminalType": "WEB", // Terminal type: WEB, WAP or APP
        "osType": "ANDROID", // Operating system type: ANDROID or IOS
        "paymentDetail": {
            "paymentMethodType": "APPLEPAY", // Required. Value APPLEPAY.
            "mitType": "SCHEDULED", // Required. MIT type. SCHEDULED for recurring subscriptions, UNSCHEDULED for non-recurring deductions.
            "tokenForFutureUse": true, // Required. Value true, generates paymentTokenID for subsequent deductions.
            "merchantInitiated": false, // Required. false indicates user parameters are required; true indicates merchant-initiated deduction without user involvement.
            "applePayPaymentData": { // Required. Parameters after decryption of Apple payment elements.
                "applicationExpirationDate": "231231",
                "applicationPrimaryAccountNumber": "1234209400123456",
                "currencyCode": "344",
                "deviceManufacturerIdentifier": "040010030273",
                "paymentData": {
                    "eciIndicator": "7",
                    "onlinePaymentCryptogram": "AqhVFUwAAuM69WEZxe+OMAACAAA="
                },
                "paymentDataType": "3DSecure",
                "transactionAmount": "100",
                "network": "Visa",
                "type": "credit",
                "displayName": "VISA 5743"
            },
            "buyerInfo": {
                "firstName": "Deborah",
                "lastName": "Swinstead",
                "email": "your@gmail.com",
                "phoneNo": "0609 031 114",
                "address": "Test Address",
                "city": "Holden Hill",
                "region": "SA",
                "zipCode": "5088",
                "clientIp": "211.52.321.225",
                "userAgent": "Mozilla/5.0 (iPad; CPU OS 18_4_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/22E252 [FBAN/FBIOS;FBAV/513.1.0.55.90;FBBV/735017191;FBDV/iPad13,16;FBMD/iPad;FBSN/iPadOS;FBSV/18.4.1;FBSS/2;FBID/tablet;FBLC/en_GB;FBOP/5;FBRV/737247184]"
            }
        }
    }
}
```

#### 5.3.3 Drop-in Component Mode

For Drop-in Component integration, please refer to: [Integration Steps](https://docs.payermax.com/en/202606-version/acquiring/start-integration/payment-acceptance/drop-in/applepay.md).

```mermaid
%%{init: {
  'theme': 'base',
  'themeVariables': {
    'primaryColor': '#e6f0ff',
    'primaryTextColor': '#333',
    'primaryBorderColor': '#5b9bd5',
    'lineColor': '#888',
    'actorMargin': 40,
    'noteBkgColor': '#0056b3',
    'noteTextColor': '#ffffff',
    'noteBorderColor': '#004a99'
  }
}}%%
sequenceDiagram
    participant Client as Merchant Client
    participant MServer as Merchant Server
    participant Checkout as PayerMax Checkout
    participant Apple as Apple
    participant PMServer as PayerMax Server

    %% 1. Initialization Stage
    Client->>Client: 1.1 User enters merchant subscription product page
    Client->>MServer: 1.2 Obtain component information
    MServer->>PMServer: 1.3 Request applyDropinSession
    PMServer-->>MServer: 1.4 Return clientKey and sessionKey
    MServer-->>Client: 1.5 Return clientKey and sessionKey
    Client->>Client: 1.6 Render PayerMax component

    %% 2. Payment Initiation Process
 rect rgb(235, 245, 255)
    Note over Client, PMServer: Payment Initiation Process
    Client->>Client: 2.1 User selects subscription product and chooses ApplePay to initiate payment
    Client->>MServer: 2.2 Create subscription
    MServer->>PMServer: 2.3 Create subscription plan, call createSubscription
    PMServer-->>MServer: 2.4 Return subscription ID
    MServer-->>Client: 2.5 Return subscription information

    Client->>Checkout: 2.6 Call component canMakePayment API, launch Apple Wallet
Pass subscription information and mitManagementUrl to PayerMax component
    Checkout->>Apple: 2.7 Launch Apple Wallet
    Apple->>Apple: 2.8 Display subscription plan information
    Apple->>Apple: 2.9 User selects card and completes authentication
    Apple-->>Checkout: 2.10 Return Apple payment elements
    Checkout->>Checkout: 2.11 Generate paymentToken
    Checkout-->>Client: 2.12 Return paymentToken

    Client->>MServer: 2.13 Send paymentToken and sessionKey
    MServer->>PMServer: 2.14 Call orderAndPay to activate subscription
Send paymentToken, sessionKey, subscription ID
    PMServer-->>MServer: 2.15 Return activation result
    MServer-->>Client: 2.16 Return activation result
    end
    Client->>Client: 2.17 Redirect to subscription result page

    %% 3. Notification Stage
    PMServer->>MServer: 3.1 Asynchronously notify merchant of subscription result and payment result
    MServer-->>PMServer: 3.2 Merchant responds that the result was received successfully
```

Merchant Client Integration Example:

```javascript
// Obtain clientKey and sessionKey
const data = await post("applyDropinSession", {
    // Tell the server if it is a subscription payment?
    ...params
})
// Create applepay view
applePay = PMdropin.create('applepay', {
  clientKey: data.clientKey,
  sessionKey: data.sessionKey,
  theme: yourTheme,
  payButtonStyle: data.yourPayButtonStyle,
  sandbox: data.yourFrameEnv
})
// Mount to DOM
applePay.mount('.frame-applepay')
// 'load' event to determine if loaded successfully
applePay.on('load', (res = {}) => {
      const { code, msg } = res || {};
      if(code === "SUCCESS"){
        console.log('[merchant][load]success:', res)
      }else{
        console.log('[merchant][load]fail:', res)
      }
})
// Listen to the click event of the applepay button. After the user selects a subscription plan, they can listen to it via this event when clicking the applepay button.
applePay.on('payButtonClick', (res) => {
     // Do not perform async/sync server-side call processing here. It is known that the Safari browser does not allow task processing after clicking the Apple button before popping up the ApplePay confirmation dialog.
    // Disable the applepay button click status
     applePay.emit('setDisabled', true)
     // Need to pass in subscriptionPlan and mitManagementUrl;
     applePay.emit('canMakePayment', { 
         // subscriptionPlan is required for recurring subscriptions
          subscriptionPlan: {
            "subject": "subject",
            "description": "PMMAX first period deduction for subscription.",
            "totalPeriods": 12,
            "periodRule": {
                "periodUnit": "M", // Deduct by month (M), day (D), week (W), year (Y)
                "periodCount": 1 // // Deduct once every 1 month
            },
            "periodAmount": { // Fixed period deduction amount
                "amount": 404.35,
                "currency": "SAR"
            },
            "firstPeriodStartDate": "2025-02-26T12:00:00+00:00",
            "trialPeriodConfig": { // Trial period rules
                "trialPeriodCount": 1, // Number of trial periods
                "trialPeriodAmount": { // Trial period deduction amount
                    "amount": 10,
                    "currency": "SAR"
                }
            }
        },
        mitManagementUrl: "http://www.xxx.com"
     })
      .then(res => {
        console.log('canMakePayment', res)
        const paymentToken = res?.data?.paymentToken 
        data.paymentToken = paymentToken// Encrypted token
        if(paymentToken){
          // Call PayerMax createSubscription API to create a subscription plan
          createSubscription()
          // Call PayerMax orderAndPay API to initiate payment
          orderAndPay()
        }else{
            // If the input parameters do not match the format, an error message will be thrown here
            // Error res example: { code: "MIT_PARAMS_VALIDATION_ERROR", message: "xxx  is required" }
          _payLog(JSON.stringify(res))  
          applePay.emit('setDisabled', false)
        }
      })
      .catch(err => {
         // If validation fails, report a clear error. TODO
        console.log('canMakePayment catch', err)
        applePay.emit('payFail')
        applePay.emit('setDisabled', false)
        _payLog(JSON.stringify(err))      
      })
})
```

**Step 1: Apply for Drop-in Component Session**

- Prod Request URL: `https://pay-gate.payermax.com/aggregate-pay/api/gateway/applyDropinSession`

- Test Request URL: `https://pay-gate-uat.payermax.com/aggregate-pay/api/gateway/applyDropinSession`

applyDropinSession Request Example:

```json
{
  "version": "1.5",
  "keyVersion": "1",
  "requestTime": "2022-01-17T09:05:52.194+00:00",
  "appId": "3b242b56a8b64274bcc37dac281120e3",
  "merchantNo": "020213827212251",
  "data": {
    "totalAmount": "10", // Keep consistent with the subscription amount: for [n-day trial] and [n-day trial + first n periods discount], the amount is the trial period amount; for [first n periods discount], the amount is the discount period amount; for [regular subscription], the amount is the deduction amount per period; can also be left blank
    "mitType": "SCHEDULED", // Required. When PayerMax manages the subscription plan, the value is SCHEDULED.
    "currency": "USD", // Required
    "country": "SA", // Optional
    "userId": "U10001", // Required. User ID.
    "componentList": [ // Required. Payment methods supported by the component.
      "APPLEPAY"
    ]
  }
}
```

applyDropinSession Response Example:

```JSON
{
  "code": "APPLY_SUCCESS",
  "msg": "Success.",
  "data": {
    "clientKey": "37114858239eur2384237r810482390",
    "sessionKey": "bdsf8982348974hhf82934bf8239424"
  }
}
```

**Step 2: Carry the Drop-in Component Result and Call orderAndPay to Activate the Subscription Plan**

orderAndPay Request Example:

```json
{
  "version": "1.5",
  "keyVersion": "1",
  "requestTime": "2022-01-17T09:05:52.194+00:00",
  "appId": "bbd8d2639a7c4dfd8df7d005294390df",
  "merchantNo": "020113838535952",
  "data": {
    "outTradeNo": "P1642410680681", // Merchant order unique number
    "subject": "Subscription plan title", // Keep consistent with the subscription plan subject
    "totalAmount": 10, // Keep consistent with the subscription amount: for [n-day trial] and [n-day trial + first n periods discount], the amount is the trial period amount; for [first n periods discount], the amount is the discount period amount; for [regular subscription], the amount is the deduction amount per period
    "country": "UN",
    "currency": "USD", // Keep consistent with the subscription currency
    "userId": "test1111", // Keep consistent with the subscription plan userId
    "language": "en",
    "reference": "test subscription",
    "frontCallbackUrl": "https://[your domain name]/[your callback URL]",
    "notifyUrl": "https://[your domain name]/[your notify URL]",
    "integrate": "Direct_Payment", // Fixed value during activation: Direct_Payment
    "expireTime": "1800",
    "subscriptionPlan": { // Subscription information
        "subscriptionNo": "SUB25022603353890000002003" // Subscription number to be activated
    },
    "mitManagementUrl": "http://www.xxx.com",
    "terminalType": "WEB", // Terminal type: WEB, WAP or APP
    "osType": "ANDROID", // Operating system type: ANDROID or IOS
    "paymentDetail": {
      "paymentToken": "CPT4f200d278f3a454b9e91c81edc641e2b", // Required during activation
      "sessionKey": "bdsf8982348974hhf82934bf8239424", // Required during activation
      "mitType": "SCHEDULED", // Required. MIT type. SCHEDULED for recurring deductions, UNSCHEDULED for non-recurring deductions.
      "tokenForFutureUse": true, // Required. Value true, generates paymentTokenID for subsequent deductions.
      "merchantInitiated": false, // Required. false indicates it is not initiated by the merchant and the user is involved; true indicates it is initiated by the merchant and no user involvement is required.
      "buyerInfo": {
            "firstName": "Deborah",
            "lastName": "Swinstead",
            "email": "your@gmail.com",
            "phoneNo": "0609 031 114",
            "address": "Test Address",
            "city": "Holden Hill",
            "region": "SA",
            "zipCode": "5088",
            "clientIp": "211.52.321.225",
            "userAgent": "Mozilla/5.0 (iPad; CPU OS 18_4_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/22E252 [FBAN/FBIOS;FBAV/513.1.0.55.90;FBBV/735017191;FBDV/iPad13,16;FBMD/iPad;FBSN/iPadOS;FBSV/18.4.1;FBSS/2;FBID/tablet;FBLC/en_GB;FBOP/5;FBRV/737247184]"
        }
    }
  }
}
```

orderAndPay Response Example:

```json
{
  "code": "APPLY_SUCCESS",
  "msg": "",
  "data": {
    "outTradeNo": "P1642410680681",
    "tradeToken": "T2024062702289232000001",
    "status": "SUCCESS"
  }
}
```

### 5.4 APM Activation for Subscription Plan

APM generally refers to local e-wallets and other third-party payment methods (such as NaverPay, etc.). Their characteristic is that payment authorization occurs on the third-party channel page, and there is no concept of card information or wallet payment credentials. Therefore, only Hosted Checkout Mode and API Mode are supported, and Drop-in Component Mode is not supported.

#### 5.4.1 Hosted Checkout Mode

Hosted Checkout Mode supports three granularities:

|**Granularity**|**Description**|
|---|---|
|Full Checkout|Do not specify a payment method; the user selects it on the PayerMax Checkout page|
|Specified Payment Method|Send paymentMethodType; the Checkout page only displays this payment method|
|Specified Payment Method + Target Organization|Send both paymentMethodType and targetOrg to directly locate the specific wallet channel|

orderAndPay Request Example for Full Checkout:

```json
{
  "version": "1.5",
  "keyVersion": "1",
  "requestTime": "2022-01-17T09:05:52.194+00:00",
  "appId": "bbd8d2639a7c4dfd8df7d005294390df",
  "merchantNo": "020113838535952",
  "data": {
    "outTradeNo": "APIFOXDEV1745388079422", // Merchant order unique number
    "subject": "Subscription plan title", // Keep consistent with the subscription plan subject
    "totalAmount": 10, // Keep consistent with the subscription amount: [n-day trial] amount is the trial period amount; [first n periods discount] amount is the discount period amount; [regular subscription] amount is the deduction amount per period
    "currency": "KRW", // Keep consistent with the subscription currency
    "userId": "test1111", // Keep consistent with the subscription plan userId
    "language": "en",
    "reference": "test subscription",
    "frontCallbackUrl": "https://[your domain name]/[your callback URL]",
    "notifyUrl": "https://[your domain name]/[your notify URL]",
    "integrate": "Hosted_Checkout", // Fixed value during activation: Hosted_Checkout
    "expireTime": "1800",
    "subscriptionPlan": { // Subscription information
        "subscriptionNo": "SUB25022603353890000002003" // Subscription number to be activated
    },
    "paymentDetail": {
      "mitType": "SCHEDULED", // Required. MIT type. SCHEDULED for recurring deductions, UNSCHEDULED for non-recurring deductions.
      "tokenForFutureUse": true, // Required. Value true, generates paymentTokenID for subsequent deductions.
      "merchantInitiated": false // Required. false indicates it is not initiated by the merchant and the user is involved; true indicates it is initiated by the merchant and no user involvement is required.
    }
  }
}
```

> When specifying the payment method + target organization, add `paymentMethodType` (e.g., `ONE_TOUCH`) and `targetOrg` (e.g., `NAVERPAY`) to `paymentDetail`.

orderAndPay API Response Example:

```json
{
    "msg": "Success.",
    "code": "APPLY_SUCCESS",
    "data": {
        // PayerMax Checkout URL
        "redirectUrl": "https://cashier-n-uat.payermax.com/static/processApiV2.html?tradeToken=T2025042306527802000033&integrate=DIRECT_API&country=UN&payRequestNo=20250423060120EP4366527897000250005&merchantId=010213834784554&merchantAppId=6666c8b036a24579974497c2f9a33333&token=902170aeaadb4621af8d9530398d0efa&orderLan=en&countryLan=en&strategyLan=LUBCO&pmaxLinkV=1",
        "outTradeNo": "APIFOXDEV1745388079422",
        "tradeToken": "T2025042306527802000033",
        "status": "PENDING"
    }
}
```

#### 5.4.2 API Mode

The merchant directly specifies the payment method and target organization to call `orderAndPay`. PayerMax returns the wallet authorization URL. The user is redirected to complete authorization, and payment is automatically initiated.

```mermaid
%%{init: {
  'theme': 'base',
  'themeVariables': {
    'primaryColor': '#e6f0ff',
    'primaryTextColor': '#333',
    'primaryBorderColor': '#5b9bd5',
    'lineColor': '#888',
    'actorMargin': 40,
    'noteBkgColor': '#0056b3',
    'noteTextColor': '#ffffff',
    'noteBorderColor': '#004a99'
  }
}}%%
sequenceDiagram
    participant Client as Merchant Client
    participant MServer as Merchant Server
    participant PMServer as PayerMax Server
    participant Wallet as Wallet Channel

    %% 1. Subscription Initialization Stage
    Client->>MServer: 1.1 Select subscription product and place order
    MServer->>PMServer: 1.2 Create subscription plan
    PMServer-->>MServer: 1.3 Return subscription number
    MServer->>PMServer: 1.4 Activate subscription plan
    PMServer-->>MServer: 1.5 Return authorization authentication URL
    MServer-->>Client: 1.6 Return authorization authentication URL

    %% 2. Authorization and Payment Stage
    Client->>Wallet: 2.1 Redirect to authorization authentication
    Wallet->>Wallet: 2.2 User completes authorization authentication
    Wallet->>PMServer: 2.3 Notify PayerMax of authorization authentication result
    PMServer->>PMServer: 2.4 Complete payment

    %% 3. Result Notification Stage
    PMServer->>MServer: 3.1 Asynchronously notify merchant of subscription result and payment result
    MServer-->>PMServer: 3.2 Merchant responds that the result was received successfully
```

orderAndPay Request Example:

```json
{
  "version": "1.5",
  "keyVersion": "1",
  "requestTime": "2022-01-17T09:05:52.194+00:00",
  "appId": "bbd8d2639a7c4dfd8df7d005294390df",
  "merchantNo": "020113838535952",
  "data": {
    "outTradeNo": "APIFOXDEV1745388079422", // Merchant order unique number
    "subject": "Subscription plan title", // Keep consistent with the subscription plan subject
    "totalAmount": 10, // Keep consistent with the subscription amount: [n-day trial] amount is the trial period amount; [first n periods discount] amount is the discount period amount; [regular subscription] amount is the deduction amount per period
    "currency": "KRW", // Keep consistent with the subscription currency
    "country": "KR", // Required
    "userId": "test1111", // Keep consistent with the subscription plan userId
    "language": "en",
    "reference": "test subscription",
    "frontCallbackUrl": "https://[your domain name]/[your callback URL]",
    "notifyUrl": "https://[your domain name]/[your notify URL]",
    "integrate": "Direct_Payment", // Fixed value during activation: Direct_Payment
    "expireTime": "1800",
    "subscriptionPlan": { // Subscription information
        "subscriptionNo": "SUB25022603353890000002003" // Subscription number to be activated
    },
    "terminalType": "WEB", // Terminal type: WEB, WAP or APP
    "osType": "ANDROID", // Operating system type: ANDROID or IOS
    "paymentDetail": {
      "paymentMethodType": "ONE_TOUCH", // Required. Payment method.
      "targetOrg": "NAVERPAY", // Required. Target organization.
      "mitType": "SCHEDULED", // Required. MIT type. SCHEDULED for recurring subscriptions, UNSCHEDULED for non-recurring deductions.
      "tokenForFutureUse": true, // Required. Value true, generates paymentTokenID for subsequent deductions.
      "merchantInitiated": false // false indicates user parameters are required; true indicates merchant-initiated deduction without user involvement.
    }
  }
}
```

orderAndPay Response Example:

```json
{
    "msg": "Success.",
    "code": "APPLY_SUCCESS",
    "data": {
        // Redirect URL
        "redirectUrl": "https://cashier-n-uat.payermax.com/static/processApiV2.html?tradeToken=T2025042306527802000033&integrate=DIRECT_API&country=UN&payRequestNo=20250423060120EP4366527897000250005&merchantId=010213834784554&merchantAppId=6666c8b036a24579974497c2f9a33333&token=902170aeaadb4621af8d9530398d0efa&orderLan=en&countryLan=en&strategyLan=LUBCO&pmaxLinkV=1",
        "outTradeNo": "APIFOXDEV1745388079422",
        "tradeToken": "T2025042306527802000033",
        "status": "PENDING"
    }
}
```

## 6. Obtain Subscription Plan Activation Result

You can obtain the activation result in the following two ways. It is recommended to use both:

1. **Asynchronous Notification**: After activation succeeds or fails, PayerMax sends a status notification to the `callbackUrl` passed when creating the subscription. `subscriptionStatus` changes to `ACTIVE` (activation successful) or `ACTIVE_FAILED` (activation failed). For detailed field definitions, please refer to the official API documentation.

2. **Active Query**: Query the current status of the subscription plan by `subscriptionNo` through the subscription query API or PayerMax Merchant Backend, as a fallback verification method when notifications are lost or delayed. For detailed field definitions, please refer to the official API documentation.

Please update the subscription status and user service entitlements in your system based on the final status returned by PayerMax. It is not recommended to determine whether activation is successful solely based on the redirect result of the frontend payment page.
