# 接口规则

# 协议规则

传输方式 采用HTTP传输
提交方式 采用POST/GET方式提交
字符编码 UTF-8
签名算法 MD5

# 参数规范

交易金额:默认为加币交易,单位为分,参数值不能带小数。

# 在线签名检查工具

在线签名检查

# 签名算法

# 第1步:

设所有发送或者接收到的数据为集合M,将集合M内非空参数值的参数按照参数名ASCII码从小到大排序(字典序),使用URL键值对的格式(即key1=value1&key2=value2…)拼接成字符串stringA。

特别注意以下重要规则:

  • 参数名ASCII码从小到大排序(字典序);
  • 如果参数的值为空不参与签名;
  • 参数名区分大小写;
  • 验证调用返回或支付中心主动通知签名时,传送的sign参数不参与签名,将生成的签名与该sign值作校验。
  • 支付中心接口可能增加字段,验证签名时必须支持增加的扩展字段;

# 第2步:

stringA最后拼接上&key=merchant_key 得到stringSignTemp字符串,并对stringSignTemp进行MD5运算,再将得到的字符串所有字符转换为大写,得到sign值signValue。 商户通过IOTPay获得merchant_keyapiKey

# PHP code

/** sign the string
	*$prestr string to be signed
	*return  
 */

function md5sign($prestr,$sign_type)
{
    $sign='';
    if($sign_type == 'MD5')
	{
        $sign = strtoupper(md5($prestr));//to upper case
    }
	else
	{
        die("only support MD5 for now".$sign_type);
    }
    return $sign;
}
/**
    *convert array to “key=value&key2=value2...” string
	*$array
	*return
*/
function create_linkstring($array)
{
    $arg  = "";
    while (list ($key, $val) = each ($array))
	{
       if($val!=''){
          $arg.=$key."=".$val."&";
		}
    }
    $arg = substr($arg,0,count($arg)-2);  //remove last '&'
    return $arg;
}
function build_mysign($sort_array,$key,$sign_type = "MD5") 
{
    $prestr = create_linkstring($sort_array); 
    $prestr = $prestr."&key=".$key;	

    $mysgin = md5sign($prestr,$sign_type);
    return $mysgin;
}	

function arg_sort($array) 
{
    ksort($array,SORT_NATURAL | SORT_FLAG_CASE);
    reset($array);
    return $array;
}

$arr = array(
    'mchId'=>$merchant_id,
    'mchOrderNo'=>$order_sn,
    'extra'=> $sceneInfo,    
    'channelId'=>$channelId,
    'currency'=>'CAD',
    'amount'=>intval($order_amount*100),
    'clientIp'=>$ip,
    'device'=>'WEB',
    'notifyUrl'=>$notifyUrl,
    'subject'=>$subject,
    'body'=>$body,
  );
   
$sort_array = arg_sort($arr);
$arr['sign']= build_mysign($sort_array,$merchant_key,"MD5");//generate signature
$arr['subject'] = urlencode($arr['subject'])  // urlencode after computing sign
$arr['body'] = urlencode($arr['body'])   // urlencode after computing sign
$param = 'params='.json_encode($arr);  //信用卡交易,不需要有'params='

$resBody = request($url,$param);//submit request

# Java code


import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;


import com.alibaba.fastjson.JSON;

public class TestSign {
	private static String encodingCharset = "UTF-8";
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("mchId", "10000XXX");
		map.put("mchOrderNo", "6199200000006");
		map.put("channelId", "WX_MICROPAY");
		map.put("currency", "CAD");
		map.put("codeType", "barcode");
		map.put("amount", "1");
		map.put("clientIp", "127.0.0.1");
		map.put("identityCode", "135021906891251756");
		map.put("device", "superscanner");
		map.put("deviceId", "superscanner_NS010");
		map.put("notifyUrl", "http://www.xxxx.ca/getnotify");
		map.put("subject", "test");
		map.put("body", "test body");
		String merchantKey = "xxxxxxxxxxxxxxxxxxxx";
		String sign = getSign(map, merchantKey);
		System.out.println("sign is [" + sign + "]");
		//sign is [E7F9184356482199D44C9FC20704B798]
		map.put("sign", sign);
		try {
			String strSubjectEncode = URLEncoder.encode(map.get("subject")+"", StandardCharsets.UTF_8.toString());
			map.put("subject", strSubjectEncode);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			String strBodyEncode = URLEncoder.encode(map.get("body")+"", StandardCharsets.UTF_8.toString());
			map.put("body", strBodyEncode);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		String strParam = JSON.toJSONString(map);
		
		String strOutputParams = "param=" + strParam;  //信用卡交易,不需要有'params='
		String url = "https://api.iotpaycloud.com/v1/create_order";
		String result = Http(url, strOutputParams);

	}
	public static String Http(String url, String param) {
		String result = "";
		//please add your http request here.
		return result;
	}
	public static String toHex(byte input[]) {
		if (input == null)
			return null;
		StringBuffer output = new StringBuffer(input.length * 2);
		for (int i = 0; i < input.length; i++) {
			int current = input[i] & 0xff;
			if (current < 16)
				output.append("0");
			output.append(Integer.toString(current, 16));
		}

		return output.toString();
	}
	public static String md5(String value, String charset) {
		MessageDigest md = null;
		try {
			byte[] data = value.getBytes(charset);
			md = MessageDigest.getInstance("MD5");
			byte[] digestData = md.digest(data);
			return toHex(digestData);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			return null;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return null;
		}
	}
	public static String getSign(Map<String,Object> map, String key){
		ArrayList<String> list = new ArrayList<String>();
		for(Map.Entry<String,Object> entry:map.entrySet()){
			if(!"".equals(entry.getValue())){
				list.add(entry.getKey() + "=" + entry.getValue() + "&");
			}
		}
		int size = list.size();
		String [] arrayToSort = list.toArray(new String[size]);
		Arrays.sort(arrayToSort, String.CASE_INSENSITIVE_ORDER);
		StringBuilder sb = new StringBuilder();
		for(int i = 0; i < size; i ++) {
			sb.append(arrayToSort[i]);
		}
		String result = sb.toString();
		result += "key=" + key;
		result = md5(result, encodingCharset).toUpperCase();
		return result;
	}
}

