PHP實現微信小程序支付


本文僅記錄了微信小程序支付開發的基本流程和代碼,具體業務需自行修改。tp5框架下演示:

參考:

微信小程序支付:業務流程

SDK與DEMO:  下載頁

PHPPayDemo: demo

小程序端:

goPay(e){ 

  var that = this;

  //發起預支付,獲取所需參數
  wx.request({
      url: app.globalData.host + '/api/wx_pay/createOrder',   //請求地址
      data: {
        openid: wx.getStorageSync('openid'),
        total_fee: that.data.totalPrice,
        goods: JSON.stringify(that.data.goods)
      },
      method: 'POST',
      success(res){
     console.log(res)
if(res.data.code == 1){ //發起微信支付 wx.requestPayment({ timeStamp: res.data.data.timeStamp, nonceStr: res.data.data.nonceStr, package: res.data.data.package, signType: res.data.data.signType, paySign: res.data.data.paySign, success(r) {
        console.log(r) //do something
        //比如回調,修改狀態等操作 }, fail() { wx.showToast({ title: '支付失敗', icon: 'none' }) } }) }else{ wx.showToast({ title: res.data.data, icon: 'none' }) } } }) },

 

PHP端:

WxPay.php

<?php
namespace app\api\controller;
use app\api\controller\Common;
use think\Db;

/**
 * 微信支付
 */
class WxPay extends Common
{
    //生成訂單
    public function createOrder(){
        if (request()->isPost()) {
$openid = input('openid'); $total_fee = input('total_fee');$orderid = get_order_sn();  //生成訂單號 if (!$openid) { return json(array('code'=>3, 'data'=>'no openid')); } $goods = json_decode(input('goods'), TRUE); // 添加訂單,自行添加 $insert_order_id = Db::name('order') ->insertGetId(array( 'pay_price' => $total_fee, 'orderid' => $orderid ));        if($insert_order_id){
/* 調用微信【統一下單】 */
$res = $this->pay($
total_fee, $openid, $orderid);
 return json(array('code'=>1, 'data'=>$res, 'oid'=>$insert_order_id)); 
}
}
}
/* 首先在服務器端調用微信【統一下單】接口,返回prepay_id和sign簽名等信息給前端,前端調用微信支付接口 */
private function Pay($total_fee, $openid, $order_id, $body=''){
$appid = config('myapp.appid');//小程序的appid
$body = config('site.title').'-'.$body;
$mch_id = config('myapp.pay_mchid');
$KEY = config('myapp.pay_apikey');
$nonce_str = (string)mt_rand(10000, 99999).time();//隨機字符串
$notify_url = request()->domain().'api/wx_pay/notify'; //支付完成回調地址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); //簽名
$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['code'] = 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['code'] = 0;
    $data['msg'] = "錯誤";
    $data['RETURN_CODE'] = $array['RETURN_CODE'];
    $data['RETURN_MSG'] = $array['RETURN_MSG'];
    $data['ERR_CODE_DES'] = $array['ERR_CODE_DES'];
  }
  return $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;
}

//支付完后的回調
public function notify(){
  //do something  
//更新支付狀態
  //更新購物商品狀態
  
return json(array('code'=> 1, 'data'=>'支付成功'));
}

 

沒整理好,以后有時間再說吧,,,

以上所有方法都可從SDK及DEMO中尋得,官方參考。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM