以下內容請結合官方文檔
開發前准備:
商戶在微信開放平台申請開發應用后,微信開放平台會生成APP的唯一標識APPID。由於需要保證支付安全,需要在開放平台綁定商戶應用包名和應用簽名,設置好后才能正常發起支付。設置界面在【開放平台】中的欄目【管理中心 / 修改應用 / 修改開發信息】里面,如圖所示
應用簽名和應用包名如何寫,如果你是用apicloud開發的,前端會知道的,具體可參考官方文檔;下面我們就可以開始開發了
支付流程: 1.先調用統一下單API生成預付訂單
2.獲取到prepay_id后將參數再次簽名
3.傳輸給APP,發起支付
4.支付成功,異步回調
具體看代碼
WechatAppPay是我創建的第三方類
Wxpay是處理支付的
<?php namespace Wxpay; use app\common\lib\helper\ConfigHelper; use app\common\lib\helper\Helper; use think\Request; class WechatAppPay { private $appid = ''; private $partnerId = ''; private $key = ''; private $notify_url = ''; const URL='https://api.mch.weixin.qq.com/pay/unifiedorder'; function __construct() { $this->appid = ConfigHelper::getConfig('Wxpay_config')['appid']; $this->partnerId = ConfigHelper::getConfig('Wxpay_config')['mch_id']; $this->notify_url = ConfigHelper::getConfig('Wxpay_config')['notify_url']; $this->key = ConfigHelper::getConfig('Wxpay_config')['key']; } //生成訂單 public function wechat_pay($body, $out_trade_no, $total_fee){ $data["appid"] = $this->appid; $data["mch_id"] = $this->partnerId; $data["nonce_str"] = $this->getRandChar(32); $data["body"] = $body; $data["notify_url"] = $this->notify_url; $data["out_trade_no"] = $out_trade_no; $data["spbill_create_ip"] = $this->get_client_ip(); $data["total_fee"] = $total_fee; $data["trade_type"] = "APP"; $time_expire = date('YmdHis',time()+1200); //失效時間20分鍾 $data["time_expire"] = $time_expire; $sign = $this->getSign($data); $data["sign"] = $sign; //配置xml最終得到最終發送的數據 $formData=$this->data_to_xml($data); $response = $this->postXmlCurl($formData,self::URL); //將微信返回的結果xml轉成數組 $params = (array)simplexml_load_string($response, 'SimpleXMLElement', LIBXML_NOCDATA); if($params['return_code'] != 'SUCCESS'){ return Helper::ajaxFail($params); }else{ $timestamp = time(); //接收微信返回的數據,傳給APP! $arr =array( 'prepayid' =>$params['prepay_id'], 'appid' => $this->appid, 'partnerid' => $this->partnerId, 'package' => 'Sign=WXPay', 'noncestr' => $data["nonce_str"], 'timestamp' => strval($timestamp), ); //第二次生成簽名 $s = $this->getSign($arr); $arr['sign'] = $s; return Helper::ajaxSuccess($arr); } } //進行簽名 function getSign($Obj) { foreach ($Obj as $k => $v) { $arr[strtolower($k)] = $v; } ksort($arr); $string = $this->ToUrlParams($arr); $string = $string. "&key=".$this->key; $string = md5($string); $paySign = strtoupper($string); return $paySign; } public function https_request($url, $post_data = '', $timeout = 5){//curl $ch = curl_init(); curl_setopt ($ch, CURLOPT_URL, $url); curl_setopt ($ch, CURLOPT_POST, 1); if($post_data != ''){ curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data); } curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout); curl_setopt($ch, CURLOPT_HEADER, false); $file_contents = curl_exec($ch); curl_close($ch); return $file_contents; } public function data_to_xml( $params ){ if(!is_array($params)|| count($params) <= 0) { return false; } $xml = "<xml>"; foreach ($params as $key=>$val){ // if (is_numeric($val)){ $xml.="<".$key.">".$val."</".$key.">"; // }else{ // $xml.="<".$key."><![CDATA[".$val."]]></".$key.">"; // } } $xml.="</xml>"; return $xml; } //獲取指定長度的隨機字符串 private function getRandChar($length){ $str = null; $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz"; $max = strlen($strPol)-1; for($i=0;$i<$length;$i++){ $str.=$strPol[rand(0,$max)];//rand($min,$max)生成介於min和max兩個數之間的一個隨機整數 } return $str; } public function ToUrlParams($arr) { $buff = ""; foreach ($arr as $k => $v) { if($k != "sign" && $v != "" && !is_array($v)){ $buff .= $k . "=" . $v . "&"; } } $buff = trim($buff, "&"); return $buff; } //獲取當前服務器的IP function get_client_ip() { if ($_SERVER['REMOTE_ADDR']) { $cip = $_SERVER['REMOTE_ADDR']; } elseif (getenv("REMOTE_ADDR")) { $cip = getenv("REMOTE_ADDR"); } elseif (getenv("HTTP_CLIENT_IP")) { $cip = getenv("HTTP_CLIENT_IP"); } else { $cip = "unknown"; } return $cip; } //將數組轉成uri字符串 function formatBizQueryParaMap($paraMap, $urlencode) { $buff = ""; $reqPar=''; ksort($paraMap); foreach ($paraMap as $k => $v) { if($urlencode) { $v = urlencode($v); } $buff .= strtolower($k) . "=" . $v . "&"; } if (strlen($buff) > 0) { $reqPar = substr($buff, 0, strlen($buff)-1); } return $reqPar; } //數組轉xml 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; } //post https請求,CURLOPT_POSTFIELDS xml格式 function postXmlCurl($xml,$url,$second=30) { //初始化curl $ch = curl_init(); //超時時間 curl_setopt($ch,CURLOPT_TIMEOUT,$second); //這里設置代理,如果有的話 curl_setopt($ch,CURLOPT_URL, $url); curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE); curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE); //設置header curl_setopt($ch, CURLOPT_HEADER, FALSE); //要求結果為字符串且輸出到屏幕上 curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); //post提交方式 curl_setopt($ch, CURLOPT_POST, TRUE); curl_setopt($ch, CURLOPT_POSTFIELDS, $xml); //運行curl $data = curl_exec($ch); //返回結果 if($data) { curl_close($ch); return $data; } else { $error = curl_errno($ch); curl_close($ch); return false; } } //xml轉成數組 public function xmlstr_to_array($xmlstr) { $doc = new \DOMDocument(); $doc->loadXML($xmlstr); return $this->domnode_to_array($doc->documentElement); } public function domnode_to_array($node) { $output = array(); switch ($node->nodeType) { case XML_CDATA_SECTION_NODE: case XML_TEXT_NODE: $output = trim($node->textContent); break; case XML_ELEMENT_NODE: for ($i=0, $m=$node->childNodes->length; $i<$m; $i++) { $child = $node->childNodes->item($i); $v = $this->domnode_to_array($child); if(isset($child->tagName)) { $t = $child->tagName; if(!isset($output[$t])) { $output[$t] = array(); } $output[$t][] = $v; } elseif($v) { $output = (string) $v; } } if(is_array($output)) { if($node->attributes->length) { $a = array(); foreach($node->attributes as $attrName => $attrNode) { $a[$attrName] = (string) $attrNode->value; } $output['@attributes'] = $a; } foreach ($output as $t => $v) { if(is_array($v) && count($v)==1 && $t!='@attributes') { $output[$t] = $v[0]; } } } break; } return $output; } //微信支付成功以后的回調 public function notify() { $content = Request::instance()->getContent(); file_put_contents('test.txt',$content); $result = json_decode(json_encode(simplexml_load_string($content, 'SimpleXMLElement', LIBXML_NOCDATA)), true); //效驗簽名 $sign = $this->getSign($result); if ($sign == $result['sign']) { return $result; } else { return false; } } }
<?php namespace app\app_frontend\controller; use Wxpay\WechatAppPay; /** * @desc 微信支付接口 */ class Wxpay extends Common { public function pay(){ $body = '測試'; $out_trade_no = "wx".rand(1, 20).date('YmdHis',time()); //訂單號 $total_fee = 0.01 * 100; $WeChat = new WechatAppPay(); $res = $WeChat->wechat_pay($body, $out_trade_no, $total_fee); return $res; } }
/** * @return \think\response\Json * @desc 微信異步通知 */ public function WxPayBack(){ $WeChat = new WechatAppPay(); $res = $WeChat->notify(); if($res){ //簽名驗證通過后期處理 if($res['result_code'] == 'SUCCESS'){ //交易支付成功 $data = array( 'out_trade_no' => $res['out_trade_no'], 'trade_no' => $res['transaction_id'], 'total_amount' => $res['total_fee'] / 100, 'gmt_payment' => date( 'Y-m-d H:i:s',strtotime($res['time_end']) ), ); ChargeRecordModel::getInstance()->dataUpdate($data); //訂單處理 $info = array( 'return_code' => 'SUCCESS', 'return_msg' => 'OK' ); $formData=$this->arrayToXml($info); return $formData; } } }
配置參數:
//微信支付相關配置 'Wxpay_config' => array ( 'appid' => '', //應用id 'mch_id' => '', //商戶id 'key' => '', //商戶秘鑰 'notify_url' => '' //支付回調地址 ),