دليل ربط «اشترِ الآن وادفع لاحقاً»

دليل خطوة بخطوة لإضافة أقساط تطبيق كيو إلى صفحة الدفع في متجرك.

هذا الدليل التقني متوفر باللغة الإنجليزية فقط.

Contents

How it works

Buy Now, Pay Later (BNPL) is short-term financing that lets customers make a purchase now and pay for it later, interest-free. You add QPay as a payment method at checkout, and your platform calls five QPay APIs.

  1. 1List of PlansThe customer chooses QPay at checkout. You show the installment plans.
  2. 2Generate OTPThe customer picks a plan. QPay sends them a one-time password (OTP).
  3. 3List of CardsThe customer enters the OTP. You show their cards.
  4. 4Confirm PlanThe customer picks a card and confirms. QPay creates the loan and charges the card.
Later, if needed: RefundReturn all or part of the amount to the customer after the sale.

Steps 1 to 4 run during checkout, in this order. Customers must already be registered with QPay.

How to use this guide. Read it from top to bottom. Set up once, learn the rules every call follows, then build the four checkout steps. Each step shows the request, the response, and what to keep for the next step.

Next: Before you start

Before you start

Do these once, before you write any code.

Get these from QPay

  • Merchant ID. Send it in the x-Merchant-ID header on every call. QPay uses it to find your certificate.
  • Merchant service ID. Send it as merchantId on List of Plans and Confirm Plan, and as the sender on Refund.
  • A test customer. A mobile number registered with QPay, to test with in UAT. You can also send QPay a mobile number of your own, and QPay adds it for testing.

Create your key and certificate

Create an RSA key pair on the server that will sign your requests. You send QPay the certificate only.

  • Key: RSA, 2048 bits or more.
  • Certificate: SHA-256, valid for 2 years, with the country, organization and common name filled in.
OpenSSL
# 1. Private key: RSA, 2048 bits. Keep this file on your server and never share it.
openssl genrsa -out private.key 2048

# 2. Certificate signing request. OpenSSL asks for your details. Fill in at least
#    Country Name, Organization Name and Common Name. Type . to leave a field empty.
openssl req -new -key private.key -out request.csr

# 3. Certificate, valid for 2 years. Send certificate.pem to QPay.
openssl x509 -req -in request.csr -signkey private.key -out certificate.pem -days 730 -sha256

Send QPay certificate.pem. QPay registers it for UAT and production. Never send private.key, and keep it out of source control.

Using Java, or a key in the older format?

The Java sample reads a PKCS#12 keystore. Create it from the same key and certificate:

OpenSSL
# Java only: put the key and certificate in the keystore the Java sample reads.
# Enter a password when asked. Pass it as keyStorePassword, and "merchant" as certificateAlias.
openssl pkcs12 -export -inkey private.key -in certificate.pem -name merchant -out keystore.p12

OpenSSL 3 writes the private key in PKCS#8 format, which starts with -----BEGIN PRIVATE KEY-----. The Node.js, Python and Postman samples read it as it is. If your key starts with -----BEGIN RSA PRIVATE KEY-----, convert it:

OpenSSL
# Only if private.key starts with -----BEGIN RSA PRIVATE KEY-----
openssl pkcs8 -topk8 -nocrypt -in private.key -out private-pkcs8.key

UAT and production

UATTest environment

Build and test your integration here, with the test credentials QPay gives you.

Host
https://bnpl-api.fintec.solutionsDownload the Postman collection98 KB
ProductionLive environment

Real customers and real card payments. Move here when your UAT tests pass and QPay has issued your production credentials.

Host
https://bnpl-api-prod.fintec.solutionsDownload the Postman collection33 KB

Both environments use the same API paths and the same signing rules. QPay registers your certificate in each one, and issues separate credentials for production. Each Postman collection holds all five requests and signs them for you. See Test in UAT.

Next: How every call works

How every call works

All five APIs follow the same rules, so you build this part once.

Send a POST request

  • Send a POST request with a JSON body to the host plus the API path. All five paths start with /bnpl/mw.
  • Allow at least 60 seconds before your HTTP client times out. Confirm Plan runs several checks and a card payment in one call.
  • Stay under 30 requests a minute.

Headers

HeaderRequirementDescription
tokenRequiredBase64 signature of the request body, made with your private key. See Sign the body.
x-Merchant-IDRequiredYour merchant ID. QPay uses it to find the certificate that checks token.
Content-TypeRequiredapplication/json
AcceptRecommendedapplication/json
Example with cURL
# body.json must hold the exact bytes you signed.
curl -X POST "https://bnpl-api.fintec.solutions/bnpl/mw/list-plans" \
  -H "Content-Type: application/json" \
  -H "Accept: application/json" \
  -H "x-Merchant-ID: {your-merchant-id}" \
  -H "token: {base64-signature-of-body}" \
  --data-binary @body.json

