一、服務器端使用TP3.2處理(隨便寫在一個Controller裏面)php
/* 小程序報名,生成訂單 */ public function make_order(){ if(IS_POST){ $data['openid'] = I('POST.openid'); $data_total = I('POST.data_total'); $data['crsNo'] = 'W'.date('YmdHis',time()).'-'.randomkeys(2); $insertId = M('home_order','xxf_witkey_')->add($data); if($insertId){ $this->insertID = $insertId; $this->data_total = $data_total*100; //訂單總金額,單位分 /* 調用微信【統一下單】 */ $this->pay($data_total*100,$data['openid'],$data['crsNo']); }else{ echo $insertId; } //echo json_encode($re); } }
/* 首先在服務器端調用微信【統一下單】接口,返回prepay_id和sign簽名等信息給前端,前端調用微信支付接口 */ private function Pay($total_fee,$openid,$order_id){ if(empty($total_fee)){ echo json_encode(array('state'=>0,'Msg'=>'金額有誤'));exit; } if(empty($openid)){ echo json_encode(array('state'=>0,'Msg'=>'登陸失效,請從新登陸(openid參數有誤)'));exit; } if(empty($order_id)){ echo json_encode(array('state'=>0,'Msg'=>'自定義訂單有誤'));exit; } $appid = '小程序appid';//若是是公衆號 就是公衆號的appid;小程序就是小程序的appid $body = '本身填'; $mch_id = '商戶帳號'; $KEY = '你申請微信支付的key'; $nonce_str = randomkeys(32);//隨機字符串 $notify_url = 'https://m.******.com/index.php/Home/Xiaoxxf/xiao_notify_url'; //支付完成回調地址url,不能帶參數 $out_trade_no = $order_id;//商戶訂單號 $spbill_create_ip = $_SERVER['SERVER_ADDR']; $trade_type = 'JSAPI';//交易類型 默認JSAPI //這裏是按照順序的 由於下面的簽名是按照(字典序)順序 排序錯誤 確定出錯 $post['appid'] = $appid; $post['body'] = $body; $post['mch_id'] = $mch_id; $post['nonce_str'] = $nonce_str;//隨機字符串 $post['notify_url'] = $notify_url; $post['openid'] = $openid; $post['out_trade_no'] = $out_trade_no; $post['spbill_create_ip'] = $spbill_create_ip;//服務器終端的ip $post['total_fee'] = intval($total_fee); //總金額 最低爲一分錢 必須是整數 $post['trade_type'] = $trade_type; $sign = $this->MakeSign($post,$KEY); //簽名 $this->sign = $sign; $post_xml = '<xml> <appid>'.$appid.'</appid> <body>'.$body.'</body> <mch_id>'.$mch_id.'</mch_id> <nonce_str>'.$nonce_str.'</nonce_str> <notify_url>'.$notify_url.'</notify_url> <openid>'.$openid.'</openid> <out_trade_no>'.$out_trade_no.'</out_trade_no> <spbill_create_ip>'.$spbill_create_ip.'</spbill_create_ip> <total_fee>'.$total_fee.'</total_fee> <trade_type>'.$trade_type.'</trade_type> <sign>'.$sign.'</sign> </xml> '; //統一下單接口prepay_id $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder'; $xml = $this->http_request($url,$post_xml); //POST方式請求http $array = $this->xml2array($xml); //將【統一下單】api返回xml數據轉換成數組,全要大寫 if($array['RETURN_CODE'] == 'SUCCESS' && $array['RESULT_CODE'] == 'SUCCESS'){ $time = time(); $tmp=''; //臨時數組用於簽名 $tmp['appId'] = $appid; $tmp['nonceStr'] = $nonce_str; $tmp['package'] = 'prepay_id='.$array['PREPAY_ID']; $tmp['signType'] = 'MD5'; $tmp['timeStamp'] = "$time"; $data['state'] = 1; $data['timeStamp'] = "$time"; //時間戳 $data['nonceStr'] = $nonce_str; //隨機字符串 $data['signType'] = 'MD5'; //簽名算法,暫支持 MD5 $data['package'] = 'prepay_id='.$array['PREPAY_ID']; //統一下單接口返回的 prepay_id 參數值,提交格式如:prepay_id=* $data['paySign'] = $this->MakeSign($tmp,$KEY); //簽名,具體簽名方案參見微信公衆號支付幫助文檔; $data['out_trade_no'] = $out_trade_no; }else{ $data['state'] = 0; $data['text'] = "錯誤"; $data['RETURN_CODE'] = $array['RETURN_CODE']; $data['RETURN_MSG'] = $array['RETURN_MSG']; } echo json_encode($data); } /** * 生成簽名, $KEY就是支付key * @return 簽名 */ public function MakeSign( $params,$KEY){ //簽名步驟一:按字典序排序數組參數 ksort($params); $string = $this->ToUrlParams($params); //參數進行拼接key=value&k=v //簽名步驟二:在string後加入KEY $string = $string . "&key=".$KEY; //簽名步驟三:MD5加密 $string = md5($string); //簽名步驟四:全部字符轉爲大寫 $result = strtoupper($string); return $result; } /** * 將參數拼接爲url: key=value&key=value * @param $params * @return string */ public function ToUrlParams( $params ){ $string = ''; if( !empty($params) ){ $array = array(); foreach( $params as $key => $value ){ $array[] = $key.'='.$value; } $string = implode("&",$array); } return $string; } /** * 調用接口, $data是數組參數 * @return 簽名 */ public function http_request($url,$data = null,$headers=array()) { $curl = curl_init(); if( count($headers) >= 1 ){ curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); } curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE); if (!empty($data)){ curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, $data); } curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $output = curl_exec($curl); curl_close($curl); return $output; } //獲取xml裏面數據,轉換成array private function xml2array($xml){ $p = xml_parser_create(); xml_parse_into_struct($p, $xml, $vals, $index); xml_parser_free($p); $data = ""; foreach ($index as $key=>$value) { if($key == 'xml' || $key == 'XML') continue; $tag = $vals[$value[0]]['tag']; $value = $vals[$value[0]]['value']; $data[$tag] = $value; } return $data; }
/** * 將xml轉爲array * @param string $xml * return array */ public function xml_to_array($xml){ if(!$xml){ return false; } //將XML轉爲array //禁止引用外部xml實體 libxml_disable_entity_loader(true); $data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true); return $data; }
//還有就是,微信要求支付後處理微信發送的回調內容,就是告訴商戶,訂單交易成功了,你要發送‘我知道了’給微信。前端
//還有一點就是:這裏就是回調url,你預支付填寫的notify_url地址。廢話很少說,看下面算法
/* 微信支付完成,回調地址url方法 xiao_notify_url() */ public function xiao_notify_url(){ $post = post_data(); //接受POST數據XML個數
/*
function post_data(){
$receipt = $_REQUEST;
if($receipt==null){
$receipt = file_get_contents("php://input");
if($receipt == null){
$receipt = $GLOBALS['HTTP_RAW_POST_DATA'];
}
}
return $receipt;
}json
*/
$post_data = $this->xml_to_array($post); //微信支付成功,返回回調地址url的數據:XML轉數組Array $postSign = $post_data['sign']; unset($post_data['sign']); /* 微信官方提醒: * 商戶系統對於支付結果通知的內容必定要作【簽名驗證】, * 並校驗返回的【訂單金額是否與商戶側的訂單金額】一致, * 防止數據泄漏致使出現「假通知」,形成資金損失。 */ ksort($post_data);// 對數據進行排序 $str = $this->ToUrlParams($post_data);//對數組數據拼接成key=value字符串 $user_sign = strtoupper(md5($post_data)); //再次生成簽名,與$postSign比較 $where['crsNo'] = $post_data['out_trade_no']; $order_status = M('home_order','xxf_witkey_')->where($where)->find(); if($post_data['return_code']=='SUCCESS'&&$postSign){ /* * 首先判斷,訂單是否已經更新爲ok,由於微信會總共發送8次回調確認 * 其次,訂單已經爲ok的,直接返回SUCCESS * 最後,訂單沒有爲ok的,更新狀態爲ok,返回SUCCESS */ if($order_status['order_status']=='ok'){ $this->return_success(); }else{ $updata['order_status'] = 'ok'; if(M('home_order','xxf_witkey_')->where($where)->save($updata)){ $this->return_success(); } } }else{ echo '微信支付失敗'; } } /* * 給微信發送確認訂單金額和簽名正確,SUCCESS信息 -xzz0521 */ private function return_success(){ $return['return_code'] = 'SUCCESS'; $return['return_msg'] = 'OK'; $xml_post = '<xml> <return_code>'.$return['return_code'].'</return_code> <return_msg>'.$return['return_msg'].'</return_msg> </xml>'; echo $xml_post;exit; }
二、小程序端發起下單和支付請求:小程序
/** * 自定義方法,校驗form數據 */ submitForm: function (e) { //這裏是小程序wxml提交form var that = this;
//#code ,注意這裏的form數據你要校驗哦。 wx.request({ url: 'https://m.******.com/index.php/Home/Xiaoxxf/make_order', header: { "Content-Type": "application/x-www-form-urlencoded" }, method: "POST", data: { openid: wx.getStorageSync('openid'), data_name: e.detail.value.data_name, data_phone: e.detail.value.data_phone, data_IDcard: e.detail.value.data_IDcard, data_num: e.detail.value.data_num, data_addr: e.detail.value.data_addr, data_remark: e.detail.value.data_remark, data_total: e.detail.value.data_num * that.data.unitPrice,a_id:that.data.a_id}, success: function (res) { if (res.data.state==1) { // --------- 訂單生成成功,發起支付請求 ------------------ wx.requestPayment({ timeStamp: res.data.timeStamp, nonceStr: res.data.nonceStr, //字符串隨機數 package: res.data.package, signType: res.data.signType, paySign: res.data.paySign, 'success': function (res) { console.log(res.errMsg); //requestPayment:ok==>調用支付成功 wx.showToast({ title: '報名成功',//這裏打印出報名成功 icon: 'success', duration: 1000 }) }, 'fail': function (res) { console.log(res.errMsg); }, 'complete': function (res) { console.log(res.errMsg); } }) } else if (res.data.state == 0){ wx.showToast({ title: res.data.Msg, icon: 'fail', duration: 1000 }) }else{ wx.showToast({ title: '系統繁忙,請稍後重試~', icon: 'fail', duration: 1000 }) } } }) }