SCB Direct Debit API - Developer Implementation Guide

1. Overview

This guide provides technical implementation details for the Financial Team's SCB Direct Debit wrapper service. It covers authentication, encryption, and the core API integrations required to implement customer registration and payment processing.

2. Database Schema

The SCB Direct Debit integration requires three main database tables to track merchant configurations, registrations and transactions. Note that merchant-specific financial configuration data (such as merchantId, subAccountId, billerId, and PUBLIC_KEY) is stored in a separate merchant table rather than the user table to properly segregate financial credentials from general user information.

2.1 merchants Table

This table stores all SCB-specific financial configuration data for users who act as merchants (payment receivers).

Column Data Type Description Constraints / Notes
id SERIAL Unique identifier for each merchant record. Primary Key
user_id INT Links to the user who owns this merchant configuration. FK to users(id), UNIQUE
merchant_id VARCHAR(50) SCB-assigned merchant identifier for this user's account. NOT NULL, UNIQUE
sub_account_id VARCHAR(50) SCB sub-account identifier for payment processing. NOT NULL
biller_id VARCHAR(50) SCB biller identifier for this merchant account. NOT NULL
public_key TEXT SCB public key used for encrypting API requests to SCB. NOT NULL
created_at TIMESTAMPTZ Date and time when merchant configuration was created. NOT NULL, Default: now()

2.2 scb_registrations Table

This table stores the unique reference ID needed to fetch the customer's bank details from SCB.

Column Data Type Description Constraints / Notes
reg_ref VARCHAR(20) Unique identifier created by the Financial Team that serves as the SCB regRef during customer registration. Primary Key
payer_user_id INT The customer who will make payments (Payer). FK to users(id)
receiving_user_id INT The merchant who will receive payments (Receiver). FK to users(id)
status VARCHAR(50) Registration status ('pending', 'success', 'failed'). NOT NULL, Default: 'pending'
created_at TIMESTAMPTZ Date and time when registration was started. NOT NULL, Default: now()

2.3 scb_debit_transactions Table

This table tracks individual payment transactions, storing the unique ID (ref_number) for each debit request and its completion status.

Column Data Type Description Constraints / Notes
ref_number VARCHAR(20) Unique identifier created by the Financial Team that serves as the SCB refNumber for payment processing. Primary Key
reg_ref VARCHAR(20) Links to the completed registration record that enables this payment. FK to scb_registrations(reg_ref)
ref_date_time TIMESTAMPTZ Date and time stamp sent to SCB as refDateTime for this transaction. NOT NULL
ref_time_date VARCHAR(14) Transaction reference time and date returned by SCB (refTimeDate). Indexed
customer_ref VARCHAR(50) Customer reference sent to SCB in format "payerId:receiverId" (customerRef). Indexed
amount NUMERIC(12,2) Amount of money to be debited from the customer's account. NOT NULL
currency VARCHAR(3) Currency code (e.g., USD, THB) for the transaction. NOT NULL
scb_txn_number VARCHAR(255) Transaction reference number provided by SCB after processing (txnNumber). Indexed
status VARCHAR(50) Final payment status ('confirmed', 'failed', 'refunded'). NOT NULL, Default: 'pending'
created_at TIMESTAMPTZ Date and time when the payment request was submitted. NOT NULL, Default: now()

3. Authentication System

3.1 Request Headers

Every API call to SCB requires standardized headers with specific parameters. All SCB API calls must include these headers consistently.

function getHeaders(resourceOwnerId) {
  return {
    'resourceOwnerId': resourceOwnerId, // Your API Key from environment configs
    'requestUId': require('crypto').randomUUID(), // UUID v4 for request tracking
    'accept-language': 'EN',
    'Content-Type': 'application/json'
  };
}

The resourceOwnerId is your SCB API key, and requestUId must be a fresh UUID v4 for each request to ensure proper request tracking and avoid conflicts.

2.2 OAuth Token Management

SCB requires OAuth2 authentication with automatic token refresh capability. The system must handle token expiration transparently.

2.2.1 Initial Token Acquisition

Your app's environment configuration contains applicationKey and applicationSecret credentials. Use the applicationKey as resourceOwnerId, and make a POST call with these to obtain both accessToken and refreshToken.

API Details:

2.2.2 Token Refresh Implementation

Your JavaScript function will be given the current accessToken and refreshToken. Before making any protected API call, check if the accessToken has expired. If expired, you'll need to use the applicationKey and applicationSecret from your app's environment configuration, then call the refresh endpoint using refreshToken to get new tokens.