Sender details

Every request body starts with senderInfo, which says who is making the call.

FieldTypeRequirementDescription
senderInfo.langintegerRequiredLanguage ID. 1 for English, 3 for Arabic. QPay returns desc in this language.
senderInfo.senderstringRequiredOn the four checkout calls: the customer’s mobile number registered with QPay, for example 0096812345678. On Refund: your merchant service ID.
senderInfo.senderTypestringRequiredM for a customer mobile, on the four checkout calls. C for a merchant service, on Refund only.
senderInfo.msgIdstringRequiredUnique ID for this call. Generate a new value every time. Reusing one can return reason 46 (Duplicate message ID).
senderInfo.deviceIdstringRecommendedID of the device that sent the request. QPay stores it with the transaction, so you can see which device made a call when you debug it.
senderInfo.otpstringRequired on 2 APIsHashed OTP. Mandatory on List of Cards and Confirm Plan. Leave it out on the other calls. See Hash the OTP.

Sign the body

QPay checks a signature on every request, so sign the exact body you send.

  1. Build the JSON body once, as a string.
  2. Sign the UTF-8 bytes of that string with your private key, using SHA256withRSA (RSA PKCS #1 v1.5 with SHA-256).
  3. Encode the signature in Base64, and send it in the token header.
  4. Send that same string as the body. If anything changes after signing, even spacing or key order, QPay returns reason 49 (Invalid signature).

Sign

import java.io.InputStream;
import java.nio.charset.Charset;
import java.security.Key;
import java.security.KeyStore;
import java.security.PublicKey;
import java.security.Signature;
import java.security.cert.X509Certificate;
import java.security.interfaces.RSAPrivateKey;
import java.util.Base64;

public class Security {

    public boolean verifySign(String signature, String value, String algorithm, String encoding,
                              String keyStorePassword, String certificateAlias) throws Exception {
        X509Certificate cert = loadCertificate(keyStorePassword, certificateAlias);
        PublicKey publicKey = cert.getPublicKey();
        Signature sig = Signature.getInstance(algorithm);
        sig.initVerify(publicKey);
        sig.update(value.getBytes(Charset.forName(encoding)));
        return sig.verify(Base64.getDecoder().decode(signature));
    }

    public String sign(String value, String algorithm, String encoding,
                       String keyStorePassword, String certificateAlias) throws Exception {
        RSAPrivateKey privateKey = (RSAPrivateKey) loadPrivateKey(keyStorePassword, certificateAlias);
        Signature sig = Signature.getInstance(algorithm);
        sig.initSign(privateKey);
        sig.update(value.getBytes(Charset.forName(encoding)));
        return Base64.getEncoder().encodeToString(sig.sign());
    }

    private X509Certificate loadCertificate(String keyStorePassword, String certificateAlias) throws Exception {
        return (X509Certificate) loadKeyStore(keyStorePassword).getCertificate(certificateAlias);
    }

    private Key loadPrivateKey(String keyStorePassword, String certificateAlias) throws Exception {
        return loadKeyStore(keyStorePassword).getKey(certificateAlias, keyStorePassword.toCharArray());
    }

    private KeyStore loadKeyStore(String keyStorePassword) throws Exception {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        try (InputStream stream = classLoader.getResourceAsStream("keystore.p12")) {
            KeyStore keystore = KeyStore.getInstance("PKCS12");
            keystore.load(stream, keyStorePassword.toCharArray());
            return keystore;
        }
    }
}
const crypto = require('crypto');

// rawBody is the exact JSON string you will send.
function sign(rawBody, privateKeyPem) {
  return crypto
    .sign('RSA-SHA256', Buffer.from(rawBody, 'utf8'), privateKeyPem)
    .toString('base64');
}

function verifySign(rawBody, signature, publicKeyPem) {
  return crypto.verify(
    'RSA-SHA256',
    Buffer.from(rawBody, 'utf8'),
    publicKeyPem,
    Buffer.from(signature, 'base64'),
  );
}

module.exports = { sign, verifySign };
import base64

from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import padding


# raw_body is the exact JSON string you will send.
def sign(raw_body, private_key_pem):
    key = serialization.load_pem_private_key(private_key_pem, password=None)
    signature = key.sign(raw_body.encode("utf-8"), padding.PKCS1v15(), hashes.SHA256())
    return base64.b64encode(signature).decode("ascii")


def verify_sign(raw_body, signature, public_key_pem):
    key = serialization.load_pem_public_key(public_key_pem)
    try:
        key.verify(
            base64.b64decode(signature),
            raw_body.encode("utf-8"),
            padding.PKCS1v15(),
            hashes.SHA256(),
        )
        return True
    except InvalidSignature:
        return False

In Java, call sign with SHA256withRSA and UTF-8, and your own keystore password and alias. To create keystore.p12, see Create your key and certificate.

Send

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class SendRequest {

    public static String send(String baseUrl, String path, String rawBody, String merchantId,
                              String keyStorePassword, String certificateAlias) throws Exception {
        String token = new Security().sign(rawBody, "SHA256withRSA", "UTF-8",
                keyStorePassword, certificateAlias);

        HttpRequest request = HttpRequest.newBuilder(URI.create(baseUrl + path))
                .header("Content-Type", "application/json")
                .header("Accept", "application/json")
                .header("x-Merchant-ID", merchantId)
                .header("token", token)
                .POST(HttpRequest.BodyPublishers.ofString(rawBody))
                .build();

        return HttpClient.newHttpClient()
                .send(request, HttpResponse.BodyHandlers.ofString())
                .body();
    }
}
const { sign } = require('./sign');

// Build the body once, sign that string, and send that same string.
async function send(baseUrl, path, payload, merchantId, privateKeyPem) {
  const rawBody = JSON.stringify(payload);

  const response = await fetch(baseUrl + path, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      Accept: 'application/json',
      'x-Merchant-ID': merchantId,
      token: sign(rawBody, privateKeyPem),
    },
    body: rawBody,
  });

  return response.json();
}

