SCB DeepLink Mobile API - Developer Implementation Guide

Overview

This guide provides comprehensive implementation details for integrating SCB DeepLink Mobile API. DeepLink is primarily used for mobile payments where customers click a payment link, get redirected to SCB Easy app, and complete payment through the SCB banking system. This approach eliminates the need for QR code scanning by providing direct app-to-app integration.

1. Database Schema

The DeepLink API system requires a dedicated database table to track transaction lifecycles and payment statuses.

1.1 deepLink_transactions Table

This table stores all DeepLink transaction records with comprehensive tracking capabilities.

Column Name Data Type Constraints Description
id SERIAL PRIMARY KEY Auto-incrementing unique identifier
ref1 VARCHAR(50) NOT NULL Generated reference ID (REF-xxxxxxxxx format, [0-9a-f] hexadecimal)
ref2 VARCHAR(50) NOT NULL Receiver User ID for tracking
transaction_id VARCHAR(100) UNIQUE SCB's unique transaction identifier
transaction_type VARCHAR(20) NOT NULL, DEFAULT 'PURCHASE' Transaction type (always "PURCHASE" for our test)
payment_amount DECIMAL(15,2) NOT NULL Payment amount with 2 decimal precision
payment_status VARCHAR(20) NOT NULL, DEFAULT 'NA' Payment status (NA, PENDING, PAID, CANCELLED, etc.)
paid_time_date TIMESTAMP NULL Timestamp when payment was completed
deeplink_url TEXT NULL SCB DeepLink URL for payment
session_validity_period INTEGER DEFAULT 0 Session timeout in seconds (60-1800). Optional: 0 = no timeout
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP Record creation timestamp
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP Record last updated timestamp

1.2 merchants Table (Referenced)

This table stores all SCB-specific financial configuration data for users who act as merchants (payment receivers). The billerId field from this table is used in DeepLink transactions.

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. Used in DeepLink transactions as accountTo. 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. Authentication System

2.1 Request Headers

All SCB DeepLink API requests require specific headers for authentication and request tracking. Use the getHeaders() function to ensure consistent header formatting.

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',
    'channel': 'scbeasy' // Required for DeepLink transactions
  };
}

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. The channel parameter is specifically required for DeepLink transactions.

2.2 OAuth Token Management

SCB requires OAuth2 authentication with automatic token refresh capability. The system must handle token expiration transparently and include the access token as a Bearer token in the Authorization header.

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. DeepLink Transaction Creation

The DeepLink transaction creation process initiates a mobile payment flow where users are redirected to SCB Easy app to complete payment. This API creates a transaction record and returns a deeplink URL for mobile app integration.

3.1 Transaction Initialization

Creates a new DeepLink transaction with payment details and generates the redirect URL for mobile payment processing.

API Details:

3.1.1 Request Preparation

When this API is called, you will be given receiverUserId and paymentAmount. The billerId need to be obtained from the merchant table with given receiver userId as key and used directly in the API call without storing in the database. Note that merchant-specific financial configuration data (such as billerId, applicationKey, and applicationSecret) is stored in a separate merchant table rather than the user table to properly segregate financial credentials from general user information. The biller ID validation is not necessary in sandbox environment.

  1. Generate unique reference ID using PostgreSQL UUID: REF- + UUID substring (format: [0-9a-f] hexadecimal)
  2. Use billerId taken from merchants table based on receiverUserId as accountTo in API call
  3. Store initial transaction record in deepLink_transactions table with status "NA"
  4. Prepare request body with Bill Payment details

3.1.2 Transaction Data Structure

Your JavaScript function will be given receiverUserId, paymentAmount, billerId, and optional sessionValidityPeriod. You'll need to generate a unique ref1 using PostgreSQL UUID generation. ref2 will be set to receiverUserId for tracking purposes.

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

// Store in deepLink_transactions table (billerId not stored, used only for API call)
await db.query(`
  INSERT INTO deepLink_transactions (ref1, ref2, transaction_type, payment_amount, payment_status, session_validity_period)
  VALUES ($1, $2, $3, $4, $5, $6)
`, [ref1, receiverUserId, 'PURCHASE', paymentAmount, 'NA', sessionValidityPeriod || 0]);

// Prepare data for SCB API
const requestBody = {
  transactionType: "PURCHASE",
  transactionSubType: ["BP"], // Bill Payment
  sessionValidityPeriod: sessionValidityPeriod || 0, // Optional: 60 to 1800 seconds (30 min max), 0 = no timeout
  billPayment: {
    paymentAmount: parseFloat(paymentAmount), // Must be number format
    accountTo: billerId,                      // Merchant's biller ID (provided as input)
    ref1: ref1,                              // Generated reference ID
    ref2: receiverUserId                     // Receiver User ID for tracking
  }
};