Token Refresh API Details:

Implement automatic token refresh by checking token expiration before each protected API call. This creates a seamless system where you use refreshToken to get new accessToken and refreshToken without re-authentication.


3. Encryption System

All sensitive data exchanges with SCB APIs require RSA public key encryption using PKCS1 padding. The system uses the merchant's PUBLIC_KEY for encryption and decryption operations. You need to get the PUBLIC_KEY from the merchant table using the receiverUserId key.

3.1 Encryption Implementation

Use the merchant's PUBLIC_KEY to encrypt and decrypt JSON data. The Node.js "crypto" library handles encryption operations. Input is JSON data.

import fs from 'fs';
import crypto from 'crypto';

// ---------------- CONFIG ----------------
const PUBLIC_KEY_PATH = './public.pub'; // merchant's PUBLIC_KEY

// ---------------- CORE ENCRYPT FUNC ----------------
function encryptSCB(data) {
  let publicKey = fs.readFileSync(PUBLIC_KEY_PATH, 'utf8');

  if (!publicKey.includes('BEGIN PUBLIC KEY')) {
    publicKey = `-----BEGIN PUBLIC KEY-----\n${publicKey}\n-----END PUBLIC KEY-----`;
  }

  const buffer = Buffer.from(JSON.stringify(data));
  const encrypted = crypto.publicEncrypt(
    { key: publicKey, padding: crypto.constants.RSA_PKCS1_PADDING },
    buffer
  );

  return encrypted.toString('base64').replace(/\n/g, '');
}

3.2 Decryption Implementation

Response decryption is critical for retrieving payment status and registration data. The SCB API returns encrypted responses that must be decrypted using the public key with PKCS1 padding.

import fs from 'fs';
import crypto from 'crypto';
// ---------------- CONFIG ----------------
const PUBLIC_KEY_PATH = './public.pub'; // merchant's PUBLIC_KEY

// ---------------- CORE DECRYPT FUNC ----------------
function decryptSCBResponse(encryptedValue) {

  // Read the public key file that was used for encryption
  let publicKey = fs.readFileSync(PUBLIC_KEY_PATH, 'utf8');

  // Ensure proper PEM format for the public key
  // SCB expects standard PEM wrapper format
  if (!publicKey.includes('BEGIN PUBLIC KEY')) {
    publicKey = `-----BEGIN PUBLIC KEY-----\n${publicKey}\n-----END PUBLIC KEY-----`;
  }

  // Convert base64 encrypted string to buffer for decryption
  const buffer = Buffer.from(encryptedValue, 'base64');
  
  // Decrypt using public key with PKCS1 padding
  // This matches the encryption method used by SCB
  const decrypted = crypto.publicDecrypt(
    {
      key: publicKey,
      padding: crypto.constants.RSA_PKCS1_PADDING, // Must match SCB encryption
    },
    buffer
  );

    // Parse the decrypted response
    return JSON.parse(decrypted.toString('utf8'));
}

4. Registration Implementation

4.1 Registration Initialization

Initiates customer debit card registration process with SCB banking system.

API Details:

4.1.1 Request Preparation

When this API is called, you will be given payerUserId and receiverUserId. You need to get merchantId, subAccountId, and PUBLIC_KEY from the merchant table using the receiverUserId.

  1. Retrieve merchantId, subAccountId, and PUBLIC_KEY from merchant table using receiverUserId
  2. Use getHeaders() and your accessToken for Authorization Bearer type
  3. Generate unique regRef using format REG-xxxxxxxxx ([0-9a-f] hexadecimal)
  4. Prepare encrypted data payload using the Encryption section method

4.1.2 Registration Data Structure

Your JavaScript function will be given payerUserId, receiverUserId, and backUrl. You'll need to generate a unique regRef and retrieve the merchant's merchantId, subAccountId, and PUBLIC_KEY from the merchant table using the receiverUserId. When using PostgreSQL, use the database's UUID generation for uniqueness.

// Generate unique registration reference using PostgreSQL UUID
// Execute: SELECT gen_random_uuid() to get a UUID, then format it
const uuidResult = await db.query('SELECT gen_random_uuid() as id');
const regRef = 'REG-' + uuidResult.rows[0].id.replace(/-/g, '').substring(0, 18).toUpperCase();