module.exports = { send };
import json
import urllib.request

from sign import sign


# Build the body once, sign that string, and send that same string.
def send(base_url, path, payload, merchant_id, private_key_pem):
    raw_body = json.dumps(payload, separators=(",", ":"))

    request = urllib.request.Request(
        base_url + path,
        data=raw_body.encode("utf-8"),
        method="POST",
        headers={
            "Content-Type": "application/json",
            "Accept": "application/json",
            "x-Merchant-ID": merchant_id,
            "token": sign(raw_body, private_key_pem),
        },
    )

    with urllib.request.urlopen(request) as response:
        return json.load(response)

QPay signs its responses too, in the token response header. To check one, verify the raw response body with QPay’s certificate in the same way.

Check a signature on your own machine

Sign a body with OpenSSL and compare the result with your code. The same body and the same key always give the same signature, so the two token values must match. If QPay returns reason 49 and the values differ, your code is signing different bytes from the ones it sends, or using another key.

OpenSSL
# 1. Save the exact body you send, with no line break at the end.
printf '%s' '{"senderInfo":{"lang":1,"sender":"0096812345678","senderType":"M","msgId":"b7c1e0a0-6c2a-4d1e-9f10-2a6c0e1b1001","deviceId":"web-checkout-01"},"amount":"25.500","merchantId":"MERCHANT01"}' > body.json

# 2. Sign it. The line printed is the value for the token header.
openssl dgst -sha256 -sign private.key -out body.sig body.json
openssl base64 -A -in body.sig; echo

# 3. Check it with your certificate. Expect "Verified OK".
openssl x509 -in certificate.pem -pubkey -noout > public.pem
openssl dgst -sha256 -verify public.pem -signature body.sig body.json

The commands run in a Linux or macOS terminal, or in a Bash shell on Windows.

Never paste your private key into a website or online tool to test a signature. Anyone who has the key can sign requests as you.

Read the response

Every result comes back with HTTP 200, failures included. Read responseInfo before any other field.

FieldTypeDescription
responseInfo.errorCdstringThe result code. 00 means success. Any other value is a reason ID from Error codes, for example 89 for Invalid OTP.
responseInfo.descstringDescription of the result, in the language set by senderInfo.lang. Success on success.
responseInfo.statusCodestringWhat happened. See the table below.
responseInfo.loanIdstringLoan ID. Set by Confirm Plan, and returned again on Refund results. null on the other APIs.
responseInfo.failureReasonsarray of stringExtra detail for reason 70, when the loan service gives it. Usually null.

What to do with each status

statusCodeMeaningWhat to do
1 SuccessSuccessContinue. On Confirm Plan, complete the order.
3 RejectedRejectedStop, and show the customer the reason from desc. Validation errors also return 3.
4 PendingPendingRefund only. The refund is not final, so do not send it again. Ask QPay for the final result.
5 FailedFailedConfirm Plan only. The card payment did not go through, so do not complete the order.

A failed call looks like this:

Failed response
{
  "responseInfo": {
    "errorCd": "49",
    "desc": "Invalid Credentials",
    "statusCode": "3",
    "loanId": null,
    "failureReasons": null
  }
}

Here desc says Invalid Credentials, and the reason is 49 (Invalid signature). QPay manages the desc texts, and they follow the language you send, so compare on errorCd. Every reason ID is in Error codes.

