Account Balance Inquiry

# Code example

TopPayRequestUtil Click to obtain code examples


import com.google.gson.JsonObject;
public class BalanceQuery {
  //MCH_ID: Merchant ID
  //1.Please log in to the merchant backend
  //2.Click on personal center > personal information
  //3.Get Merchant ID in Basic Information
  private static final String MCH_ID = "S820211021094748000001";
  private static final String PLAT_PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC2JoMfFqLsSJjAiCahEnlP3aRj8yCT+WHzR+VvPBTw9S1i7iYWb+MY09CG/HYuHF4+IxshXDJygmndxKf/esuwPybS8mAd//yubHpmZsmBqg1FffT8VH1APa6ZRWASUp4U01ZrbCCp35QA8FuWrJGMJxGx4xk7KUtV2yujxC8noQIDAQAB";  // platform public key
  private static final String MCH_PRIVATE_KEY = "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAJU8gKFKD0luIYx7X8+JRdCIE0UDBctS6LjXxWLEv/EO7jDBTid6zYP1KmNgpd2DAWWtBFBSQ+gcNwVZZSBHJiSDqVvvJVs2FEbeBvfdv4X93+IYRAXksBasSW5Tpdshbo82pVL4V7wuKCuFLk9UxBHbpQjWAbfyF66RmwIbZD71AgMBAAECgYBjPe7UU2nDDSfmQg0++CyjNjqKRC5QPfxhH6w1uF1kMueXKJWOj42n2RutJpJmsj31nY8m0u4xpsG4HvCu/GGSFhhKZCHLvzp41oY2ubYj9nuFNU//81LycQjulWo2y0UUBY0k2piEt+SwPaiUNbT6nMxNMjlnjRe2okp/3rw+KQJBANG3YlZWoVbCEqzy64bJJLxiPsCA5ErGB0NzRGitq44xkhqGtR8ZZQyVz40pruNa58d73O2xyJSy5+fmZGn4E+sCQQC2LBnguj0CSCKub0mPDcunTTz9V79VXBBZdlB1/YGmRUx2s4sQrJNZS7rL4EqBQ3maIRnG+s+AXCSTfsYrV6CfAkEAxugnVfpelhoGepEAgNuggyivmgfl/2Gpm/jk5l/qOjib+ZrQiQmeBPzGWX4yiSM8eMDrP2sC8r5pJFMp5DRONwJBAJ4n4XuSFJ9jgwCPy3vvzSv9SYLk6E6yM9uHdUlKgoGYzk6Lh6M9QFuY/J49plFdBDiEnj16yCU3WeXXfTJpzB8CQQDMNMR/rIOTE9xGybS3mlQbt22AUnO6XhupWcckEKW4nPGxATwYBQzCY3i/9FTGN0vA+9ZPC2cwHtNxI2kXf3Vp";  // merchant private key
  private static final String BALANCE_QUERY_URL = "https://tl-openapi.toppay.asia/gateway/interface/getBalance";

  public static void main(String[] args) throws Exception {
    query();
  }
  private static void query() throws Exception {
    Map<String, String> requestParams = new TreeMap<>();
    requestParams.put("merchantCode", MCH_ID);
    requestParams.put("currency", "THB"); // currency(THB)

    StringBuilder stringBuilder = new StringBuilder();
    for (String key : requestParams.keySet()) {
      stringBuilder.append(requestParams.get(key));  // stitching parameters
    }

    String keyStr = stringBuilder.toString();  // get the string to be encrypted
    System.out.println("keyStr:" + keyStr);
    String signedStr = TopPayRequestUtil.privateEncrypt(keyStr, TopPayRequestUtil.getPrivateKey(MCH_PRIVATE_KEY));  // private key encryption
    requestParams.put("sign", signedStr);

    String postJson = new Gson().toJson(requestParams);
    System.out.println("Post Json Params:" + postJson);

    String responseJson = TopPayRequestUtil.doPost(BALANCE_QUERY_URL, postJson);  // send post json request
    System.out.println("Response Msg:" + responseJson);
  }
}