// Store in scb_registrations table
await db.query(`
  INSERT INTO scb_registrations (reg_ref, payer_user_id, receiving_user_id, status)
  VALUES ($1, $2, $3, 'pending')
`, [regRef, payerUserId, receiverUserId]);

// Prepare data for SCB API
const regData = {
  regRef: regRef,
  ref1: payerUserId,      // Payer User ID
  ref2: receiverUserId,   // Receiver User ID  
  remarks: '',            // Optional field
  backUrl: backUrl        // Redirect URL after bank registration
};

// Request body for SCB API
const requestBody = {
  merchantId: merchantId,      // From merchant configuration
  subAccountId: subAccountId,  // From merchant configuration  
  encryptedValue: encryptSCB(regData) // Encrypt the registration data
};

4.1.3 Response Structure

The webUrl is what we return from our wrapper to other teams or redirect the user to. User needs to fill in their debit card info and go through the registration process at the bank website, and after registration they will be redirected to backUrl. The API will also return regRef which should be stored in the scb_registrations table for tracking.

// SCB Registration Init API Response
{
  "status": {
    "code": 1000,
    "description": "Success"
  },
  "data": {
    "merchantId": "2020000001",
    "subAccountId": "1293340504",
    "registrationResponse": {
      "webURL": "https://..."  // Bank registration URL - this is what we return to user
    },
    "validationMessages": []
  }
}

// Response data usage:
// - status.code: Check if request was successful
// - registrationResponse.webURL: The URL to redirect user for bank registration
// - validationMessages: For error handling if needed

// Implementation example:
if (response.status.code === 1000) {
  const webURL = response.data.registrationResponse.webURL;
  
  // Update database with the webURL for tracking
  await db.query(`
    UPDATE scb_registrations 
    SET web_url = $1, status = 'initiated'
    WHERE reg_ref = $2
  `, [webURL, regRef]);
  
  // Return webURL to client for user redirection
  return {
    success: true,
    regRef: regRef,
    webURL: webURL,
    message: 'Registration initiated successfully'
  };
} else {
  throw new Error(`Registration failed: ${response.status.description}`);
}

4.2 Registration Status Inquiry

Monitors registration completion and retrieves customer account information.

API Details:

4.2.1 Implementation Logic

Your JavaScript function will be given either regRef directly, or payerUserId and receiverUserId. If user IDs are provided, you'll need to query the PostgreSQL scb_registrations table to find the corresponding regRef. You'll also need to retrieve the merchant's merchantId from the merchant table using the receiverUserId.

// If regRef not provided, look it up from database
let lookupRegRef = regRef;
if (!lookupRegRef && payerUserId && receiverUserId) {
  const result = await db.query(`
    SELECT reg_ref FROM scb_registrations 
    WHERE payer_user_id = $1 AND receiving_user_id = $2
    ORDER BY created_at DESC LIMIT 1
  `, [payerUserId, receiverUserId]);
  
  if (result.rows.length === 0) {
    throw new Error('No registration found for these users');
  }
  lookupRegRef = result.rows[0].reg_ref;
}

// Get merchant config and prepare request
const requestBody = {
  merchantId: merchantId,  // From merchant configuration
  encryptedValue: encryptSCB(lookupRegRef) // Encrypt just the regRef string
};

4.2.2 Response Structure and Decryption

The SCB API returns an encrypted response that you must decrypt to get the registration status and account information.

// SCB Registration Inquiry API Response Structure
{
  "status": {
    "code": 1000,
    "description": "Success"
  },
  "data": {
    "merchantId": "2020000001",
    "encryptedValue": "",  // This contains the actual registration data
    "validationMessages": []
  }
}

// Decrypt the encryptedValue to get registration information:
const decryptedData = decryptSCBResponse(response.data.encryptedValue);
// decryptedData contains all these fields:
{
  "regRef": "REG-xxxxxxxxxxxxx",     // Registration reference (String 20)
  "ref1": "12345",                   // Customer reference (payerUserId) (String 20)
  "ref2": "67890",                   // Other reference (receiverUserId) (String 20)
  "statusCode": "0002",              // Registration status code (String)
  "statusDesc": "Registration completed successfully", // Status description (String)
  "errorCode": "000",                // Registration error code (String) - only if error
  "accountNo": "1234567890"          // Customer's account number (String) - only when successful
}

// Response data usage:
// - status.code: Check if API call was successful
// - decryptedData.statusCode: Check registration status ("0001" = initiated, "0002" = success)
// - decryptedData.accountNo: Cache this in Firebase RTDB for payment processing (only available when statusCode = "0002")
// - decryptedData.regRef, ref1, ref2: For verification and tracking
// - validationMessages: For error handling