HTTP 400 with no responseInfo body means the request format is wrong: a required field is missing, a JSON type is wrong, or senderType is not M or C. Fix the request before you try again.

Responses can contain other fields that are empty. Ignore any field this guide does not list.

Next: List of Plans

Step 1 of 4

List of Plans

POST/bnpl/mw/list-plans

Returns the installment plans available for a purchase amount and a merchant. Call this when the customer chooses QPay at checkout.

Sender
Customer mobile
Sender type
M
OTP
Not used

Request

FieldTypeRequirementDescription
senderInfoobjectRequiredThe customer’s mobile number, with senderType M. See Sender details.
amountstringRequiredPurchase amount as a decimal string, for example 25.500.
merchantIdstringRequiredYour merchant service ID, issued by QPay.
Request body
{
  "senderInfo": {
    "lang": 1,
    "sender": "0096812345678",
    "senderType": "M",
    "msgId": "b7c1e0a0-6c2a-4d1e-9f10-2a6c0e1b1001",
    "deviceId": "web-checkout-01"
  },
  "amount": "1.000",
  "merchantId": "MERCHANT01"
}

Response

FieldTypeDescription
principalIdintegerPlan principal ID. Send this value as planInfo.principleId on Confirm Plan. It can be negative, so store it as a signed integer and send it back unchanged.
plans[]arrayInstallment options. When none are available, QPay returns reason 319 (No plans available) and plans is null, so check statusCode before you read it.
plans[].namestringName of the installment option.
plans[].descriptionstringDescription of the installment option. Can be null.
plans[].penaltiesarray of stringPenalty texts. Currently always ["No Penalties"].
plans[].numberOfRepaymentsintegerNumber of installments.
plans[].typestringPlan type name.
plans[].idintegerInstallment plan ID. Send this value as planInfo.planId on Confirm Plan.
plans[].installments[]arrayInstallment schedule.
plans[].installments[].dueDatestringDue date, as yyyy-MM-dd.
plans[].installments[].amountnumberInstallment amount.
plans[].installments[].periodintegerInstallment number in the schedule.
plans[].installments[].loanBalanceAfterPaymentnumberRemaining loan balance after this installment.
Success response
{
  "responseInfo": {
    "errorCd": "00",
    "desc": "Success",
    "statusCode": "1",
    "loanId": null,
    "failureReasons": null
  },
  "plans": [
    {
      "name": "QPAY BNPL",
      "description": null,
      "penalties": [
        "No Penalties"
      ],
      "numberOfRepayments": 4,
      "type": "MONTHLY",
      "id": 1,
      "installments": [
        {
          "dueDate": "2026-06-23",
          "amount": 0.25,
          "period": 1,
          "loanBalanceAfterPayment": 0.75
        },
        {
          "dueDate": "2026-07-23",
          "amount": 0.25,
          "period": 2,
          "loanBalanceAfterPayment": 0.5
        },
        {
          "dueDate": "2026-08-23",
          "amount": 0.25,
          "period": 3,
          "loanBalanceAfterPayment": 0.25
        },
        {
          "dueDate": "2026-09-23",
          "amount": 0.25,
          "period": 4,
          "loanBalanceAfterPayment": 0
        }
      ]
    }
  ],
  "principalId": -208453800
}

Keep for later. Keep principalId, and the id of the plan the customer picks. You send both on Confirm Plan.

Results to handle

  • 3 Rejected319No plans available. plans and principalId are null.
  • 3 Rejected241Invalid merchant service ID. merchantId does not match a merchant service.
  • 3 Rejected49Invalid signature. The token header does not match the body.

Every result this call can return is in Error codes.

Next: Generate OTP

Step 2 of 4

Generate OTP

POST/bnpl/mw/generate-otp

Creates a one-time password and sends it to the customer’s mobile number by notification. Call this after the customer selects a plan.

Sender
Customer mobile
Sender type
M
OTP
Sends the OTP
  • The sender is always the customer, because the customer receives the OTP. Send the customer’s mobile number in sender with senderType M.
  • The OTP is never returned in the response. Show a screen where the customer enters it, then hash it for List of Cards and Confirm Plan.
  • Calling this API resets the OTP retry count for the mobile number.

Request

FieldTypeRequirementDescription
senderInfoobjectRequiredThe customer’s mobile number, with senderType M. QPay sends the OTP to this number. See Sender details.
storeInformationobjectRecommendedDetails of your store. Send the object with a name, or leave it out. Do not send it as null.
storeInformation.namestringRecommendedYour store name. QPay includes it in the OTP message the customer receives.
Request body
{
  "senderInfo": {
    "lang": 1,
    "sender": "0096812345678",
    "senderType": "M",
    "msgId": "b7c1e0a0-6c2a-4d1e-9f10-2a6c0e1b1002",
    "deviceId": "web-checkout-01"
  },
  "storeInformation": {
    "name": "Your Store"
  }
}

