微信小程序支付接入注意點


一、微信支付后台服務器部署

服務器采用ubuntu16.04 + php7.0 + apache2.0。

微信支付后台服務使用了curl 和 samplexml ,因此php.ini配置中必須開啟這兩項的擴展。

查看是否開啟這兩項擴展:在網站根目錄下(www)下新建index.php文件,文件代碼寫入:phpinfo() 保存退出,然后訪問index.php.如果在網頁中找到,這說明已經開啟,反之沒有開啟。

如果沒有開啟這兩項擴展,微信小程序支付調試會提示:內部錯誤(500)

1、開啟curl擴展的方法:

sudo apt-get install curl libcurl3 libcurl-dev php7.0-curl

命令成功安裝curl后,重啟apache服務

sudo /etc/init.d/apache2 restart

如果仍有問題,嘗試編輯php.ini配置文件(文件路徑:/etc/php/7.0/apache2/php.ini)

找到“extentsion = php_curl.dll”把前面的“#”號去掉,保存重啟apache服務。

2、開啟simplexml方法:

sudo apt-get install php7.0-xml

命令成功安裝samplexml 重啟apache服務

如果仍有問題,嘗試編輯php.ini配置文件

找到“extentsion = php_samplexml.dll” 去掉前面的“#”,保存重啟apache服務。

二、微信支付服務程序搭建

去官網下載sdk和demo文件。我們這里是下載php版本。

下載地址:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=11_1

sdk與demo的文件結構如下:

下載文件后把文件拷貝到服務器上,服務的入口文件是 wxpay/jsapi.php

 

 1 <?php
 2   /**
 3   *微信小程序支付后台交易程序
 4   **/
 5   require_once "../lib/WxPay.Api.php";
 6   require_once "WxPay.Config.php";
 7   require_once 'log.php';
 8   header('Access-Control-Allow-Origin:*');//注意!跨域要加這個頭
 9   header("Access-Control-Allow-Method:POST,GET");
10  /*
11   * 初始化日志
12   * 
13  */
14  $logHandler= new CLogFileHandler("../logs/".date('Y-m-d').'.log');
15  $log = Log::Init($logHandler);
16  
17  if($_SERVER['REQUEST_METHOD'] != 'POST'){
18          return_err('error request method');
19  }
20  log::info("*****交易開始*****");
21  //$info = json_encode($_POST);
22  //log::info($info);
23  try{
24       $openid = $_POST['openid'];//openid 微信唯一識別碼
25       $body = $_POST['body'];//設置商品或支付單簡要描述
26       $order_sn = $_POST['order_sn'];//訂單號
27       $total_fee = $_POST['total_fee'];//付款金額
28       log::info('*****獲取post值開始*****');
29       log::info($openid);
30       log::info($body);
31       log::info($order_sn);
32       log::info($total_fee);
33       log::info('*****獲取post值結束*****');
34       /*統一下單*/
35       $input = new WxPayUnifiedOrder();
36       $input->SetBody($body);//設置商品或支付單簡要描述
37       $input->SetAttach($body);//設置附加數據,在查詢API和支付通知中原樣返回,該字段主要用於商戶攜帶訂單的自定義數據
38       $input->SetOut_trade_no($order_sn);//設置商戶系統內部的訂單號,32個字符內、可包含字母, 其他說明見商戶訂單號
39       $input->SetTotal_fee($total_fee);//設置訂單總金額,只能為整數,詳見支付金額
40       $input->SetTime_start(date("YmdHis"));
41       $input->SetTime_expire(date("YmdHis", time() + 600));
42       //$input->SetGoods_tag("test");//設置商品標記,代金券或立減優惠功能的參數,說明詳見代金券或立減優惠
43       $input->SetNotify_url( 'https://'.$_SERVER['HTTP_HOST'].'/notify.php');
44       $input->SetTrade_type("JSAPI");
45       $input->SetOpenid($openid);
46       $config = new WxPayConfig();
47       $order = WxPayApi::unifiedOrder($config, $input);
48       return_data($order);
49  
50  } catch(Exception $e) {
51     log::info('*****異常錯誤開始*****');
52  }
53 /**
54  * 錯誤返回提示
55  * @param string $errMsg 錯誤信息
56  * @param string $status 錯誤碼
57  * @return  json的數據
58  */
59 function return_err($errMsg='error',$status=0){
60    $ret_str = json_encode(array('status'=>$status,'result'=>'fail','errmsg'=>$errMsg));
61     Log::ERROR("error request method");
62    exit($ret_str);
63 }
64 /**
65  * 正確返回
66  * @param  array $data 要返回的數組
67  * @return  json的數據
68  */
69 function return_data($data=array()){
70    $ret_str = json_encode(array('status'=>1,'result'=>'success','data'=>$data));
71     log::INFO($ret_str);
72    exit($ret_str);
73 }

 