<?php
    //Mchchant private key(Please replace it yourself)
    //Please pay attention to the format of the key and do not include spaces.
    $mchPrivateKey = 'MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAPGGGdiAwLnyJqtoQZdTvbP+kdX/PWscZziOAkUNVPBXuMesnZ5IVSFIHTl6A7SCMn5VShIsUVlVmB+Sn1mCE0QXv2GJpz30kNyA4DKghblFmZ7sy4siJp7+T/hON31kM+q6wuRATbriJ87p5iZdF4W9+iyZGZjhLaTVPjBZxn2xAgMBAAECgYEA7Nu1VxSVbQXkFG8u/Af835tFTBd/FR8Kv3TNFwkHBpkQtok7HjITgoslVeup3IlemXRtKrtZoAGIKVZyfaZJ2rKuEHuPbPjZLRxhepl2OIjSv0fDQP3u5y/EcUv3ujgL117Ain4ui7In8JSsuFY0I6LEZo6NVcTASdY9qL6fGk0CQQD7NiH+7A1VX+zSBxz0edaw3UjAYnXNaAO39nyFxt8v5UJuFEDwHUrD6r53TLxE1yMpLEtiweKPqSHjaukmNYdLAkEA9iCxvGKkirmoUab6Fs6cz++WUd+rj+kTAVC6dLjpP1osy87oh32q3NEne9CnCXfb3C+RnApZuOAwX0WaIxrFcwJBANg5As/hq6RVeYhZmQGQsUrwXINC/DR9l93K6elXgJlAEoqfIjnKbKTvM1uKD+6M4nW463YoffK7WDDfv6gkoLsCQFSc1L1QpARU4vp/Dsa8bMhHM0QeQpqMo8319MOftf/jfjbqgKHjn9Ody5cTGfl1TQ4bBFHCdSnLWJXIFb8vuuUCQQDn6sPtz7BUsbZtO7pdE6u1cl2m3VjIYTs5Bhc9cWYI/DFI0pf/88LtSZ25hYwY06Az8QvCrNmL0NRS6AoUbZT/';
    
    //merchantId: Merchant ID
    //1.Please log in to the merchant backend
    //2.Click on personal center > personal information
    //3.Get Merchant ID in Basic Information
    $merchantId = 'S820230414142102000012';
    
    //Currency (optional)
    $currency = 'THB';
    $params = array(
        'merchantCode' => $merchantId,

        'currency' => $currency,
    );

    ksort($params);
    $params_str = '';
    foreach ($params as $key => $val) {
        $params_str = $params_str . $val;
    }

    //Encryption
    $sign = pivate_key_encrypt($params_str, $mchPrivateKey);
    $params['sign'] = $sign;

    $params_string = json_encode($params);
    $url = 'https://tl-openapi.toppay.asia/gateway/interface/getBalance';
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $params_string);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Content-Length: ' . strlen($params_string))
    );
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

    //execute post
    $request = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    if($httpCode == 200)
    {
        $result = json_decode($request, true);
        echo "message :". $result['message'] . "<br>";
        //Create a new array to store data with currency THB
        $thbData = array();

        //Iterate over the data array
        foreach ($result['data'] as $item) {
            //Check if currency is THB
            if ($item['currency'] === 'THB') {
                //If yes, add to new array
                $thbData[] = $item;
            }
        }
        //Print data that meets the conditions
        print_r($thbData);
    }
    else {
        echo $httpCode;
    }

    //Encryption method
    function pivate_key_encrypt($data, $pivate_key)
    {
        $pivate_key = '-----BEGIN PRIVATE KEY-----'."\n".$pivate_key."\n".'-----END PRIVATE KEY-----';
        $pi_key = openssl_pkey_get_private($pivate_key);
        $crypto = '';
        foreach (str_split($data, 117) as $chunk) {
            openssl_private_encrypt($chunk, $encryptData, $pi_key);
            $crypto .= $encryptData;
        }

        return base64_encode($crypto);
    }