Response

The response has responseInfo only. See Read the response.

Success response
{
  "responseInfo": {
    "errorCd": "00",
    "desc": "Success",
    "statusCode": "1",
    "loanId": null,
    "failureReasons": null
  }
}

Results to handle

  • 3 Rejected4Mobile not registered. The mobile number is not registered with QPay.
  • 3 Rejected46Duplicate message ID. msgId was already used.

Every result this call can return is in Error codes.

Next: List of Cards

Step 3 of 4

List of Cards

POST/bnpl/mw/list-card

Returns the cards registered on the customer’s mobile number. QPay checks the hashed OTP before it returns any cards. Call this after the customer enters the OTP.

Sender
Customer mobile
Sender type
M
OTP
Mandatory

Before you call: hash the OTP

Hash the OTP the customer typed, and send the hash in senderInfo.otp. The OTP is mandatory on List of Cards and Confirm Plan, and you send the same hash on both.

  • Take the OTP exactly as the customer typed it, as UTF-8 text.
  • Hash it with SHA-256, and encode the hash bytes in Base64.
  • Check your code: 123456 must give jZae727K08KaOmKSgOaGzww/XVqGr/PKEgIMkjrcbJI=.
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.util.Base64;

public class OtpHash {

    public static String hash(String value) throws Exception {
        String encoding = "UTF-8";
        String hashingAlgorithm = "SHA-256";
        MessageDigest msgDig = MessageDigest.getInstance(hashingAlgorithm);
        msgDig.reset();
        msgDig.update(value.getBytes(Charset.forName(encoding)));
        return new String(Base64.getEncoder().encode(msgDig.digest()));
    }
}
const crypto = require('crypto');

function hashOtp(otp) {
  return crypto.createHash('sha256').update(otp, 'utf8').digest('base64');
}

module.exports = { hashOtp };
import base64
import hashlib


def hash_otp(otp):
    digest = hashlib.sha256(otp.encode("utf-8")).digest()
    return base64.b64encode(digest).decode("ascii")
Check a hash from the command line

OpenSSL gives the same result as the code above:

OpenSSL
# 123456 must print jZae727K08KaOmKSgOaGzww/XVqGr/PKEgIMkjrcbJI=
printf '%s' '123456' | openssl dgst -sha256 -binary | openssl base64 -A; echo

Never send the plain OTP. Do not add anything to the value, such as a customer ID, and do not hash it a second time.

OTP limits

  • A wrong or empty OTP returns reason 89 (Invalid OTP). An expired one returns reason 88 (Expired OTP). Both count as a failed attempt.
  • QPay sets how long an OTP stays valid and how many failed attempts are allowed. The attempt that reaches the limit still returns 89 or 88, and blocks the mobile number.
  • After the block, List of Cards returns reason 72 (Customer mobile blocked), and Confirm Plan returns reason 207 (Maximum OTP attempts reached).
  • Calling Generate OTP sends a new OTP and resets the attempt count.

This request has no merchantId and no amount.

Request

FieldTypeRequirementDescription
senderInfoobjectRequiredThe customer’s mobile number, with senderType M, and the hashed OTP. See Sender details.
senderInfo.otpstringRequiredHashed OTP. Mandatory on this API. See OTP hashing. An empty value returns reason 89 (Invalid OTP).
Request body
{
  "senderInfo": {
    "lang": 1,
    "sender": "0096812345678",
    "senderType": "M",
    "msgId": "b7c1e0a0-6c2a-4d1e-9f10-2a6c0e1b1003",
    "deviceId": "web-checkout-01",
    "otp": "Base64Sha256OfTheOtp"
  }
}

Response

FieldTypeDescription
cards[]arrayCards on the customer’s mobile number.
cards[].accountstringCard account reference, such as BNPL001. Send this value unchanged as planInfo.account on Confirm Plan.
cards[].cardNumberstringCard number, masked except for the last four digits, for example xxxx-xxxx-xxxx-1234. Always show it masked.
cards[].expiryDatestringCard expiry date as MM/yyyy, for example 12/2030. Can be null.
cards[].cardHolderNamestringCardholder name. Can be null, so do not rely on it to identify the card.
Success response
{
  "responseInfo": {
    "errorCd": "00",
    "desc": "Success",
    "statusCode": "1",
    "loanId": null,
    "failureReasons": null
  },
  "cards": [
    {
      "account": "BNPL002",
      "cardNumber": "xxxx-xxxx-xxxx-8785",
      "expiryDate": "12/2030",
      "cardHolderName": null
    },
    {
      "account": "BNPL001",
      "cardNumber": "xxxx-xxxx-xxxx-1111",
      "expiryDate": null,
      "cardHolderName": null
    }
  ]
}