在配置文件中配置相應的常量,必須注意一點的是商戶號 mchid 與 appid 一定要匹配,,如果調試提示未匹配在,進入 微信支付后台(pay.weixin.qq.com) 中的產品中心下的APPID授權管理中加入,加入后需要,登入小程序的管理后台審核通過。

經過上面的注意事項后,程序支付調用成功,則返回 

 

根據返回的內容,發起微信支付請求,下面是支付函數封裝

 
         
/**
* 微信支付
* 參數說明:
* @body 商品或支付單簡要描述
* @order_no 訂單號
* @totalprice 支付金額 (微信支付是以分為單位的,要轉換成元為單位。)
* function wxpay(body, order_sn, totalpri    var that = this   wx.request({
 url: app.globalData.urlWxpayPath, method: "POST", header: { 'content-type': 'application/x-www-form-urlencoded' }, data: { "openid": app.globalData.openid, "body": body, "order_sn": order_sn, "total_fee": Number(totalprice)*100 //微信支付是以分為單位的,要轉換成元為單位。 }, success: function (res) { //console.log(res); //console.log(new Date().bv ().toString()); var appid = res.data.data.appid; var mch_id = res.data.data.mch_id; var prepay_id = res.data.data.prepay_id; var sign = res.data.data.sign; var trade_type = res.data.data.trade_type; var timeStamp = new Date().getTime().toString();//時間戳 var nonceStr = res.data.data.nonce_str; var signType = 'MD5'; const key = app.globalData.key;//key為商戶的支付密鑰,微信后台頁面可以查詢到。 var pg = 'prepay_id=' + res.data.data.prepay_id;
//md5加密
var paySign = utils.hexMD5('appId=' + appid + '&nonceStr=' + nonceStr + '&package=' + pg + '&signType=' + signType + '&timeStamp=' + timeStamp + '&key=' + key); //console.log(paySign.toUpperCase()); wx.requestPayment({ timeStamp: timeStamp, nonceStr: nonceStr, package: pg, signType: 'MD5', paySign: paySign.toUpperCase(), success: function (res) { //接口調用成功的回調函數 //console.log(res) wx.showToast({ title: '支付成功', icon: 'none', duration: 2000 }) }, fail: function (res) { //接口調用失敗的回調函數 wx.showToast({ title: '支付失敗', icon: 'none', duration: 2000 }) }, complete: function (res) { //接口調用結束的回調函數(調用成功、失敗都會執行) console.log(res); } }) } }) }

支付請求中paySign涉及到一個md5 加密算法

/* 
 * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message 
 * Digest Algorithm, as defined in RFC 1321. 
 * Version 1.1 Copyright (C) Paul Johnston 1999 - 2002. 
 * Code also contributed by Greg Holt 
 * See http://pajhome.org.uk/site/legal.html for details. 
 */

/* 
 * Add integers, wrapping at 2^32. This uses 16-bit operations internally 
 * to work around bugs in some JS interpreters. 
 */
function safe_add(x, y) {
  var lsw = (x & 0xFFFF) + (y & 0xFFFF)
  var msw = (x >> 16) + (y >> 16) + (lsw >> 16)
  return (msw << 16) | (lsw & 0xFFFF)
}

/* 
 * Bitwise rotate a 32-bit number to the left. 
 */
function rol(num, cnt) {
  return (num << cnt) | (num >>> (32 - cnt))
}

/* 
 * These functions implement the four basic operations the algorithm uses. 
 */
function cmn(q, a, b, x, s, t) {
  return safe_add(rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b)
}
function ff(a, b, c, d, x, s, t) {
  return cmn((b & c) | ((~b) & d), a, b, x, s, t)
}
function gg(a, b, c, d, x, s, t) {
  return cmn((b & d) | (c & (~d)), a, b, x, s, t)
}
function hh(a, b, c, d, x, s, t) {
  return cmn(b ^ c ^ d, a, b, x, s, t)
}
function ii(a, b, c, d, x, s, t) {
  return cmn(c ^ (b | (~d)), a, b, x, s, t)
}