// Implementation example:
if (response.status.code === 1000) {
  const decryptedData = decryptSCBResponse(response.data.encryptedValue);
  
  // Update database with current status
  await db.query(`
    UPDATE scb_registrations 
    SET status_code = $1, status_desc = $2, last_checked = NOW()
    WHERE reg_ref = $3
  `, [decryptedData.statusCode, decryptedData.statusDesc, decryptedData.regRef]);
  
  // If registration completed successfully, cache account number
  if (decryptedData.statusCode === "0002" && decryptedData.accountNo) {
    // Cache in Firebase RTDB for fast payment processing
    await firebase.database()
      .ref(`scb_accounts/${decryptedData.regRef}/accountNumber`)
      .set(decryptedData.accountNo);
      
    // Update PostgreSQL with success status
    await db.query(`
      UPDATE scb_registrations 
      SET status = 'success', account_number = $1
      WHERE reg_ref = $2
    `, [decryptedData.accountNo, decryptedData.regRef]);
    
    return {
      success: true,
      regRef: decryptedData.regRef,
      statusCode: decryptedData.statusCode,
      statusDesc: decryptedData.statusDesc,
      accountNumber: decryptedData.accountNo,
      message: 'Registration completed successfully'
    };
  } else {
    return {
      success: false,
      regRef: decryptedData.regRef,
      statusCode: decryptedData.statusCode,
      statusDesc: decryptedData.statusDesc,
      message: 'Registration still in progress'
    };
  }
} else {
  throw new Error(`Registration inquiry failed: ${response.status.description}`);
}

After decryption, cache the accountNo in Firebase RTDB for future payment processing:

// Cache account number in Firebase RTDB when statusCode is "0002"
if (decryptedData.statusCode === "0002" && decryptedData.accountNo) {
  await firebase.database()
    .ref(`scb_accounts/${regRef}/accountNumber`)
    .set(decryptedData.accountNo);
    
  // Update registration status in PostgreSQL
  await db.query(`
    UPDATE scb_registrations 
    SET status = 'success' 
    WHERE reg_ref = $1
  `, [regRef]);
}

4.2.3 Status Code Reference

For statusCode: 0001 is after init and 0002 is after payer successfully validates their debit card. You can only get accountNo at 0002.

Status Code Description Account Number Available
0001 Registration initiated (after init) No
0002 Registration completed successfully (payer validated debit card) Yes - accountNo available

5. Payment Processing Implementation

5.1 Direct Debit Payment (Charging Registered User)

This API charges the registered user. Header will be getHeaders() with accessToken.

API Details:

5.1.1 Payment Data Preparation

Your JavaScript function will be given amount, currency, and regRef. You'll need to query the PostgreSQL scb_registrations table to get the payer and receiver IDs, then retrieve the merchant configuration including merchantId, subAccountId, and PUBLIC_KEY from the merchant table using the receiverUserId. The customer's account number should be retrieved from Firebase RTDB where it was cached from the registration inquiry.

  1. Query scb_registrations table using regRef to get payer and receiver IDs
  2. Retrieve merchant configuration (merchantId, subAccountId, PUBLIC_KEY) from merchant table using receiverUserId
  3. Generate unique reference numbers and timestamps
// Look up registration details from PostgreSQL
const regResult = await db.query(`
  SELECT payer_user_id, receiving_user_id, status
  FROM scb_registrations 
  WHERE reg_ref = $1
`, [regRef]);

if (regResult.rows.length === 0 || regResult.rows[0].status !== 'success') {
  throw new Error('No successful registration found for this regRef');
}

const { payer_user_id: payerId, receiving_user_id: receiverId } = regResult.rows[0];

// Get account number from Firebase RTDB cache first
let accountNumber = await firebase.database()
  .ref(`scb_accounts/${regRef}/accountNumber`)
  .once('value')
  .then(snapshot => snapshot.val());

// If not cached, call registration inquiry API to get fresh data
if (!accountNumber) {
  const inquiryResponse = await callRegistrationInquiry(regRef, merchantId);
  const decryptedInquiry = decryptSCBResponse(inquiryResponse.data.encryptedValue);
  
  if (decryptedInquiry.statusCode === "0002" && decryptedInquiry.accountNo) {
    accountNumber = decryptedInquiry.accountNo;
    
    // Cache it for future use
    await firebase.database()
      .ref(`scb_accounts/${regRef}/accountNumber`)
      .set(accountNumber);
  } else {
    throw new Error('Registration not completed or account number not available');
  }
}