Keep for later. Keep the hashed OTP, and the account of the card the customer picks. You send both on Confirm Plan.

Results to handle

  • 3 Rejected89Invalid OTP. The OTP hash does not match. This counts as a failed attempt.
  • 3 Rejected88Expired OTP. The OTP was right but has expired. Call Generate OTP again.
  • 3 Rejected72Mobile blocked. Too many failed OTP attempts blocked the mobile number.

Every result this call can return is in Error codes.

Next: Confirm Plan

Step 4 of 4

Confirm Plan

POST/bnpl/mw/confirm-plan

Confirms the selected plan, creates the loan, and charges the selected card for the purchase amount. Call this when the customer confirms the plan and pays.

Sender
Customer mobile
Sender type
M
OTP
Mandatory

What this call does

  1. Credit checkQPay also verifies the hashed OTP here, then clears it. The OTP is not checked again in the later steps.
  2. Customer verificationQPay confirms the customer can go ahead with this purchase.
  3. Plan confirmation and card paymentQPay creates the loan and charges the selected card.

One call runs all three steps. Any of them can end the request, and you do not call them separately.

Request

FieldTypeRequirementDescription
senderInfoobjectRequiredThe customer’s mobile number, with senderType M, and the hashed OTP. See Sender details.
senderInfo.otpstringRequiredHashed OTP. Mandatory on this API. Send the same hash you sent to List of Cards. See OTP hashing.
planInfoobjectRequiredThe selected plan and card.
planInfo.planIdintegerRequiredThe id of the selected plan from List of Plans.
planInfo.principleIdintegerRequiredThe principalId from List of Plans. Note the spelling: principleId in this request, principalId in the List of Plans response.
planInfo.merchantIdstringRequiredYour merchant service ID. Use the same merchant as on List of Plans.
planInfo.accountstringRequiredThe account of the selected card from List of Cards, unchanged.
amountstringRequiredPurchase amount as a decimal string, for example 25.500. This field sits beside planInfo, not inside it.
Request body
{
  "senderInfo": {
    "lang": 1,
    "sender": "0096812345678",
    "senderType": "M",
    "msgId": "b7c1e0a0-6c2a-4d1e-9f10-2a6c0e1b1004",
    "deviceId": "web-checkout-01",
    "otp": "Base64Sha256OfTheOtp"
  },
  "planInfo": {
    "planId": 1,
    "principleId": -208453800,
    "merchantId": "MERCHANT01",
    "account": "BNPL002"
  },
  "amount": "1.000"
}

Response

FieldTypeDescription
responseInfo.loanIdstringLoan ID, inside responseInfo. Set when the loan is created, and stays set if the card payment is then rejected or fails. Send this value as refundInfo.loanId.
transactionIdstringCard-payment transaction ID, set when the payment call returns a result. Used for status inquiries.
tokenstringSaved card token, unrelated to the token request header. Set only when the payment is accepted.
  • Any errorCd other than 00 is not a successful payment.
  • Some failed responses also return planId and principalId beside responseInfo. You can ignore them.
Success response
{
  "responseInfo": {
    "errorCd": "00",
    "desc": "Success",
    "statusCode": "1",
    "loanId": "100245",
    "failureReasons": null
  },
  "transactionId": "tp-9f2c1",
  "token": "saved-card-token"
}

Keep for later. Keep responseInfo.loanId from every response, even when the payment is rejected or fails, and keep transactionId when it is set. You send loanId unchanged on Refund.

Results to handle

  • 3 Rejected59Rejected. The bank declined the card payment, for example for insufficient funds.
  • 5 Failed36Failed. The card payment did not go through. Do not complete the order.
  • 3 Rejected70Invalid plan. planId or principleId is missing or invalid.
  • 3 Rejected89Invalid OTP. Nothing was charged. This counts as a failed OTP attempt.
  • 3 Rejected2System error. Try again later with a new msgId.

Every result this call can return is in Error codes.

Next: Refund

After the sale

Refund

POST/bnpl/mw/bnpl-refund

Refunds an amount on an active loan for your merchant service. Call this after the sale, when you need to return money to the customer.

Sender
Your merchant service
Sender type
C
OTP
Not used
  • No OTP is needed. The sender is your merchant service, not the customer.
  • Partial refunds are allowed until the refunded total would exceed the original transaction amount.
  • A refund is accepted only within the refund period after the original transaction, and only while the loan is active.

Request