# C# code

using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;

namespace demo_sign
{
    class Program
    {
        //get the merchantKey from IOTPay
        static string merchantKey = "xxxxxxxxxxxxxxxxxxx";

        public static string GetMD5Hash(string str)
        {
            StringBuilder sb = new StringBuilder();
            using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider())
            {
                byte[] data = md5.ComputeHash(Encoding.UTF8.GetBytes(str));
                int length = data.Length;
                for (int i = 0; i < length; i++)
                    sb.Append(data[i].ToString("X2"));
            }
            return sb.ToString();
        }

        static string create_linkstring(SortedDictionary<string, string> dict)
        {
            string arg = "";
            foreach (KeyValuePair<string, string> kv in dict)
            {
                if (kv.Value != "")
                {
                    arg += kv.Key + "=" + kv.Value + "&";
                }
                
            }
            arg = arg.TrimEnd('&');
            return arg;

        }

        static void Main(string[] args)
        {
            //add all parameters into sorted dict, order by key name in lexicographic order
            SortedDictionary<string, string> para_array = new SortedDictionary<string, string>();
            para_array.Add("mchId", "10000XXX");
            para_array.Add("mchOrderNo", "6199200000006");
            para_array.Add("channelId", "WX_MICROPAY");
            para_array.Add("currency", "CAD");
            para_array.Add("codeType", "barcode");
            para_array.Add("amount", "1");
            para_array.Add("clientIp", "127.0.0.1");
            para_array.Add("identityCode", "135021906891251756");
            para_array.Add("device", "superscanner");
            para_array.Add("deviceId", "superscanner_NS010");
            para_array.Add("notifyUrl", "http://www.xxxx.ca/getnotify");
            para_array.Add("subject", "test");
            para_array.Add("body", "test body");

            Console.WriteLine(para_array.Count);
            //convert the dict to url string
            string link_str = create_linkstring(para_array);
            //append the merchant key as the last parameter
            link_str += ("&key="+merchantKey);
            Console.WriteLine(link_str);
            //get md5 sign value
            string sign = GetMD5Hash(link_str);
            Console.WriteLine(sign);

        }
    }
}

# VB code

Private Sub test()
    Dim disc As Object
    Set disc = CreateObject("Scripting.Dictionary")
    'get the merchantKey from IOTPay
    Dim merchantKey As String
    merchantKey = "xxxxxxxxxxxxxxxxxxxx"
    
    'add all parameters into sorted dict, order by key name in lexicographic order
    disc.Add "mchId", "10000xxx"
    disc.Add "mchOrderNo", "6199200000006"
    disc.Add "channelId", "WX_MICROPAY"
    disc.Add "currency", "CAD"
    disc.Add "codeType", "barcode"
    disc.Add "amount", "1"
    disc.Add "clientIp", "127.0.0.1"
    disc.Add "identityCode", "135021906891251756"
    disc.Add "device", "superscanner"
    disc.Add "deviceId", "superscanner_NS010"
    disc.Add "notifyUrl", "http://www.xxxx.ca/getnotify"
    disc.Add "subject", "test"
    disc.Add "body", "test body"

    sign = GetSign(disc, merchantKey)

    Debug.Print sign

    
End Sub
Function GetSign(disc As Object, merchantKey As String) As String

    ' Sort the keys
    Dim arrList As Object
    Set arrList = CreateObject("System.Collections.ArrayList")
    
    ' Put keys in an ArrayList
    Dim key As Variant, coll As New Collection
    For Each key In disc
        arrList.Add key
    Next key
    
    arrList.Sort
    
    ' convert the dict to url string
    Dim result As String
    Dim result_segment As String
    result_segment = ""
    For Each key In arrList
        result = result & result_segment & key & "=" & disc(key)
        result_segment = "&"
    Next key
    
    'append the merchant key as the last parameter
    result = result & result_segment & "key" & "=" & merchantKey
    
    'get md5 sign value
    GetSign = UCase(StringToMD5Hex(result))
End Function


Function StringToMD5Hex(ByVal s As String) As String
    Dim enc As Object
    Dim bytes() As Byte
    Dim pos As Long
    Dim outstr As String

    Set enc = CreateObject("System.Security.Cryptography.MD5CryptoServiceProvider")

    bytes = StrConv(s, vbFromUnicode)
    bytes = enc.ComputeHash_2(bytes)

    For pos = 1 To UBound(bytes) + 1
        outstr = outstr & LCase(Right("0" & Hex(AscB(MidB(bytes, pos, 1))), 2))
    Next pos

    StringToMD5Hex = outstr
    Set enc = Nothing
End Function

上次更新: 8/21/2020, 12:07:15 PM