// Retrieve merchant configuration using receiverId
const merchantConfig = await getMerchantConfig(receiverId);

5.1.2 Reference Generation

You'll need to generate a unique refNumber with RF-xxxxxxxxx format ([0-9a-f] hexadecimal) using PostgreSQL UUID generation for better uniqueness. You'll also need to create refDateTime in YYYYMMDDHHmmss format using dayjs.

// Generate unique payment reference using PostgreSQL UUID  
const uuidResult = await db.query('SELECT gen_random_uuid() as id');
const refNumber = 'RF-' + uuidResult.rows[0].id.replace(/-/g, '').substring(0, 18).toUpperCase();

// Generate timestamp in required format YYYYMMDDHHmmss
const refDateTime = dayjs().format('YYYYMMDDHHmmss');

// Create customer reference by concatenating payer:receiver
const customerRef = `${payerId}:${receiverId}`;

// Store in scb_debit_transactions table for tracking
await db.query(`
  INSERT INTO scb_debit_transactions (ref_number, reg_ref, ref_date_time, amount, currency, customer_ref, status)
  VALUES ($1, $2, $3, $4, $5, $6, 'pending')
`, [refNumber, regRef, refDateTime, amount, currency, customerRef]);

5.1.3 Payment Data Structure

For body you will put merchantId, subAccountId, and encryptedValue. Currency will be code (e.g., THB). Amount with two decimals (x.xx).

// encryptedValue contains all payment details
const paymentData = {
  refNumber: refNumber,
  refDateTime: refDateTime,
  amount: amount.toFixed(2),        // Format with two decimals: "100.00"
  currency: currency,               // Currency code e.g., "THB"
  accountNumber: accountNumber,     // From registration inquiry
  customerRef: customerRef          // "payerId:receiverId" format
};

// Request body structure
const requestBody = {
  merchantId: merchantId,
  subAccountId: subAccountId,
  encryptedValue: encryptSCB(paymentData) // Encrypt the payment data
};

5.1.4 Payment Response Handling

After receiving the payment response from SCB, you need to decrypt the response and update your database with the transaction details including the SCB transaction number.

// SCB Direct Debit Payment API Response Structure
const paymentResponse = await callSCBPaymentAPI(requestBody, headers);

// Response structure:
// {
//   "status": {
//     "code": 1000,
//     "description": "Success"
//   },
//   "data": {
//     "merchantId": "2020000001",
//     "subAccountId": "1293340504",
//     "encryptedValue": "",  // Contains payment information
//     "validationMessages": []
//   }
// }

// Decrypt the encryptedValue to get payment information:
const decryptedPayment = decryptSCBResponse(paymentResponse.data.encryptedValue);
// decryptedPayment contains all these fields:
// {
//   "refNumber": "RF-xxxxxxxxxxxxx",      // Merchant reference number (String)
//   "refDateTime": "20231007143000",      // Merchant reference date/time (String: yyyyMMddHHmmss)
//   "amount": 100.00,                     // Transaction amount (Number)
//   "currency": "THB",                    // Transaction currency (String)
//   "customerRef": "12345:67890",         // Customer reference (String)
//   "txnNumber": "SCB202310071234567890", // SCB's unique transaction number (String)
//   "txnDateTime": "20231007143055",      // SCB transaction date/time (String)
//   "statusCode": "0000",                 // Transaction status code (String)
//   "statusDesc": "Success",              // Transaction status description (String)
//   "responseCode": "00"                  // Response code (String) - only if rejected
// }

// Response data usage:
// - status.code: Check if API call was successful
// - decryptedPayment.txnNumber: Store as scb_txn_number in database
// - decryptedPayment.statusCode: Determine final transaction status
// - decryptedPayment.statusDesc: For user feedback
// - decryptedPayment.responseCode: For error handling if transaction rejected
// - validationMessages: For error handling

// Update database with SCB transaction number, refTimeDate, and final status
const finalStatus = decryptedPayment.statusCode === '0000' ? 'confirmed' : 'failed';
await db.query(`
  UPDATE scb_debit_transactions 
  SET scb_txn_number = $1, ref_time_date = $2, status = $3
  WHERE ref_number = $4
`, [decryptedPayment.txnNumber, decryptedPayment.txnDateTime, finalStatus, refNumber]);

