Account balance inquiry

# Code example

  • The code example is for reference only. For specific parameter descriptions, please refer to the request parameter description

TopPayRequestUtil(Click here to get the code sample)


import com.google.gson.JsonObject;
public class BalanceQuery {
    
  private static final String MCH_ID = "S820250514103726000009";
  private static final String PLAT_PUBLIC_KEY = "MIGfMA0GCSqG.........iDtQIDAQAB";
  private static final String MCH_PRIVATE_KEY = "MIICeAIBAD9Fz0.......jKTtoWN6j3F1V0bdyvhh";
  private static final String BALANCE_QUERY_URL = "https://vnm-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", "VND");

    List<String> paramNameList = new ArrayList<>();
    for (String key : maps.keySet()) {
        paramNameList.add(key);
    }
    Collections.sort(paramNameList);
    StringBuilder stringBuilder = new StringBuilder();
    for (String key : paramNameList) {
        stringBuilder.append(requestParams.get(key));  
    }
    String keyStr = stringBuilder.toString();
    System.out.println("keyStr:" + keyStr);
    String signedStr = TopPayRequestUtil.privateEncrypt(keyStr, TopPayRequestUtil.getPrivateKey(MCH_PRIVATE_KEY));
    requestParams.put("sign", signedStr);

    String postJson = new Gson().toJson(requestParams);
    System.out.println("Post Json Params:" + postJson);
    String responseJson = TopPayRequestUtil.doPost(orderQueryUrl, postJson);  
    System.out.println("Response Msg:" + responseJson);
  }
}


<?php
    $mchPrivateKey = 'MIICeAIBAD9Fz0.......jKTtoWN6j3F1V0bdyvhh';
    
    $merchantCode = 'S820250514103726000009';
    
    $currency = 'VND';
    $params = array(
        'merchantCode' => $merchantCode,
        'currency' => $currency,
    );

    ksort($params);
    $params_str = '';
    foreach ($params as $key => $val) {
        $params_str = $params_str . $val;
    }
    $sign = pivate_key_encrypt($params_str, $mchPrivateKey);
    $params['sign'] = $sign;
    $params_string = json_encode($params);
    $url = 'https://vnm-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);

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

    if($httpCode == 200)
    {
        $result = json_decode($request, true);
        echo "message :". $result['message'] . "<br>";
        $thbData = array();
        foreach ($result['data'] as $item) {
            if ($item['currency'] === 'VND') {
                $thbData[] = $item;
            }
        }
        print_r($thbData);
    }
    else {
        echo $httpCode;
    }
    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 BalanceQueryDemo
    {
        private static readonly string MCH_ID = "S820250514103726000009";   
        private static readonly string PLAT_PUBLIC_KEY = "MIGfMA0GCSqG.........iDtQIDAQAB";  
        private static readonly string MCH_PRIVATE_KEY = "MIICeAIBAD9Fz0.......jKTtoWN6j3F1V0bdyvhh";
        private static readonly string payUrl = "https://vnm-openapi.toppay.asia/gateway/interface/getBalance";
        public static void requestQuery()
        {
            long currenttimemillis = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
            string merchantCode = MCH_ID;
            string currency = "VND";
            Dictionary<string, object> VarPost = new Dictionary<string, object>(); ;
            VarPost.Add("merchantCode", merchantCode);
            VarPost.Add("currency", currency);
            List<string> paramNameList = new List<string>();
            foreach (string key in VarPost.Keys)
            {
                paramNameList.Add(key);
            }
            paramNameList.Sort();
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < paramNameList.Count; i++)
            {
                string key = paramNameList[i];
                stringBuilder.Append(VarPost[key]);
            }
            string keyStr = stringBuilder.ToString();
            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);
            string sRemoteInfo = w.UploadString(payUrl, "POST", jsonStr);
        }

    }
}

package main

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

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

func main() {
	cryptor := NewCryptor()
	cryptor.Pub64 = "MIGfMA0GCSqG.........iDtQIDAQAB"
	cryptor.Pri64 = "MIICeAIBAD9Fz0.......jKTtoWN6j3F1V0bdyvhh"
	
	url := "https://vnm-openapi.toppay.asia/gateway/interface/getBalance"
	request := RequestBody{
		MerchantCode: "S820250514103726000009",
		Currency: "VND",
	}
	sortedValues, err := sortedConcatenatedValues(request)
	if err != nil {
		fmt.Printf("Error: %s\n", err)
		return
	}
	encryptedData := cryptor.PriEncrypt([]byte(sortedValues))
	encodedString := base64.StdEncoding.EncodeToString(encryptedData)
	request.Sign = encodedString
	jsonBytes, err := json.Marshal(request)
	if err != nil {
		fmt.Printf("Error: %s", err.Error())
		return
	}
	fmt.Println("json2", bytes.NewBuffer(jsonBytes))
	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()
	respBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("Error reading response body:", err)
		return
	}
	fmt.Println("Response Body:", string(respBody))
}

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]
		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:
    MCH_PRI_KEY_FILE = '\data\company_rsa_private_key.pem'
    MCH_PUBLIC_KEY_FILE = '\data\plat_rsa_public_key.pem'
    
    MCH_ID = "S820250514103726000009"
    
    url = "https://vnm-openapi.toppay.asia/gateway/interface/getBalance"

    @staticmethod
    def cash():
        request_params = OrderedDict()
        request_params["merchantCode"] = TopQueryDemo.MCH_ID
        request_params["currency"] = "VND"

        key_str = ''.join([str(value) for value in request_params.values()])
        print("keyStr:", key_str)

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

        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)
        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');

var merchantCode = 'S820250514103726000009'
var currency = 'VND'
const data = {
    merchantCode: merchantCode,
    currency: currency
};
console.log(merchantCode)
console.log(data.merchantCode)

const sortedKeys = Object.keys(data).sort();

let sortedString = '';
sortedKeys.forEach(key => {
    sortedString += data[key];
});

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

data.sign = sign;
const jsonData = JSON.stringify(data);
console.log(jsonData)

var url = 'https://vnm-openapi.toppay.asia/gateway/interface/getBalance'
axios.post(url, jsonData,{
  headers: {
    'Content-Type': 'application/json'
  }
})
.then((response) => {
  console.log('code:', response.status);
  console.log('msg:', response.data);
})
.catch((error) => {
  console.error('fail:', error);
});

# API address

  • Request method : POST
  • Request address : https://vnm-openapi.toppay.asia/gateway/interface/getBalance

# Request Parameters

Params Type Required Ex
merchantCode MchId Y S820211021094748000001
currency Currency N VND(If not passed, balances in all currencies will be displayed)
sign RSA Signature Y ja6R8eukQ...

# Request message example

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

# Response Parameters

Params Type Required Desc Ex
success BOOLEAN Y Request Result true/false
code Int Y Code 1000-SUCCESS,all others are failures
message String Y message Response Info
data Json Y Data The following parameters are returned in data, or null if failed
mchId String Y MchId S8202110212321300001
mchName String Y MchName test
mchNo String Y MchNo TP123
currency String Y Currency VND
balance String Y Available balance 1000.00
freeze String Y Freeze Balance 10.00
waitingSettleAmount String Y Amount to be settled 200.00
freezeWaitingSettleAmount String Y Freeze the amount to be settled 100.00
totalAmount String Y Total amount (available balance + frozen balance + pending settlement amount + frozen pending settlement amount) 20000.00

# Response result example

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