// Prepare headers using getHeaders() function
const headers = getHeaders(resourceOwnerId);
headers['authorization'] = `Bearer ${accessToken}`;

// Make API call to create DeepLink transaction
const response = await fetch('https://api-sandbox.partners.scb/partners/sandbox/v3/deeplink/transactions', {
  method: 'POST',
  headers: headers,
  body: JSON.stringify(requestBody)
});

const responseData = await response.json();

3.1.3 Response Structure

The deeplinkUrl is what we return from our wrapper to other teams for mobile app integration. Users will be redirected to this URL which opens SCB Easy app for payment processing. The API also returns transactionId which must be stored in the database for transaction tracking and status checking.

// SCB DeepLink Transaction Creation API Response
{
  "status": {
    "code": 1000,
    "description": "Deeplink successfully created"
  },
  "data": {
    "transactionId": "a4220ec2-bd0b-441f-b333-7c32d7b6d7f9",
    "deeplinkUrl": "scbeasysim://purchase/a4220ec2-bd0b-441f-b333-7c32d7b6d7f9",
    "userRefId": "7b109a37-09ba-4a62-aa56-9ea7ea3e97ab"
  }
}

// Response data usage:
// - status.code: Check if request was successful (1000 = success)
// - data.transactionId: Store in database for status checking
// - data.deeplinkUrl: Return to client for mobile app redirection
// - data.userRefId: SCB's internal user reference

// Implementation example:
if (response.status.code === 1000) {
  const { transactionId, deeplinkUrl } = response.data;
  
  // Update database with SCB transaction ID and deeplink URL
  await db.query(`
    UPDATE deepLink_transactions 
    SET transaction_id = $1, deeplink_url = $2, payment_status = 'PENDING'
    WHERE ref1 = $3
  `, [transactionId, deeplinkUrl, ref1]);
  
  // Return deeplink URL to client for mobile redirection
  return {
    success: true,
    ref1: ref1,
    transactionId: transactionId,
    deeplinkUrl: deeplinkUrl,
    message: 'DeepLink transaction created successfully'
  };
} else {
  throw new Error(`Transaction creation failed: ${response.status.description}`);
}

4. Payment Status Inquiry

4.1 Transaction Status Check

Retrieves the current payment status of a DeepLink transaction using the transaction ID obtained during transaction creation. This API should be polled regularly to track payment completion.

API Details:

4.1.1 Status Check Implementation

Your JavaScript function will be given transactionId to check the payment status. The API returns detailed transaction information including the current status code which maps to specific payment states.

// Look up transaction details from PostgreSQL using transactionId
const transactionResult = await db.query(`
  SELECT ref1, ref2, payment_amount
  FROM deepLink_transactions 
  WHERE transaction_id = $1
`, [transactionId]);

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

// Make API call to check transaction status
const headers = getHeaders(resourceOwnerId);
headers['authorization'] = `Bearer ${accessToken}`;

const statusResponse = await fetch(`https://api-sandbox.partners.scb/partners/sandbox/v2/transactions/${transactionId}`, {
  method: 'GET',
  headers: headers
});

const statusData = await statusResponse.json();

4.1.2 Status Code Mapping

The SCB API returns numeric status codes that map to specific payment states. Your system must handle these status codes and update the database accordingly.

// Status code mapping for payment states
const statusMapping = {
  0: 'PENDING',    // Payment is still being processed
  1: 'PAID',       // Payment completed successfully
  2: 'CANCELLED',  // Payment was cancelled by user
  3: 'INVALID',    // Payment is invalid
  4: 'PARTIAL',    // Partial payment received
  5: 'EXPIRED'     // Payment session has expired
};

// Extract status code from API response
const statusCode = statusData.data.statusCode;
const paymentStatus = statusMapping[statusCode] || 'UNKNOWN';

// Update database with current status
await db.query(`
  UPDATE deepLink_transactions 
  SET payment_status = $1, updated_at = CURRENT_TIMESTAMP
  WHERE transaction_id = $2
`, [paymentStatus, transactionId]);

// Update paid_time_date if payment is completed
if (statusCode === 1) { // PAID
  await db.query(`
    UPDATE deepLink_transactions 
    SET paid_time_date = CURRENT_TIMESTAMP
    WHERE transaction_id = $1
  `, [transactionId]);
}

4.1.3 Response Structure

The transaction status API returns comprehensive payment information including bill payment details, timestamps, and current status.

