项目:开发了微信小程序,后台需要用到微信支付统一下单接口
1、微信商户平台APPID绑定授权申请
2、开通app支付,不行的话把其他支付也开通
3、在账户设置===》API安全===》设置api密钥
以上三步获取到:小程序appid,商户号和key
4、随机字符串(nonce_str),$length=32
public static function randomStr($length=32) {
$str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$len = 62;
while($length > $len) {
$str .= $str;
$len += 62;
}
$str = str_shuffle($str);
return substr($str, 0, $length);
}
5、签名算法,参数是统一下单接口的数组形式参数
public function getSign($urlObj='')
{
$buff = "";
ksort($urlObj);
foreach ($urlObj as $k => $v)
{
if($k != "sign"){
$buff .= $k . "=" . $v . "&";
}
}
$buff = trim($buff, "&");
$key=\Yii::$app->params['payment.weixin.appkey'];
$buff = $buff.'&key='.$key;
$buff = strtoupper(md5($buff));
return $buff;
}
6、数组转化xml
public function ToXml($data)
{
if(!is_array($data) || count($data) <= 0)
{
throw new WxPayException("数组数据异常!");
}
$xml = "<xml>";
foreach ($data as $key=>$val)
{
if (is_numeric($val)){
$xml.="<".$key.">".$val."</".$key.">";
}else{
$xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
}
}
$xml.="</xml>";
return $xml;
}
7、调用统一下单接口,$wxurl是统一下单接口, $data是第六步转化后的xml参数
/*小程序统一下单接口调用*/
public function getUrlInfo($wxurl,$data){
$headerArray =array("Content-type:application/json;charset='utf-8'","Accept:application/json");
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $wxurl);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,FALSE);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl,CURLOPT_HTTPHEADER,$headerArray);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($curl);
curl_close($curl);
return $output;
}
8、调用接口后返回xml转数组
/**
* 将xml转为array
* @param string $xml
* @throws WxPayException
*/
public function FromXml($xml)
{
if(!$xml){
throw new WxPayException("xml数据异常!");
}
//将XML转为array
//禁止引用外部xml实体
libxml_disable_entity_loader(true);
$arr = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
return $arr;
}
9、保存返回数据