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();
}