?>

using demo.utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace demo.demos
{
    class QueryBalanceDemo
    {
        //MCH_ID: Merchant ID
        //1.Please log in to the merchant backend
        //2.Click on personal center > personal information
        //3.Get Merchant ID in Basic Information
        private static readonly string MCH_ID = "S820230414142102000012";   //Merchent ID
        private static readonly string PLAT_PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCcEUIvQ/5L+SWbHOeR8VFeZvLbUk7V7OeEAQlQwIVLSZMTef3KtIOKKAsUYPf/aAcKRzZZXECODsPQiDPcdZvM/rFkgrFWkR7lPjTj5SiPxGaiK2Z2sne7A8aDF7fV/D7lfmEwNdZ7FWKVEB84/81BHnlGUwb5HpRTISG+boSO6wIDAQAB";  // 平台公钥
        private static readonly string MCH_PRIVATE_KEY = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAMigm7rtWnTeNagwFzGTH+Uw1ypbiy7VhIoFJbgSYSSHdCaXWdT/l2+2fQlEYgAETVZ/IXB29MCnrf3O0dwRFXiipIbsm5zyqSLiS6cKXe8zN1/PlQWUbEt5wyWm0GADB/4bV6eu6gA7sGXmjQqrzfKZkcie3aK7+7ry1NFxTI51AgMBAAECgYEAklqXQAVlt1tiSQ7L3J425jp6u6uMHN4lkYmvuleuBbfKQ1yla3wIPLYjAF+iHeEFidOz0Rb19JRdmIkHDkJoJg2W27LvO6RdUwzgRnsuA3OuNz97w08B3aXXbPmB91nTFjKSlUsbh3IQWP71noxW+iKn844EW5hC5Gvn4L3quAECQQDrz1r0VKIbBSBB2aLuz1XyD/TBT2aRhvOKf0XtTRiQhNjtJxoQmvNbbhvUwj8an7HyCuihAbdbrC2ymFFyOSDZAkEA2c4Yudi48C6COrroi1cWgPlEFeGJXP/V1k5loZ1n2vstYAGPhAB4wUnFBLDvMqaBzWJt7MRkikzT8KnBQCDY/QJAMXpNlEyZwt+deBOpO0BnwSWV7mWxmMFfImU4D+WITPKC7aexsWBBxaJh1o93XCe715RwYTAR//stj3akSDoyaQJAa4FKuxC51/Nc3Fg9R+modeiTLqmv/3NXvPvdNjRXesLX1rduex0wfVdII9ShfEKrdxDKaT9W0NyzD+r6NAkCkQJBAMAnTgPYf0f7rh417GdoP7R7Nwi8KBKwPHlmfRukibOQlKt9xjqpsKJwglLn8pcnXbYbswXIdqzuBvIGAe3OWNg=";  // 商户私钥
        private static readonly string payUrl = "https://tl-openapi.toppay.asia/gateway/interface/getBalance";
        public static void requestQuery()
        {
            string merchantId = MCH_ID;                                             //Merchent ID
            string currency = "THB";                                                    //Currency (optional)
            Dictionary<string, object> VarPost = new Dictionary<string, object>(); ;
            VarPost.Add("merchantCode", merchantId);
            VarPost.Add("currency", currency);
            List<string> paramNameList = new List<string>();
            foreach (string key in VarPost.Keys)
            {
                paramNameList.Add(key);
            }
            paramNameList.Sort();// sort key
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < paramNameList.Count; i++)
            {
                string key = paramNameList[i];
                stringBuilder.Append(VarPost[key]);  //Splicing parameters
            }
            string keyStr = stringBuilder.ToString();  //Get the string to be encrypted
            int len = keyStr.Length;
            string signedStr = "";
            try
            {
                RSAForJava rsa = new RSAForJava();
                signedStr = rsa.EncryptByPrivateKey(keyStr, MCH_PRIVATE_KEY);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            VarPost.Add("sign", signedStr);

            WebClient w = new WebClient();
            w.Headers[HttpRequestHeader.ContentType] = "application/json";
            string jsonStr = JsonNewtonsoft.SerializeDictionaryToJsonString(VarPost);
            Console.WriteLine("postJson:" + jsonStr);     //Do post
            string sRemoteInfo = w.UploadString(payUrl, "POST", jsonStr);
        }

    }
}

