微信小程式支付 後端PHP
阿新 • • 發佈:2019-01-02
看文章 掃一掃 領紅包哦
前端:比較簡單,在對應的支付事件上進行網路請求就好:
後端程式碼:view_moneysure:function(){ var code = this.data.code; console.log('code是' +code) wx.request({ url: 'https://...com/pay.php',//這個連結是後端寫的 header: { 'Content-Type': 'application/x-www-form-urlencoded' }, data: { code: code, }, method: 'POST', success: function (response) { console.log( response.data); // 發起支付 wx.requestPayment({ 'appId': response.data.appId, 'timeStamp': response.data.timeStamp, 'nonceStr': response.data.nonceStr, 'package': response.data.package, 'signType': 'MD5', 'paySign': response.data.paySign, 'success': function (res) { wx.showToast({ title: '支付成功' }); console.log(res); }, 'fail': function (res) { console.log(res) } }); }, fail: function (res) { console.log(res) } }) },
1. pay.php //小程式請求的後端地址
<?php /** * Created by PhpStorm. * User: UFO * Date: 17/7/18 * Time: 下午5:31 */ require_once ('WxPay.Api.php'); class WXPay { function index() { // 初始化值物件 $input = new WxPayUnifiedOrder(); // 文件提及的引數規範:商家名稱-銷售商品類目 $input->SetBody("testceshi"); // 訂單號應該是由小程式端傳給服務端的,在使用者下單時即生成,demo中取值是一個生成的時間戳 $input->SetOut_trade_no(time().''); // 費用應該是由小程式端傳給服務端的,在使用者下單時告知服務端應付金額,demo中取值是1,即1分錢 $input->SetTotal_fee("1"); $input->SetNotify_url("https://...com/notify.php");//需要自己寫的notify.php $input->SetTrade_type("JSAPI"); // 由小程式端傳給後端或者後端自己獲取,寫自己獲取到的, $input->SetOpenid('UdhncondJcnkJnjknkcssdcAbckn'); //$input->SetOpenid($this->getSession()->openid); // 向微信統一下單,並返回order,它是一個array陣列 $order = WxPayApi::unifiedOrder($input); // json化返回給小程式端 header("Content-Type: application/json"); echo $this->getJsApiParameters($order); } private function getJsApiParameters($UnifiedOrderResult) { //判斷是否統一下單返回了prepay_id if(!array_key_exists("appid", $UnifiedOrderResult) || !array_key_exists("prepay_id", $UnifiedOrderResult) || $UnifiedOrderResult['prepay_id'] == "") { throw new WxPayException("引數錯誤"); } $jsapi = new WxPayJsApiPay(); $jsapi->SetAppid($UnifiedOrderResult["appid"]); $timeStamp = time(); $jsapi->SetTimeStamp("$timeStamp"); $jsapi->SetNonceStr(WxPayApi::getNonceStr()); $jsapi->SetPackage("prepay_id=" . $UnifiedOrderResult['prepay_id']); $jsapi->SetSignType("MD5"); $jsapi->SetPaySign($jsapi->MakeSign()); $parameters = json_encode($jsapi->GetValues()); return $parameters; } //這裡是伺服器端獲取openid的函式 // private function getSession() { // $code = $this->input->post('code'); // $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.WxPayConfig::APPID.'&secret='.WxPayConfig::APPSECRET.'&js_code='.$code.'&grant_type=authorization_code'; // $response = json_decode(file_get_contents($url)); // return $response; // } } $WxPay = new WXPay(); $WxPay->index();
2. 微信SDK 下載連結:https://pay.weixin.qq.com/wiki/doc/api/download/WxpayAPI_php_v3.zip
解壓在lib資料夾下可以看到:
放到服務端可訪問的目錄下。
在WxPayConfig.php裡面配置賬號資訊:
class WxPayConfig { //=======【基本資訊設定】===================================== // /** * TODO: 修改這裡配置為您自己申請的商戶資訊 * 微信公眾號資訊配置 * * APPID:繫結支付的APPID(必須配置,開戶郵件中可檢視) * * MCHID:商戶號(必須配置,開戶郵件中可檢視) * * KEY:商戶支付金鑰,參考開戶郵件設定(必須配置,登入商戶平臺自行設定) * 設定地址:https://pay.weixin.qq.com/index.php/account/api_cert * * APPSECRET:公眾帳號secert(僅JSAPI支付的時候需要配置, 登入公眾平臺,進入開發者中心可設定), * 獲取地址:https://mp.weixin.qq.com/advanced/advanced?action=dev&t=advanced/dev&token=2005451881&lang=zh_CN * @var string */ const APPID = 'wx123456789...';//這裡填上自己的對應資訊 const MCHID = '14151666888'; const KEY = '11223344556677889900'; const APPSECRET = '828bfsdibfsiubfikdbfik'; const NOTIFY_URL='https://...com/notify.php';
注:
期間遇到一個簽名錯誤,一直不好,使用微信支付介面簽名校驗工具校驗也沒有錯,像網上說的漏寫錯寫引數都查了,就是一直返回<return_code><![CDATA[FAIL]]></return_code>
<return_msg><![CDATA[簽名錯誤]]></return_msg>
這樣的資訊,最後解決辦法是:重置了KEY (商戶支付金鑰),重置的和之前的一模一樣,但竟然就可以了...
問題主要都是報簽名錯誤,仔細檢查就好,比如XML格式不對,MD5加密後的位數,字典排序沒排好,缺少引數等...
3.最後附上notify.php
<?php
/**
* Created by PhpStorm.
* User: UFO
* Date: 17/7/13
* Time: 下午6:42
*/
require_once ('WxPay.Api.php');
require_once ('WxPay.Notify.php');
class PayNotifyCallBack extends WxPayNotify
{
//查詢訂單
public function Queryorder($transaction_id)
{
$input = new WxPayOrderQuery();
$input->SetTransaction_id($transaction_id);
$result = WxPayApi::orderQuery($input);
if(array_key_exists("return_code", $result)
&& array_key_exists("result_code", $result)
&& $result["return_code"] == "SUCCESS"
&& $result["result_code"] == "SUCCESS")
{
return true;
}
return false;
}
//重寫回調處理函式
public function NotifyProcess($data, &$msg)
{
$notfiyOutput = array();
if(!array_key_exists("transaction_id", $data)){
$msg = "輸入引數不正確";
return false;
}
//查詢訂單,判斷訂單真實性
if(!$this->Queryorder($data["transaction_id"])){
$msg = "訂單查詢失敗";
return false;
}
return true;
}
}
$notify = new PayNotifyCallBack();
$notify->Handle(false);
歡迎留言交流指正!