/* 
 * Calculate the MD5 of an array of little-endian words, producing an array 
 * of little-endian words. 
 */
function coreMD5(x) {
  var a = 1732584193
  var b = -271733879
  var c = -1732584194
  var d = 271733878

  for (var i = 0; i < x.length; i += 16) {
    var olda = a
    var oldb = b
    var oldc = c
    var oldd = d

    a = ff(a, b, c, d, x[i + 0], 7, -680876936)
    d = ff(d, a, b, c, x[i + 1], 12, -389564586)
    c = ff(c, d, a, b, x[i + 2], 17, 606105819)
    b = ff(b, c, d, a, x[i + 3], 22, -1044525330)
    a = ff(a, b, c, d, x[i + 4], 7, -176418897)
    d = ff(d, a, b, c, x[i + 5], 12, 1200080426)
    c = ff(c, d, a, b, x[i + 6], 17, -1473231341)
    b = ff(b, c, d, a, x[i + 7], 22, -45705983)
    a = ff(a, b, c, d, x[i + 8], 7, 1770035416)
    d = ff(d, a, b, c, x[i + 9], 12, -1958414417)
    c = ff(c, d, a, b, x[i + 10], 17, -42063)
    b = ff(b, c, d, a, x[i + 11], 22, -1990404162)
    a = ff(a, b, c, d, x[i + 12], 7, 1804603682)
    d = ff(d, a, b, c, x[i + 13], 12, -40341101)
    c = ff(c, d, a, b, x[i + 14], 17, -1502002290)
    b = ff(b, c, d, a, x[i + 15], 22, 1236535329)

    a = gg(a, b, c, d, x[i + 1], 5, -165796510)
    d = gg(d, a, b, c, x[i + 6], 9, -1069501632)
    c = gg(c, d, a, b, x[i + 11], 14, 643717713)
    b = gg(b, c, d, a, x[i + 0], 20, -373897302)
    a = gg(a, b, c, d, x[i + 5], 5, -701558691)
    d = gg(d, a, b, c, x[i + 10], 9, 38016083)
    c = gg(c, d, a, b, x[i + 15], 14, -660478335)
    b = gg(b, c, d, a, x[i + 4], 20, -405537848)
    a = gg(a, b, c, d, x[i + 9], 5, 568446438)
    d = gg(d, a, b, c, x[i + 14], 9, -1019803690)
    c = gg(c, d, a, b, x[i + 3], 14, -187363961)
    b = gg(b, c, d, a, x[i + 8], 20, 1163531501)
    a = gg(a, b, c, d, x[i + 13], 5, -1444681467)
    d = gg(d, a, b, c, x[i + 2], 9, -51403784)
    c = gg(c, d, a, b, x[i + 7], 14, 1735328473)
    b = gg(b, c, d, a, x[i + 12], 20, -1926607734)

    a = hh(a, b, c, d, x[i + 5], 4, -378558)
    d = hh(d, a, b, c, x[i + 8], 11, -2022574463)
    c = hh(c, d, a, b, x[i + 11], 16, 1839030562)
    b = hh(b, c, d, a, x[i + 14], 23, -35309556)
    a = hh(a, b, c, d, x[i + 1], 4, -1530992060)
    d = hh(d, a, b, c, x[i + 4], 11, 1272893353)
    c = hh(c, d, a, b, x[i + 7], 16, -155497632)
    b = hh(b, c, d, a, x[i + 10], 23, -1094730640)
    a = hh(a, b, c, d, x[i + 13], 4, 681279174)
    d = hh(d, a, b, c, x[i + 0], 11, -358537222)
    c = hh(c, d, a, b, x[i + 3], 16, -722521979)
    b = hh(b, c, d, a, x[i + 6], 23, 76029189)
    a = hh(a, b, c, d, x[i + 9], 4, -640364487)
    d = hh(d, a, b, c, x[i + 12], 11, -421815835)
    c = hh(c, d, a, b, x[i + 15], 16, 530742520)
    b = hh(b, c, d, a, x[i + 2], 23, -995338651)

    a = ii(a, b, c, d, x[i + 0], 6, -198630844)
    d = ii(d, a, b, c, x[i + 7], 10, 1126891415)
    c = ii(c, d, a, b, x[i + 14], 15, -1416354905)
    b = ii(b, c, d, a, x[i + 5], 21, -57434055)
    a = ii(a, b, c, d, x[i + 12], 6, 1700485571)
    d = ii(d, a, b, c, x[i + 3], 10, -1894986606)
    c = ii(c, d, a, b, x[i + 10], 15, -1051523)
    b = ii(b, c, d, a, x[i + 1], 21, -2054922799)
    a = ii(a, b, c, d, x[i + 8], 6, 1873313359)
    d = ii(d, a, b, c, x[i + 15], 10, -30611744)
    c = ii(c, d, a, b, x[i + 6], 15, -1560198380)
    b = ii(b, c, d, a, x[i + 13], 21, 1309151649)
    a = ii(a, b, c, d, x[i + 4], 6, -145523070)
    d = ii(d, a, b, c, x[i + 11], 10, -1120210379)
    c = ii(c, d, a, b, x[i + 2], 15, 718787259)
    b = ii(b, c, d, a, x[i + 9], 21, -343485551)

    a = safe_add(a, olda)
    b = safe_add(b, oldb)
    c = safe_add(c, oldc)
    d = safe_add(d, oldd)
  }
  return [a, b, c, d]
}