FieldTypeRequirementDescription
senderInfoobjectRequiredYour merchant service ID, with senderType C. This is the service key issued by QPay, not a display name. No OTP. See Sender details.
refundInfoobjectRequiredThe loan and the amount to refund.
refundInfo.loanIdstringRequiredLoan ID from responseInfo.loanId on Confirm Plan, sent unchanged.
refundInfo.amountstringRequiredRefund amount as a decimal string, for example 0.500.
Request body
{
  "senderInfo": {
    "lang": 1,
    "sender": "MERCHANT01",
    "senderType": "C",
    "msgId": "b7c1e0a0-6c2a-4d1e-9f10-2a6c0e1b1005",
    "deviceId": "web-checkout-01"
  },
  "refundInfo": {
    "loanId": "100245",
    "amount": "0.500"
  }
}

Response

The response has responseInfo only. See Read the response.

  • Refund results return the loan ID you sent in responseInfo.loanId.
  • A gateway rejection and a gateway failure both return statusCode 4. Use errorCd to tell them apart.
Success response
{
  "responseInfo": {
    "errorCd": "00",
    "desc": "Success",
    "statusCode": "1",
    "loanId": "100245",
    "failureReasons": null
  }
}

Results to handle

  • 4 Pending59 or 36Gateway rejected or failed. QPay records the refund as pending.
  • 3 Rejected58Amount not allowed. The amount is more than what is left to refund.
  • 3 Rejected201Already refunded. This transaction was already refunded.
  • 3 Rejected34Transaction not found. Check loanId and the merchant service.

Every result this call can return is in Error codes.

Next: Test and go live

Test and go live

Test in UAT

Run the whole journey in UAT before you go live. The quickest way is QPay’s Postman collection. It holds all five requests, signs each one and hashes the OTP for you. Download it from UAT and production.

  1. Import the collection into Postman with File, then Import.
  2. Open the collection’s Variables tab. Fill in your private key, merchant ID, merchant service ID, the customer’s mobile number, the amount, your device ID and your store name.
  3. Send the requests in call order. Before List of Cards, enter the OTP the customer received in the OTP variable.
  4. In Confirm Plan, replace planId and principleId with the values List of Plans returned. Wrong values return reason 70.

Postman stores collection variables in your workspace. Use a test key, never your production key, in a shared workspace.

Checklist before you go live

  • Keep your private key on your server, and sign and call QPay from your backend only.
  • Generate a new msgId for every call.
  • Send deviceId on every call, so a request can be traced to the device that sent it.
  • Hash the OTP once with SHA-256 and Base64, and reuse the same hash for List of Cards and Confirm Plan.
  • Sign the exact bytes of the JSON body you send, and send the signature in the token header.
  • Send amount as a decimal string, such as "1.000", on List of Plans, Confirm Plan and Refund.
  • Keep responseInfo.loanId from every Confirm Plan response, even when the payment is rejected or fails, and send it unchanged on Refund.
  • Complete an order only on statusCode 1. Treat 4 as pending, not as a final rejection.
  • Check statusCode and errorCd before you read any other field. Failures also come back with HTTP 200.
  • Allow at least 60 seconds before your HTTP client times out, and stay under 30 requests a minute.

When every item is done, switch to the production host and your production credentials.

Next: Error codes

Error codes

Every result QPay can return, by call. errorCd carries the reason ID, and statusCode tells you what to do.

Start with Any call, which applies to all five APIs. The four checkout calls also run the customer checks. Success is always errorCd 00 with statusCode 1.

Any call

All five APIs can return these.

Reason IDResultstatusCodeWhen it happens
49Invalid signature3 Rejectedtoken does not verify against the raw request body, or it cannot be verified.
79Language not supported3 RejectedsenderInfo.lang is not a supported language.
46Duplicate message ID3 RejectedmsgId has already been used.
38Service currently unavailable3 RejectedThe requested operation is currently unavailable. Contact QPay if this continues.
70Service integration failure3 RejectedThe loan service could not complete the request. On Confirm Plan, this also happens when planInfo.planId or planInfo.principleId is missing or invalid. The response may include more detail in failureReasons.
2Internal system error3 RejectedAn unexpected error at QPay stopped the request. Try again later with a new msgId, and contact QPay if it continues.

Customer checks

List of Plans, Generate OTP, List of Cards and Confirm Plan check the customer’s mobile number first.

Reason IDResultstatusCodeWhen it happens
4Customer mobile not registered3 RejectedThe mobile number is missing or is not registered with QPay.
188Customer mobile dormant3 RejectedThe mobile number is dormant.
8Customer mobile not active3 RejectedThe mobile number is inactive.
72Customer mobile blocked3 RejectedThe mobile number is blocked. This can follow too many failed OTP attempts. See OTP limits.
7Customer not active3 RejectedThe customer exists but is inactive.
92Customer account not found3 RejectedThe customer’s mobile account is missing.
94Customer account not active3 RejectedThe customer’s mobile account is inactive.

List of Plans