package main

import (
	"bytes"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"reflect"
	"sort"
	"strings"
)

// Create json request structure
type RequestBody struct {
	MerchantCode string `json:"merchantCode"`
	Currency     string `json:"currency"`
	Sign         string `json:"sign"`
}

func main() {
	//公私钥(仅用于测试)
	cryptor := NewCryptor()
	cryptor.Pub64 = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCvGQXHktEoCrQ/EnMceY4QVc15KHyvW1ePyYmSqZJC99u4gcdbzYYuunw7kqsdIKWSjPV6q/4cc8665ZOFuUH8W8iFMdOmuGO0QRUIvif09hhyWyaM7IpPMlU2+oydAWWjgc8JFmDZt1dWbMuaOS9Rw959wUOoQpbQK4yD37Bj0wIDAQAB"
	cryptor.Pri64 = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAK8ZBceS0SgKtD8Scxx5jhBVzXkofK9bV4/JiZKpkkL327iBx1vNhi66fDuSqx0gpZKM9Xqr/hxzzrrlk4W5QfxbyIUx06a4Y7RBFQi+J/T2GHJbJozsik8yVTb6jJ0BZaOBzwkWYNm3V1Zsy5o5L1HD3n3BQ6hCltArjIPfsGPTAgMBAAECgYBtrMS7/zBXXm0MXKgRm+nqPXRYgY2n4RT1kY1EekaM/+d2qIOQ8ykrN8/9GJ9pvTs4kmZokja256sD0i0XQ7UaLXYp31jTU4HlNpB8ixiCQG0gvldZRlLlGEeCeNrCQXT88dqC9mmvR7FIvS1sUnDonMZXEtJC8HOL4L80P52P0QJBAN3aovKYaCtmbtmYc76U+CqxyijRCxqV1Cb6u+YFY423FrFG2hXhdVu8UmgV+VvgT5lh0VQyKzVqRIdwk1hwzW8CQQDKDB8alSSBgcaEhlQkuTUjz4TwnYa5UhDuwzIs9FC2QLbBMa5alUiJDVlqVc33WzAHmGBJPRtMnnsGlgPeQiXdAkEAw9GVfjeTyqrxMNLlZtSqb1TaMUjCWkbhKT6q1w7unkl6mCMHn8SPB9ejjQfIP5Yv7Bxw3bYieVVBA6MUCz4VtQJAKju8aK8SMWvyFhOKFR8Np42iKTWUSrqHxZDRtSngkSgXy2xaGJ8pyVQcA6kp43GRKZVFUynNwgdCig7jghrrlQJBANfIE+D+PcFLSC8pRmX0sPhTLbuSFORgRzvpovW/FGXonNRp/yPWgIdXzpJKb40IFbbPEPjZtHKRJwSWWBDEfuk="

	url := "https://tl-openapi.toppay.asia/gateway/interface/getBalance"
	//Specific order parameters
	request := RequestBody{
	    //MerchantCode: Merchant ID
        //1.Please log in to the merchant backend
        //2.Click on personal center > personal information
        //3.Get Merchant ID in Basic Information
		MerchantCode: "S820230414142102000012",	
		//Currency
		Currency: "THB",
	}
	//Sort the fields of the structure by JSON tags and splice their values
	sortedValues, err := sortedConcatenatedValues(request)
	if err != nil {
		fmt.Printf("Error: %s\n", err)
		return
	}
	//The sorted and spliced values are encrypted using the private key and base64 encoded.
	encryptedData := cryptor.PriEncrypt([]byte(sortedValues))
	encodedString := base64.StdEncoding.EncodeToString(encryptedData)
	//Put the obtained signature into the request structure
	request.Sign = encodedString
	jsonBytes, err := json.Marshal(request)
	if err != nil {
		fmt.Printf("Error: %s", err.Error())
		return
	}
	fmt.Println("json2", bytes.NewBuffer(jsonBytes))
	//Make http request
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonBytes))
	if err != nil {
		fmt.Println("Error creating HTTP request:", err)
		return
	}
	req.Header.Set("Content-Type", "application/json")
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("Error sending HTTP request:", err)
		return
	}
	defer resp.Body.Close()
	//Read and print the response body
	respBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("Error reading response body:", err)
		return
	}
	fmt.Println("Response Body:", string(respBody))
}