/* 
 * Convert an array of little-endian words to a hex string. 
 */
function binl2hex(binarray) {
  var hex_tab = "0123456789abcdef"
  var str = ""
  for (var i = 0; i < binarray.length * 4; i++) {
    str += hex_tab.charAt((binarray[i >> 2] >> ((i % 4) * 8 + 4)) & 0xF) +
      hex_tab.charAt((binarray[i >> 2] >> ((i % 4) * 8)) & 0xF)
  }
  return str
}

/* 
 * Convert an array of little-endian words to a base64 encoded string. 
 */
function binl2b64(binarray) {
  var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
  var str = ""
  for (var i = 0; i < binarray.length * 32; i += 6) {
    str += tab.charAt(((binarray[i >> 5] << (i % 32)) & 0x3F) |
      ((binarray[i >> 5 + 1] >> (32 - i % 32)) & 0x3F))
  }
  return str
}

/* 
 * Convert an 8-bit character string to a sequence of 16-word blocks, stored 
 * as an array, and append appropriate padding for MD4/5 calculation. 
 * If any of the characters are >255, the high byte is silently ignored. 
 */
function str2binl(str) {
  var nblk = ((str.length + 8) >> 6) + 1 // number of 16-word blocks  
  var blks = new Array(nblk * 16)
  for (var i = 0; i < nblk * 16; i++) blks[i] = 0
  for (var i = 0; i < str.length; i++)
    blks[i >> 2] |= (str.charCodeAt(i) & 0xFF) << ((i % 4) * 8)
  blks[i >> 2] |= 0x80 << ((i % 4) * 8)
  blks[nblk * 16 - 2] = str.length * 8
  return blks
}

/* 
 * Convert a wide-character string to a sequence of 16-word blocks, stored as 
 * an array, and append appropriate padding for MD4/5 calculation. 
 */
function strw2binl(str) {
  var nblk = ((str.length + 4) >> 5) + 1 // number of 16-word blocks  
  var blks = new Array(nblk * 16)
  for (var i = 0; i < nblk * 16; i++) blks[i] = 0
  for (var i = 0; i < str.length; i++)
    blks[i >> 1] |= str.charCodeAt(i) << ((i % 2) * 16)
  blks[i >> 1] |= 0x80 << ((i % 2) * 16)
  blks[nblk * 16 - 2] = str.length * 16
  return blks
}

/* 
 * External interface 
 */
function hexMD5(str) { return binl2hex(coreMD5(str2binl(str))) }
function hexMD5w(str) { return binl2hex(coreMD5(strw2binl(str))) }
function b64MD5(str) { return binl2b64(coreMD5(str2binl(str))) }
function b64MD5w(str) { return binl2b64(coreMD5(strw2binl(str))) }
/* Backward compatibility */
function calcMD5(str) { return binl2hex(coreMD5(str2binl(str))) }
module.exports = {
  hexMD5: hexMD5
}

這樣程序就會成功接入微信支付了。

需要注意的一點是:支付需要傳入的訂單號不能重復使用,比如,第一次支付取消了,然后去訂單頁面去重新支付,會提示 total_fee 是必須傳入選項,這時需要重新再生成一個新的訂單號才行。 


免責聲明!

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



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