Collect orders

# Code Sample

  • 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.Gson;
import com.google.gson.JsonObject;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.Map;
import java.util.TreeMap;

public class TopPayDemo {

  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 payUrl = "https://vnm-openapi.toppay.asia/gateway/prePayIn";
  private static final String payNotify = "your notify url";

  public static void main(String[] args) throws Exception {
    pay();
  }
  private static void pay() throws Exception {
    Map<String, String> requestParams = new TreeMap<>();
    requestParams.put("merchantCode", MCH_ID);
    requestParams.put("orderType", "0");
    requestParams.put("method", "QR");
    requestParams.put("orderNum", "T1324657980");
    requestParams.put("payMoney", "10000.00");
    requestParams.put("notifyUrl", payNotify);
    requestParams.put("dateTime", "20250514102512");
    List<String> paramNameList = new ArrayList<>();
    for (String key : requestParams.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(payUrl, postJson); 
    System.out.println("Response Msg:" + responseJson);
  }
}

<?php
    $platPublicKey = 'MIGfMA0GCSqG.........iDtQIDAQAB';
    $mchPrivateKey = 'MIICeAIBAD9Fz0.......jKTtoWN6j3F1V0bdyvhh';
    $merchantCode = 'S820250514103726000009';
    $orderType = '0';
    $orderNum = 'T1324657980';
    $payMoney = '10000.00';
    $notifyUrl = 'http://XXXXX';
    $dateTime = date("YmdHis",time());
    $params = array(
        'merchantCode' => $merchantCode,
        'orderType' => $orderType,
        'orderNum' => $orderNum,
        'payMoney' => $payMoney,
        'notifyUrl' => $notifyUrl,
        'dateTime' => $dateTime,
    );

    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/prePayIn';
    $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 "platRespCode :". $result['platRespCode'] . "\n";
        echo "platRespMessage :". $result['platRespMessage'] . "\n";
        echo "platOrderNum :". $result['platOrderNum'] . "\n";
        echo "orderNum :". $result['orderNum'] . "\n";
        echo "payMoney :". $result['payMoney'] . "\n";
        echo "platSign :". $result['platSign'] . "\n";

        $decryptStr = public_key_decrypt($result['platSign'], $platPublicKey);
        echo "decryptStr :". $decryptStr . "\n";
    }
    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);
    }

    function public_key_decrypt($data, $public_key)
    {
        $public_key = '-----BEGIN PUBLIC KEY-----'."\n".$public_key."\n".'-----END PUBLIC KEY-----';
        $data = base64_decode($data);
        $pu_key =  openssl_pkey_get_public($public_key);
        $crypto = '';
        foreach (str_split($data, 128) as $chunk) {
            openssl_public_decrypt($chunk, $decryptData, $pu_key);
            $crypto .= $decryptData;
        }

        return $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 CreateBillDemo
    {
        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/prePayIn";
        public static void requestPayment()
        {
            long currenttimemillis = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
            string merchantCode = MCH_ID;                                               
            string orderType = "0";                                                     
            string method = "QR";                                                       
            string orderNum = "T1324657980";                                       
            string payMoney = "10000";                                                 
            string notifyUrl = "https://www.baidu.com";                               
            string dateTime = "20251107105500";                                         
            Dictionary<string, object> VarPost = new Dictionary<string, object>(); ;
            VarPost.Add("merchantCode", merchantCode);
            VarPost.Add("orderType", orderType);
            VarPost.Add("method", method);
            VarPost.Add("orderNum", orderNum);
            VarPost.Add("payMoney", payMoney);
            VarPost.Add("notifyUrl", notifyUrl);
            VarPost.Add("dateTime", dateTime);
            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);
            Console.WriteLine("return:" + sRemoteInfo);    
            Dictionary<string, object> dict = JsonNewtonsoft.DeserializeJsonToDict(sRemoteInfo);
            bool pass = false;
            try
            {
                RSAForJava rsa = new RSAForJava();
                pass = rsa.verifySign(dict, PLAT_PUBLIC_KEY);  
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.WriteLine("verifysign:"+pass);
        }

    }
}

package main

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

type RequestBody struct {
	MerchantCode string `json:"merchantCode"`
	OrderType    string `json:"orderType"`
	OrderNum     string `json:"orderNum"`
	PayMoney     string `json:"payMoney"`
	NotifyUrl    string `json:"notifyUrl"`
	DateTime     string `json:"dateTime"`
	Method       string `json:"Method"`
	Sign         string `json:"sign"`
}