/**
* Use the JSON tag of the structure to sort according to ASCII and splice the corresponding value into a string
 */
func sortedConcatenatedValues(v interface{}) (string, error) {
	valueOf := reflect.ValueOf(v)
	typeOf := valueOf.Type()
	kv := make(map[string]string)
	for i := 0; i < valueOf.NumField(); i++ {
		field := typeOf.Field(i)
		jsonTag := field.Tag.Get("json")
		if jsonTag == "" || jsonTag == "-" {
			continue
		}
		tagName := strings.Split(jsonTag, ",")[0] //Ignore omitempty option
		kv[tagName] = fmt.Sprint(valueOf.Field(i).Interface())
	}
	keys := make([]string, 0, len(kv))
	for k := range kv {
		keys = append(keys, k)
	}
	sort.Strings(keys)
	var concatenatedValues strings.Builder
	for _, key := range keys {
		concatenatedValues.WriteString(kv[key])
	}
	return concatenatedValues.String(), nil
}

import json
import requests
import base64
import easyocr
from M2Crypto import RSA
from collections import OrderedDict

class TopQueryDemo:
    # Merchant private key storage address
    MCH_PRI_KEY_FILE = 'D:\data\company_rsa_private_key.pem'
    # Platform public key storage address
    MCH_PUBLIC_KEY_FILE = 'D:\data\plat_rsa_public_key.pem'
    
    # MCH_ID: Merchant ID
    # 1.Please log in to the merchant backend
    # 2.Click on personal center > personal information
    # 3.Get Merchant ID in Basic Information
    MCH_ID = "S820240215181932000047"
    
    # Balance inquiry address
    url = "https://tl-openapi.toppay.asia/gateway/interface/getBalance"

    @staticmethod
    def cash():
        request_params = OrderedDict()
        # Merchant ID
        request_params["merchantCode"] = TopQueryDemo.MCH_ID
        # Currency
        request_params["currency"] = "THB"

        # Sort parameters according to key
        key_str = ''.join([str(value) for value in request_params.values()])
        print("keyStr:", key_str)

        # Encryption
        signed_str = TopQueryDemo.private_encrypt(key_str, TopQueryDemo.MCH_PRI_KEY_FILE)
        request_params["sign"] = signed_str

        # Send request
        post_json = json.dumps(request_params)
        print("Post Json Params:", post_json)

        response_json = TopQueryDemo.do_post(TopQueryDemo.url, post_json)
        print("Response Msg:", response_json)

        check = TopQueryDemo.public_key_decrypt(signed_str, TopQueryDemo.MCH_PUBLIC_KEY_FILE);
        print("check:", check)

    @staticmethod
    def private_encrypt(data, prikey_file):
        rsa_pri = RSA.load_key(prikey_file)
        # Encrypt data using private key
        # M2Crypto.RSA.pkcs1_padding   is a common filling method
        crypto = b''
        for chunk in [data[i:i + 117] for i in range(0, len(data), 117)]:
            encrypt_data = rsa_pri.private_encrypt(chunk.encode('utf-8'), RSA.pkcs1_padding)
            crypto += encrypt_data
        return base64.b64encode(crypto).decode('utf-8')


    @staticmethod
    def public_key_decrypt(data, public_file):
        rsa_key = RSA.load_pub_key(public_file)
        data = base64.b64decode(data)
        crypto = b''
        for chunk in [data[i:i+128] for i in range(0, len(data), 128)]:
            decrypt_data = rsa_key.public_decrypt(chunk, RSA.pkcs1_padding)
            crypto += decrypt_data
        return crypto.decode('utf-8')
    @staticmethod
    def do_post(url, data):
        headers = {"Content-Type": "application/json"}
        response = requests.post(url, data=data, headers=headers)
        if response.status_code == 200:
            return response.json()
        return None

