thinkPHP5 +easywechat 微信支付
阿新 • • 發佈:2019-02-07
1、composer下載thinkphp5
composer create-project topthink/think [你的目錄名] --prefer-dist
2、composer下載easywechat
composer require hooklife/thinkphp5-wechat
3、配置好小程式的appid和appsercret,還有證書
第一步:
獲取使用者的openid
小程式程式碼
//app.js
App({
onLaunch: function() {
wx.login({
success: function (res) {
if (res.code) {
//發起網路請求獲得openid
wx.request({
url: 'https://xxxxxxxx/index/on_login/index',
data: {
code: res.code
},
success:function(res){
//console.log(res.data.openid)
that.globalData.openId = res.data.openid
},
fail:function(e){
console .log(e);
}
})
} else {
console.log('獲取使用者登入態失敗!' + res.errMsg)
}
}
});
}
})
php 程式碼
public function index(){
$code = input('code');
$appid = 'xxx';
$appsecret = 'xxxx';
//初始化
$ch = curl_init();
//設定選項,包括URL
curl_setopt($ch, CURLOPT_URL, "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$appsecret}&js_code={$code}&grant_type=authorization_code" );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
//執行並獲取HTML文件內容
$output = curl_exec($ch);
//釋放curl控制代碼
curl_close($ch);
//列印獲得的資料
return $output;
}
第二步:
發起微信支付
小程式程式碼
payMent:function(e){
var that = this;
wx.request({
url: 'https://xxx/index/index/index.html',
data:{
'openid': app.globalData.openId,
'total_money':1
},
success:function(res){
wx.requestPayment({
'timeStamp': res.data.timeStamp+'',
'nonceStr': res.data.nonceStr,
'package': res.data.package,
'signType': 'MD5',
'paySign': res.data.paySign,
'success': function (ref) {
console.log(ref);
wx.showToast({
title: '支付成功',
icon: 'success',
duration: 2000
})
},
'fail': function (ref) {
console.log(ref);
wx.showToast({
title: '支付失敗',
icon: 'fail',
duration: 2000
})
}
})
}
})
},
php程式碼
easywechat支付
public function index()
{
$app = Wechat::app();
$payment = $app->payment;
$openid = input('openid');
$total_money = input('total_money/d');
$attributes = [
'trade_type' => 'JSAPI', // JSAPI,NATIVE,APP...
'body' => 'iPad mini 16G 白色',
'detail' => 'iPad mini 16G 白色',
'out_trade_no' => time() . rand(1000, 9999),
'total_fee' => $total_money, // 單位:分
'notify_url' => 'https://xxx/index/index/order_notify.html', // 支付結果通知網址,如果不設定則會使用配置裡的預設地址
'openid' => $openid, // trade_type=JSAPI,此引數必傳,使用者在商戶appid下的唯一標識,
];
$order = new Order($attributes);
$result = $payment->prepare($order);
$config = array();
if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
$prepayId = $result->prepay_id;
$config = $payment->configForJSSDKPayment($prepayId);
}
$arr = array(
'timeStamp'=>$config['timestamp'],
'nonceStr'=>$config['nonceStr'],
'package'=>$config['package'],
'signType'=>'MD5',
'paySign'=>$config['paySign'],
);
return json_encode($arr);
}
public function order_notify(){
$app = Wechat::app();
$response = $app->payment->handleNotify(function($notify, $successful){
// 你的邏輯
return true; // 或者錯誤訊息
});
$response->send();
}