zhichijunjun 2019-09-08
<?php class wxPay { /* 微信jsapi支付相关配置 */ protected $key = 'c2a7d232222222222e795'; //商户号API KEY 在商户后台设置 protected $appid = 'wxbb82111119f5e5f04'; //公众号appid protected $mchid = '11111111'; //商户号 /* 微信JSAPI支付 body out_trade_no 外部订单号 (自己生成的订单号) total_fee 支付的金额 notify_url 支付成功后的回调 openid 用户对应公众号的openid */ public function jsApiPay($params) { $postData = array(); $postData['appid'] = $this->appid; $postData['mch_id'] = $this->mchid; $postData['nonce_str'] = $this->createNoncestr(); $postData['body'] = $params['body']?$params['body']:'jsapi支付'; $postData['out_trade_no'] = $params['out_trade_no']; $postData['total_fee'] = $params['total_fee']; $postData["spbill_create_ip"] = $_SERVER["REMOTE_ADDR"]; $postData['notify_url'] = $params['notify_url']; $postData['trade_type'] = 'JSAPI'; $postData['openid'] = $params['openid']; $postData["sign"] = $this->createSign($postData); //把数组转化成xml格式 $xmlData = $this->arrayToXml($postData); $resXml = $this->curl_post('https://api.mch.weixin.qq.com/pay/unifiedorder', $xmlData); $resData = json_decode(json_encode(simplexml_load_string($resXml, 'SimpleXMLElement', LIBXML_NOCDATA)), true); if($resData['return_code']!='SUCCESS' || $resData['result_code']!='SUCCESS') return false; // 生成正式支付参数 $data = array( 'appId'=> $resData['appid'], 'nonceStr'=> $resData['nonce_str'], 'package'=> "prepay_id=" . $resData['prepay_id'], 'signType'=> 'MD5', 'timeStamp'=> time(), ); //支付签名 $data['paySign'] = $this->createSign($data); return $data; } //生成签名 private function createSign($params) { //签名步骤一:按字典序排序参数 ksort($params); $String = $this->formatBizQueryParaMap($params, false); //签名步骤二:在string后加入KEY $String = $String."&key=".$this->key; //签名步骤三:MD5加密 $String = md5($String); //签名步骤四:所有字符转为大写 $result_ = strtoupper($String); return $result_; } //按字典序排序参数 private function formatBizQueryParaMap($params,$urlencode=false) { ksort($params); $buff = ''; foreach($params as $key=>$val) { $buff .= $key . "=" . $val . "&"; } $reqPar = substr($buff, 0, strlen($buff)-1); return $reqPar; } //将数组转换为xml格式 private function arrayToXml($arr) { $xml = "<xml>"; foreach($arr as $key=>$val) { if(is_numeric($val)) $xml .= '<' . $key .'>' . $val . '</' . $key . '>'; else $xml .= "<".$key."><![CDATA[".$val."]]></".$key.">"; } $xml .="</xml>"; return $xml; } //随机字符串 private function createNoncestr($length=32) { $chars = 'abcdefghijklmnopqrstuvwxyz0123456789'; $str = ''; for($i=0;$i<$length;$i++){ $str .= substr($chars, mt_rand(0, strlen($chars)-1), 1); } return $str; } } //调用 $obj = new wxPay() $params = array(); $params['out_trade_no'] = date('YmdHis'); $params['total_fee'] = 100; $params['notify_url'] = 'http://www.xxx.com/mobile/notify.php'; $params['openid'] = 'ouD322auhn9o5m-8'; $res = $obj->jsApiPay($params); ?>
如果一直报签名错误, 可以先到签名工具里对签名进行验证。 如果在签名工具里校验签名是正确的,那很有可能是api key的问题,重新在商户后台 ,设置一下api key,一般就可以正常了