func main() {
	cryptor := NewCryptor()
	cryptor.Pub64 = "MIGfMA0GCSqG.........iDtQIDAQAB"
	cryptor.Pri64 = "MIICeAIBAD9Fz0.......jKTtoWN6j3F1V0bdyvhh"
	url := "https://vnm-openapi.toppay.asia/gateway/prePayIn"
	request := RequestBody{
		MerchantCode: "S820250514103726000009",
		OrderType:    "0",
		OrderNum:     "T1324657980",
		PayMoney:     "10000.00",
		NotifyUrl:    "http://xxxxxx",
		Method:       "QR",
		DateTime:     "20250101235959",
	}
	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 TopPayDemo:
    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/prePayIn"  
    pay_notify = "your notify url"

    @staticmethod
    def pay():
        request_params = OrderedDict()
        request_params["merchantCode"] = TopPayDemo.MCH_ID
        request_params["orderType"] = "0"
        request_params["payMoney"] = "10000.00"
        request_params["orderNum"] = "T1642592278863"
        request_params["method"] = "QR" 
        request_params["notifyUrl"] = "http://xxxxxx"
        request_params["dateTime"] = "20250514102565"

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

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

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

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

        check = TopPayDemo.public_key_decrypt(signed_str, TopPayDemo.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 orderType =0
var orderNum = 'T1642592278863'
var payMoney = 10000
var notifyUrl = 'http://xxxxxx'
var dateTime = '20250514102565'
var method = 'QR'
const data = {
    merchantCode: merchantCode,
    orderType: orderType,
    orderNum: orderNum,
    payMoney: payMoney,
    notifyUrl: notifyUrl,
    dateTime: dateTime,
    method: method
};
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/prePayIn'
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

  • Cashier (Mode 1): Use our POS system for transactions.

  • Request Method: POST

  • Request URL: https://vnm-openapi.toppay.asia/gateway/prePayIn

  • Direct Connection Mode (Mode 2): Retrieve payment information (suitable for merchants with their own POS page).

  • Request Method: POST

  • Request URL: https://vnm-openapi.toppay.asia/gateway/payment

# Request Parameters

Note: Do not fill in Chinese in all parameters!!!

Params Type Required Desc Ex
merchantCode String Y MchId S820250514103726000009
orderType String Y Order Type The default value is 0
method String Y Method BANK_QR
Click to view supported payment methods
orderNum String Y Merchant order number T1642592278863
payMoney String Y Payment amount (only two decimal places are allowed) 10000.00
notifyUrl String Y Notification Address https://host:port/notifyUrl
dateTime String Y yyyyMMddHHmmss 20190101235959
extendParam String N Transparent parameters (uploaded content will be returned by the original path) test
sign String Y Signature fnbSOvY83pr8hXg+Fd ...

# Request Params Example

{
    "merchantCode": "S820250514103726000009",
    "orderType": "0",
    "orderNum": "T1642593166888",
    "payMoney": "10000.00",
    "method": "QR",
    "notifyUrl": "your notify url",
    "dateTime": "20250514102565",
    "extendParam": "TEST",
    "sign": "fnbSOvY83pr8hXg+FdNNYi2ubQUGNv/qGYc4TjRl+Xxd1yc9fpkpTx5UQEDTgmhwdCKBkhHVsx2AiQbYDxZ5WBuU1GZeiJ"
}

# Response Params

Params Type Required Desc Ex
platRespCode String Y Request Result FAIL\SUCCESS
platRespMessage String Y Message Request Transaction Success
platOrderNum String Y Platform order number PI1453242857400963072
payMoney string Y Payment amount 10000.00
orderNum String Y Merchant order number T1234567980
payData String N Payment Info Mode 1 returns a link, Mode 2 returns payment information
extendParam string(100) N Transparent parameters (uploaded content will be returned by the original path) 123

# Response Params Example

{
    "platOrderNum": "P16546513165462132132",
    "payMoney": "10000.00",
    "orderNum": "T1642593166888",
    "platRespCode": "SUCCESS",
    "platRespMessage": "Request Transaction Success",
    "payData": "https://vnm-openapi.toppay.asia/gateway/order/P16546513165462132132",
    "extendParam": "TEST"
}

# Order Notification

  • **When verifying the signature, use the platform public key provided in the merchant backend-payment configuration-API configuration for decryption! ! ! **
  • When verifying the signature, the actual callback parameters shall prevail, and do not verify the fixed parameters
  • **The final status of the order shall be based on the status of the notification! ! ! **
  • **After receiving the asynchronous notification, you need to respond to the SUCCESS string, otherwise TopPay will continue to initiate 5 notifications! ! ! **
import com.google.gson.JsonObject;

public class TopPayNotify {
    private static final String PLAT_PUBLIC_KEY = "MIGfMA0GCSqG.........iDtQIDAQAB";
    public static void main(String[] args) throws Exception {
        JsonObject notifyBody = new jsonObject();
        boolean verifyResult = TopPayRequestUtil.verifySign(notifyBody,PLAT_PUBLIC_KEY);
        if (verifyResult) {
        } else {
        }
    }
}
<?php

$res = json_decode(file_get_contents('php://input'), true);
$platSign = $res['platSign'];
unset($res['platSign']);
$public_key = 'MIGfMA0GCSq.......zXwIDAQAB';
$decryptSign = public_key_decrypt($platSign, $public_key);

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

if($params_str == $decryptSign) {
    if($res['code'] == '00') {
        echo 'success';
    }
    else {
        echo 'fail';
    }
}
else {
    echo 'fail';
}

function public_key_decrypt($data, $public_key)
{
    $public_key = '-----BEGIN PUBLIC KEY-----'."\n".$public_key."\n".'-----END PUBLIC KEY-----';
    $data = base64_decode($data);
    $pu_key =  openssl_pkey_get_public($public_key);
    $crypto = '';
    foreach (str_split($data, 128) as $chunk) {
        openssl_public_decrypt($chunk, $decryptData, $pu_key);
        $crypto .= $decryptData;
    }

    return $crypto;
}
using demo.utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace demo.demos
{
    class CallbackDemo
    {
        private static readonly string PLAT_PUBLIC_KEY = "MIGfMA0GCSqG.........iDtQIDAQAB";
        private static readonly string jsonstr = "{\"code\":\"00\",\"msg\":\"SUCCESS\",\"platOrderNum\":\"I1_1289033071470972928\",\"payMoney\":\"10000\",\"method\":\"QR\",\"platSign\":\"INaY8jjdvaHdWKc4gXtTee9PwLl1157wC4+XN1tIQpHxnKtEjoGAD1cHok66eK+PzvPFUfmK/opvZhqf/MhOZEX6i/C9/iU4Esi9rfcN/l+DToG+rBPv8B4Ha908irHeosd3W4F1MnPCxxdjL+NH6aYyxX9cT5rZkJz5eUlr5Y8=\",\"orderNum\":\"T1596164382079\",\"status\":\"SUCCESS"}";

        public static void requestCallback()
        {
            bool pass = false;
            try
            {
                Dictionary<string, object> dict = JsonNewtonsoft.DeserializeJsonToDict(jsonstr);

                RSAForJava rsa = new RSAForJava();
                pass = rsa.verifySign(dict, PLAT_PUBLIC_KEY);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.WriteLine("verifysign:" + pass.ToString());
        }

    }
}

package main

import (
	"crypto/rsa"
	"crypto/x509"
	"encoding/base64"
	"fmt"
	"log"
	"math/big"
)

func main() {
	pubKeyBase64 := "MIGfMA0GCSqGSIb3D............jYvQK7QIDAQAB"
	
	encryptedData := "hPgCobTZQM36IxbSATbFncPc9hY............UH0ogKd7sdgw8vYg3fZu7NiI38="

	pubKey, err := parsePublicKey(pubKeyBase64)
	if err != nil {
		log.Fatalf("fail: %v", err)
	}

	encryptedBytes, err := base64.StdEncoding.DecodeString(encryptedData)
	if err != nil {
		log.Fatalf("fail: %v", err)
	}

	decryptedData, err := decryptWithPublicKey(pubKey, encryptedBytes)
	if err != nil {
		log.Fatalf("fail: %v", err)
	}

	fmt.Printf("result: %s\n", string(decryptedData))
}

func parsePublicKey(pubKeyBase64 string) (*rsa.PublicKey, error) {
	pubKeyBytes, err := base64.StdEncoding.DecodeString(pubKeyBase64)
	if err != nil {
		return nil, fmt.Errorf("fail: %v", err)
	}

	pubKeyInterface, err := x509.ParsePKIXPublicKey(pubKeyBytes)
	if err != nil {
		pubKeyInterface, err = x509.ParsePKCS1PublicKey(pubKeyBytes)
		if err != nil {
			return nil, fmt.Errorf("fail: %v", err)
		}
	}

	pubKey, ok := pubKeyInterface.(*rsa.PublicKey)
	if !ok {
		return nil, fmt.Errorf("fail")
	}

	return pubKey, nil
}

func decryptWithPublicKey(pubKey *rsa.PublicKey, encryptedData []byte) ([]byte, error) {
	k := (pubKey.N.BitLen() + 7) / 8
	if k != len(encryptedData) {
		return nil, fmt.Errorf("longth fail")
	}

	m := new(big.Int).SetBytes(encryptedData)
	if m.Cmp(pubKey.N) > 0 {
		return nil, fmt.Errorf("fail")
	}

	m.Exp(m, big.NewInt(int64(pubKey.E)), pubKey.N)

	d := leftPad(m.Bytes(), k)
	if d[0] != 0 {
		return nil, fmt.Errorf("error")
	}
	if d[1] != 0 && d[1] != 1 {
		return nil, fmt.Errorf("fail")
	}

	var i = 2
	for ; i < len(d); i++ {
		if d[i] == 0 {
			break
		}
	}
	i++
	if i == len(d) {
		return nil, nil
	}

	return d[i:], nil
}

func leftPad(input []byte, size int) []byte {
	n := len(input)
	if n > size {
		n = size
	}
	out := make([]byte, size)
	copy(out[len(out)-n:], input)
	return out
} 

import base64
import json
from collections import OrderedDict

import requests
from M2Crypto import RSA


class TopNotifyDemo:
    PLAT_PUBLIC_KEY_FILE = 'data\plat_rsa_public_key.pem'
    MCH_ID = "S820250514103726000009"

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


if __name__ == '__main__':
    response = '{"platOrderNum":"T123465790","payMoney":"10000","method":"QR","platSign":"INaY8jjdvaHdWKc4gXtTee9PwLl1157wC4+XN1tIQpHxnKtEjoGAD1cHok66eK+PzvPFUfmK/opvZhqf/MhOZEX6i/C9/iU4Esi9rfcN/l+DToG+rBPv8B4Ha908irHeosd3W4F1MnPCxxdjL+NH6aYyxX9cT5rZkJz5eUlr5Y8=\",\"orderNum\":\"T1596164382079\",\"code\":\"SUCCESS\",\"msg\":\"Request Transaction Success\",\"status\":\"SUCCESS"}'
    response_json = json.loads(response)
    sign = response_json["sign"]
    del response_json["sign"]
    sign='U/ohCCCF9Ia3Vq+eF0TIxM4yQBMLOANdNPdVJ+U3bVtBjxlAl8YnjgizhKuiaRlP4Em4clLcshlYTjtDX9aRDIjuCew8if4y7PAX5q66Zvka5XCJgu3jOpmOP0InVtTEndhVjNaQwYCnSc3W6w13vjshJZepHgyfjnb/ij4UjJU='
    data = json.JSONDecoder(object_pairs_hook=OrderedDict).decode(response_json)
    key_str = ''.join([str(value) for value in data.values()])
    check = TopNotifyDemo.public_key_decrypt(sign, TopNotifyDemo.PLAT_PUBLIC_KEY_FILE);
    if(key_str == check):
        print("true")
    print("false")
    print(response_json)

const { decryptWithPublicKey } = require('./RSAUtil');
const publicKey = `-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEB..........OQIDAQAB
-----END PUBLIC KEY-----`;

const jsonString = '{"msg":"SUCCESS","code":"00","method":"QR","orderNum":"20240508224642","platOrderNum":"P416514563454345","payMoney":"10000.00","platSign":"BCJqad4TC8iUQRlA1SqzWrnV86FNJ1ugcaAS+DToje0NLbDV2kPhI61Y3vXJShZD7Fo0NDmdaW1qu8i3Whf9jFmj4n9QqAAy5jC4dxmk//cpTSYW1kMGBQs0q6dkuMBnRL3WyGxeEW4W43p6NrrvGTcQUNs4Lu4oZhL1Wvg1MyA=","status":"SUCCESS"}';

try {
    const jsonObj = JSON.parse(jsonString);
    const signature = jsonObj.platSign;
    delete jsonObj['platSign'];   
    const sortedKeys = Object.keys(jsonObj).sort();
    let sortedString = '';
    sortedKeys.forEach(key => {
        sortedString += jsonObj[key];
    });
    console.log(sortedString);
   const decryptedData = decryptWithPublicKey(signature);
  
  console.log(sortedString === decryptedData.toString());
  if(sortedString === decryptedData.toString()){
  }
} catch (e) {
    console.error('error:', e);
}

# Params

Params Required Desc Ex
code Y Code 00
msg Y Message SUCCESS
method Y Method QR
status Y Order Status Order Status
platOrderNum Y Platform order number P16546513165462132132
orderNum Y Merchant order number T1231511321515
payMoney Y Order amount 10000.00
extendParam N Transparent parameters (uploaded content will be returned by the original path) TEST
platSign Platform Signature ja6R8eukQY9jc8zrhtf34654ungj7u8sdgdfjfs

# Response Example

{
    "code": "00",
    "msg": "SUCCESS",
    "status": "SUCCESS",
    "method": "QR",
    "platOrderNum": "P16546513165462132132",
    "orderNum": "T1642593166888",
    "payMoney": "10000.00",
    "extendParam": "TEST",
    "platSign": "ja6R8eukQY9jc8zrhtf34654ungj7u8sdgdfjfs"
}