// SCB Transaction Status API Response Structure
{
  "status": {
    "code": 1000,
    "description": "Success"
  },
  "data": {
    "transactionId": "a4220ec2-bd0b-441f-b333-7c32d7b6d7f9",
    "userRefId": "7b109a37-09ba-4a62-aa56-9ea7ea3e97ab",
    "transactionType": "PURCHASE",
    "transactionSubType": ["BP"],
    "transactionMethod": "BP",
    "paidAmount": 3500.00,
    "billPayment": {
      "paymentAmount": 3500.00,
      "accountTo": "001230083",      // Biller ID
      "ref1": "REF-523863962",       // Generated reference
      "ref2": "user123",             // Receiver User ID
      "ref3": "ABC123",
      "accountFrom": "029470043"     // Customer's account (when paid)
    },
    "partnerId": "66900789566433434",
    "partnerName": "Trusted Partner",
    "sessionValidityPeriod": 1800,
    "createdTimestamp": "2022-01-20T13:00:00+07:00",
    "updatedTimestamp": "2022-01-20T13:41:00+07:00",
    "fee": 10,
    "statusCode": 1,               // 0=PENDING, 1=PAID, 2=CANCELLED, 3=INVALID, 4=PARTIAL, 5=EXPIRED
    "merchantMetaData": {
      "deeplinkUrl": "scbeasysim://purchase/a4220ec2-bd0b-441f-b333-7c32d7b6d7f9",
      "paymentInfo": []
    }
  }
}

// Response data usage:
// - status.code: Check if API call was successful
// - data.statusCode: Current payment status (0-5)
// - data.paidAmount: Actual amount paid by customer
// - data.billPayment.accountFrom: Customer's account number (available when paid)
// - data.updatedTimestamp: Last status update time
// - createdTimestamp vs updatedTimestamp: Track payment duration

// Implementation example:
if (response.status.code === 1000) {
  const transactionData = response.data;
  const statusCode = transactionData.statusCode;
  const paymentStatus = statusMapping[statusCode];
  
  // Return status information to wrapper API caller
  return {
    success: true,
    transactionId: transactionData.transactionId,
    ref1: transactionData.billPayment.ref1,
    ref2: transactionData.billPayment.ref2,
    paymentStatus: paymentStatus,
    statusCode: statusCode,
    paidAmount: transactionData.paidAmount,
    paymentAmount: transactionData.billPayment.paymentAmount,
    createdTimestamp: transactionData.createdTimestamp,
    updatedTimestamp: transactionData.updatedTimestamp,
    shouldContinuePolling: ![1, 2, 5].includes(statusCode) // Stop polling on PAID, CANCELLED, or EXPIRED
  };
} else {
  throw new Error(`Status check failed: ${response.status.description}`);
}

4.1.4 Polling Strategy

Developers should implement regular polling to check payment status until completion. The polling should stop when the transaction reaches a final state.

// Polling implementation for payment status
// We will be polling for 10 minutes (max 60 attempts, 10 seconds interval)
async function pollPaymentStatus(transactionId, maxAttempts = 60, intervalSeconds = 10) {
  let attempts = 0;
  
  while (attempts < maxAttempts) {
    try {
      const statusResult = await checkTransactionStatus(transactionId);
      
      // Stop polling on final states: PAID (1), CANCELLED (2), or EXPIRED (5)
      if ([1, 2, 5].includes(statusResult.statusCode)) {
        return {
          success: true,
          finalStatus: statusResult.paymentStatus,
          statusCode: statusResult.statusCode,
          attempts: attempts + 1,
          data: statusResult
        };
      }
      
      // Continue polling for PENDING (0), INVALID (3), or PARTIAL (4)
      attempts++;
      await new Promise(resolve => setTimeout(resolve, intervalSeconds * 1000));
      
    } catch (error) {
      console.error(`Polling attempt ${attempts + 1} failed:`, error.message);
      attempts++;
      
      if (attempts >= maxAttempts) {
        throw new Error(`Payment status polling failed after ${maxAttempts} attempts`);
      }
      
      // Wait before retry
      await new Promise(resolve => setTimeout(resolve, intervalSeconds * 1000));
    }
  }
  
  return {
    success: false,
    message: 'Polling timeout - payment status still pending',
    attempts: attempts
  };
}

// Usage example:
const pollingResult = await pollPaymentStatus('a4220ec2-bd0b-441f-b333-7c32d7b6d7f9', 60, 5);
if (pollingResult.success) {
  console.log(`Payment completed with status: ${pollingResult.finalStatus}`);
} else {
  console.log('Payment polling timed out');
}

5. Error Handling

5.1 Common Error Scenarios

5.2 Status Code Handling

5.3 Business Logic Validation


6. API Reference Links