return {
  success: decryptedPayment.statusCode === '0000',
  refNumber: refNumber,
  scbTxnNumber: decryptedPayment.txnNumber,
  refTimeDate: decryptedPayment.txnDateTime,
  amount: decryptedPayment.amount,
  currency: decryptedPayment.currency,
  statusDesc: decryptedPayment.statusDesc
};

6. Payment Status Inquiry Implementation

6.1 Payment Status Inquiry

This API allows checking the status of a previously submitted payment transaction using the payment reference details.

API Details:

6.1.1 Implementation Logic

Your JavaScript function will be given refNumber and refTimeDate. You need to query the PostgreSQL scb_debit_transactions table to find the corresponding transaction and extract the customerRef. From the customerRef (format: "customerId:merchantId"), you can extract the merchantId needed for the SCB API call.

// Look up transaction details from PostgreSQL using refNumber and refTimeDate
const transactionResult = await db.query(`
  SELECT customer_ref, reg_ref, ref_date_time, amount, currency
  FROM scb_debit_transactions 
  WHERE ref_number = $1 AND ref_time_date = $2
`, [refNumber, refTimeDate]);

if (transactionResult.rows.length === 0) {
  throw new Error('No transaction found for the provided refNumber and refTimeDate');
}

const { customer_ref: customerRef, ref_date_time: refDateTime } = transactionResult.rows[0];

// Extract merchantId from customerRef (format: "customerId:merchantId")
const [customerId, merchantId] = customerRef.split(':');

if (!merchantId) {
  throw new Error('Invalid customerRef format - unable to extract merchantId');
}

// Prepare encrypted data for SCB API
const inquiryData = {
  refNumber: refNumber,
  refDateTime: refDateTime.toISOString().replace(/[-:]/g, '').slice(0, 14), // Format: YYYYMMDDHHmmss
  customerRef: customerRef
};

// Request body structure
const requestBody = {
  merchantId: merchantId,
  encryptedValue: encryptSCB(inquiryData) // Encrypt the inquiry data
};

6.1.2 Response Structure and Decryption

The SCB API returns an encrypted response that you must decrypt to get the payment status and transaction details.

// SCB Payment Inquiry API Response Structure
{
  "status": {
    "code": 1000,
    "description": "Success"
  },
  "body": {
    "merchantId": "2020000001",
    "encryptedValue": "",
    "validationMessages": []
  }
}

// Decrypt the encryptedValue to get payment information:
const decryptedPayment = decryptSCBResponse(response.body.encryptedValue);
// decryptedPayment contains all these fields:
// {
//   "refNumber": "RF-xxxxxxxxxxxxx",      // Payment reference number (String)
//   "refDateTime": "20231007143000",      // Payment reference date/time (String: yyyyMMddHHmmss)
//   "amount": 100.00,                     // Transaction amount (Number)
//   "currency": "THB",                    // Transaction currency (String)
//   "customerRef": "12345:67890",         // Customer reference (String)
//   "txnNumber": "SCB202310071234567890", // SCB's transaction number (String)
//   "statusCode": "0000",                 // Payment status code (String)
//   "statusDesc": "Success"               // Payment status description (String)
// }

// Response data usage:
// - status.code: Check if API call was successful
// - decryptedPayment.statusCode: Check payment status
// - decryptedPayment.statusDesc: Status description for user feedback
// - decryptedPayment.amount, currency: Transaction details
// - decryptedPayment.customerRef: Extract customerId and merchantId
// - validationMessages: For error handling

// Implementation example:
if (response.status.code === 1000) {
  const decryptedPayment = decryptSCBResponse(response.body.encryptedValue);
  
  // Extract customerId and merchantId from customerRef
  const [customerId, merchantId] = decryptedPayment.customerRef.split(':');
  
  // Return payment status information to wrapper API caller
  return {
    success: decryptedPayment.statusCode === '0000',
    amount: decryptedPayment.amount,
    currency: decryptedPayment.currency,
    customerId: customerId,
    merchantId: merchantId,
    refDateTime: decryptedPayment.refDateTime,
    statusCode: decryptedPayment.statusCode,
    description: decryptedPayment.statusDesc
  };
} else {
  throw new Error(`Payment inquiry failed: ${response.status.description}`);
}

7. Error Handling and Best Practices

7.1 Token Management

7.2 Encryption Security

7.3 Reference Generation


8. API Reference Links