1、核心代码:
<?php require("helper.php"); header('content-type:text/html;charset=utf-8'); $key = 'C43D436036E643F5AFA654FED758BCF7'; //参数数组 $post_data = array ( "parter" => '2308', "orderid" => '201711021121', ); //签名 ksort($post_data);//键按ASCII码升序排序 $preSignString=getPreSignString($post_data); $sign = md5($preSignString.'&key='.$key); $sign=strtoupper($sign);//大写 //签名参数添加到参数数组 $post_data['sign']=$sign; //参数转成json $parameters =json_encode($post_data); //发送请求 $url='http://localhost:64781/api/Query/QueryStatus'; $ch = curl_init(); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $response = curl_exec($ch); curl_close($ch); //处理返回数据 $responseData=json_decode($response,true);//发序列化为数组 print_r($responseData);
2、工具类代码:
<?php /* * 获取待签名字符串 * */ function getPreSignString($array) { $prestr=''; if(empty($array)) return $prestr; else { foreach($array as $key=>$value){ if(!empty(trim($value)) && strtolower($key)!='sign') { $prestr.=$key.'='.$value.'&'; } } if(!empty($prestr)){ $length=strlen($prestr); $prestr=substr($prestr,0,$length-1);//去掉最后一个‘&’ } return $prestr; } }
3、调试:
3.1 远程接口接收数据包:
以c#为例(以流的形式接收):
Stream requestData = HttpContext.Current.Request.InputStream; //获取参数 byte[] b = new byte[requestData.Length]; requestData.Read(b, 0, (int)requestData.Length); string postdata = Encoding.UTF8.GetString(b);
postdata 结果如下:
{"orderid":"201711021121","parter":"2308","sign":"A75F1B4687105C84666F0812AB24232D"}
3.2 远程接口返回数据包(这里把接收的json转为数组):
Array ( [orderid] => 201711021121 [ekaorderid] => 17110213495685030814 [opstate] => 1 [parter] => 2308 [ovalue] => 100.1000 [code] => 0000 [msg] => 成功 )