if __name__ == '__main__':
    TopPayDemo.pay()
const { encryptWithPrivateKey } = require('./RSAUtil');
const axios = require('axios');

//MCH_ID: Merchant ID
//1.Please log in to the merchant backend
//2.Click on personal center > personal information
//3.Get Merchant ID in Basic Information
var merchantCode = 'S820230414142102000012'
//currency(THB)
var currency = 'THB'
const data = {
    merchantCode: merchantCode,
    currency: currency
};
console.log(merchantCode)
console.log(data.merchantCode)

//Sort object key names by ASCII code
const sortedKeys = Object.keys(data).sort();

//Concatenate their values using sorted key names
let sortedString = '';
sortedKeys.forEach(key => {
    sortedString += data[key];
});

console.log(sortedString);
var sign = encryptWithPrivateKey(sortedString);

//Add sign to the data object
data.sign = sign;
const jsonData = JSON.stringify(data);
console.log(jsonData)

var url = 'https://tl-openapi.toppay.asia/gateway/interface/getBalance'

//Send request
axios.post(url, jsonData,{
  headers: {
    'Content-Type': 'application/json'
  }
})
.then((response) => {
  console.log('code:', response.status);
  console.log('message:', response.data);
})
.catch((error) => {
  console.error('fail:', error);
});

# Request address

  • Request type: POST
  • Request address: https://tl-openapi.toppay.asia/gateway/interface/getBalance

# Request Param

param required description example
merchantCode Y merchant code S820211021094748000001
currency N currency THB(If no currency is passed, the balance of all currency units will be displayed)
sign Y RSA sign ja6R8eukQ...

# Request example

{
  "merchantCode": "S8202110212321300001",
  "currency": "THB",
  "sign": "X/o+IQUzLJqYe9Feid9Uww72mJGOvhJSJEIfo1EUChrZyVZnzGHtd61QhOqRmXCtAwk7V7k="
}

# Response param

param Type Required Description Example
success BOOLEAN Y response status true/false
code int Y response code 1000 means success, others are failure
message String Y response message return specific response information
data Json Y data The following parameters are all returned in data, or null if failed
mchId String Y merchant ID S8202110212321300001
mchName String Y merchant name test
mchNo String Y merchant number TP123
currency string Y currency IDR
balance String Y balance 1000.00
freeze String Y freeze 10.00
waitingSettleAmount String Y waiting settle amount 200.00
freezeWaitingSettleAmount String Y freeze waiting settle amount 100.00
totalAmount String Y total amount(balance+freeze+waiting settle amount +freeze waiting settle amount) 20000.00

# Response example

{
  "success": true,
  "code": 1000,
  "message": "SUCCESS",
  "data": [
    {
      "mchId": "S82022091232130000001",
      "mchName": "test",
      "mchNo": "test",
      "country": "THAILAND",
      "currency": "THB",
      "balance": "1000000.01",
      "freeze": "10.00",
      "waitingSettleAmount": "10.00",
      "freezeWaitingSettleAmount": "20.00",
      "totalAmount": "1000040.01"
    }
  ]
}