Reason IDResultstatusCodeWhen it happens
241Invalid merchant service ID3 RejectedNo merchant service exists for merchantId.
319No plans available3 RejectedNo installment plans are available for this purchase. plans and principalId are null.
311Credit score unavailable3 RejectedThe customer’s credit score could not be found, so no plans can be offered.
173Credit limit exceeded3 Rejectedamount is above the customer’s available credit limit.
VariesLoan service reason3 RejectedThe loan service could not return plans. errorCd and desc carry the reason from the loan service.

Generate OTP

Reason IDResultstatusCodeWhen it happens
3Request not allowed3 RejectedThe sender’s profile does not allow this request type.

List of Cards

Reason IDResultstatusCodeWhen it happens
207Maximum OTP attempts reached3 RejectedThe customer has already used all allowed OTP attempts. QPay checks this before the OTP value.
89Invalid OTP3 Rejectedotp is empty, or the hash does not match. This counts as a failed attempt and blocks the mobile number when the attempts run out.
88Expired OTP3 RejectedThe OTP matches, but its validity period has passed. This counts as a failed attempt in the same way as reason 89.

Confirm Plan

Reason IDResultstatusCodeWhen it happens
OTP checks
207Maximum OTP attempts reached3 RejectedThe customer has already used all allowed OTP attempts. QPay checks this before the OTP value.
89Invalid OTP3 Rejectedotp is empty, or the hash does not match. This counts as a failed attempt and blocks the mobile number when the attempts run out.
88Expired OTP3 RejectedThe OTP matches, but its validity period has passed. This counts as a failed attempt in the same way as reason 89.
Credit check
311Credit score unavailable3 RejectedThe customer’s credit score could not be retrieved in time.
Customer verification
318Credit check not passed3 RejectedThe customer’s credit assessment was rejected.
315Customer verification rejected3 RejectedThe customer did not pass verification.
317Customer verification needs review3 RejectedThe customer needs further review before this purchase can go ahead.
19Request timed out3 RejectedThe verification step timed out.
36Bank connection failure3 RejectedThe verification step failed because of a connection problem.
Plan confirmation
27Merchant service not registered3 RejectedNo merchant service exists for planInfo.merchantId.
191Merchant service dormant3 RejectedThe merchant service is dormant.
23Merchant service not active3 RejectedThe merchant service is inactive.
274Merchant service blocked3 RejectedThe merchant service is blocked.
241Invalid merchant service ID3 RejectedThe merchant’s service details are incomplete.
349Customer has a pending loan3 RejectedThe customer already has a loan in pending status.
311Credit score unavailable3 RejectedThe customer’s credit category or remaining loan balance is missing.
318Credit check not passed3 RejectedThe customer’s credit category is not allowed for this purchase.
173Credit limit exceeded3 Rejectedamount plus the customer’s remaining balance is above their credit limit.
345Merchant not included in plan3 RejectedThe selected plan does not include this merchant.
VariesLoan service reason3 RejectedThe loan service rejected the plan before a loan ID was returned. errorCd and desc carry the reason from the loan service.
348Pending transaction exists3 RejectedA debit transaction for this loan already exists. loanId is already set.
Card payment
59Bank rejected the payment3 RejectedThe bank did not accept the card payment, for example because of insufficient funds. The loan and its pending transactions are rejected. loanId is set.
36Bank connection failure5 FailedThe card payment did not go through: it returned no result, or the payment call failed. loanId is set. Do not complete the order.

Refund

Reason IDResultstatusCodeWhen it happens
Request checks
3Request not allowed3 RejectedThe sender’s profile does not allow this request type.
Merchant service checks
39Merchant service not registered3 RejectedThe merchant service is missing.
190Merchant service dormant3 RejectedThe merchant service is dormant.
25Merchant service not active3 RejectedThe merchant service is inactive.
204Merchant service blocked3 RejectedThe merchant service is blocked.
26Merchant not active3 RejectedThe merchant is inactive.
92Merchant account not found3 RejectedThe merchant service account is missing.
94Merchant account not active3 RejectedThe merchant service account is inactive.
Refund checks
34Transaction not found3 RejectedNo confirmed original transaction exists for this loan and merchant service.
201Transaction already refunded3 RejectedThe original transaction is already marked as refunded.
58Refund amount not allowed3 Rejectedamount is greater than the original amount minus earlier refunds.
299Loan not active3 RejectedThe loan is not active.
305Refund period expired3 RejectedThe refund period for the original transaction has ended.
348Pending transaction exists3 RejectedA pending transaction already exists for this loan.
VariesLoan service reason3 RejectedThe loan service rejected the refund. errorCd and desc carry the reason from the loan service.
59Bank rejected the refund4 PendingThe card gateway did not complete the refund. QPay records this as pending, so statusCode is 4.
36Bank connection failure4 PendingThe card gateway returned no result, or the gateway call failed.