可视化uniapp整合thinkphp6 EasyWeChat实现微信小程序、公众事情支付,调用tp6接口返回微信相关下单参数。
开源地址:https://gitee.com/diygw/diygw...
//小程序支付相关方法
var Pay = {
async pay(param){
let page = getApp().globalData.currentPage
let session = page.$session;
if(!session.getToken() || !session.getUser().openid){
//如果参数自带openid跳过验证
if(!param.openid){
page.showToast('请先登录')
return;
}
}
if(!param.total){
page.showToast('请配置价格参数total')
return;
}
let data = await page.$http.post(param.url||'/api/wepay/order',{
total:param.total,
body:param.body,
openid:param.openid||session.getUser().openid,
},{},'json')
if(data.code!=200){
page.showToast(data.msg)
return;
}
if(this[param.paytype]){
this[param.paytype](Object.assign(data,param))
}else{
page.showToast('请使用微信打开')
return;
}
},
//微信支付
weixin(params = {}) {
uni.requestPayment({
provider: 'wxpay',
timeStamp: params.data.timeStamp,// 支付签名时间戳,注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
nonceStr: params.data.nonceStr,// 支付签名随机串,不长于 32 位
package: params.data.package,// 统一支付接口返回的prepay_id参数值,提交格式如:prepay_id=\*\*\*)
signType: params.data.signType,// 签名方式,默认为'SHA1',使用新版支付需传入'MD5'
paySign: params.data.paySign,// 支付签名
success: res => {
if(typeof params.success=='function'){
params.success(res)
}else{
console.log('配置支付回调成功方法')
}
},
fail: res => {
if(typeof params.fail=='function'){
params.fail(res)
}else{
console.log('配置支付回调失败方法')
}
}
})
}
}
export default Pay
wepayApp = Factory::payment($paymentConfig);
}
/**
* 用户下单
* @return \think\response\Json
* @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
* @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
* @throws \GuzzleHttp\Exception\GuzzleException
* @throws \think\exception\DbException
*/
public function order(){
$userModel = DiyUserModel::where(['id'=>$this->request->userId])->find();
if(!$userModel){
return $this->error('请先登录'.$this->request->userId);
}
$user = $userModel->toArray();
if(empty($user['openid'])){
return $this->error('请先登录');
}
// 生成订单信息
$data = $this->request->param();
$data['orderNo'] = getOrderNo();
$data['status'] = 0;
$data['payStatus'] = 0;
$data['openid'] = $user['openid'];
$data['userId'] = $this->request->userId;
$model = new DiyOrderModel();
$data = $model->add($data);
$notify_url = url('api/wepay/notify')
->suffix('html')
->domain($this->request->domain())->build();
//调起微信支付
$payData = [
'body' => $data['body'],
'out_trade_no' =>$data['orderNo'] ,
'total_fee' =>(float)($data['total']*100),
'notify_url' => $notify_url, // 支付结果通知网址,如果不设置则会使用配置里的默认地址
'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
'openid' => $data['openid'],
];
$result = $this->wepayApp->order->unify($payData);
if ($result['return_code'] === 'SUCCESS') {
$jssdk = $this->wepayApp->jssdk;
$config = $jssdk->bridgeConfig($result['prepay_id'],false); // 返回数组
return $this->successData($config);
}else{
return $this->errorData($result);
}
}
/**
* 支付回调
* @return mixed
*/
public function notify(){
$response = $this->wepayApp->handlePaidNotify(function ($message,$error){
$order = DiyOrderModel::where(['order_no'=>$message['out_trade_no']])->find();
if (!$order || $order['status'] == '1') return true;
if ($message['return_code'] === 'SUCCESS') {
if ($message['result_code'] === 'SUCCESS') {
$order['status'] = '1';
} elseif ($message['result_code'] === 'FAIL') {
$order['status'] = '2';
}
} else {
return $error('通信失败,请稍后再通知我');
}
if ($order->save()){
return true;
}
return false;
});
$send = $response->send();
return $send;
}
}
wexcxApp = Factory::miniProgram($minConfig);
}
/**
* 获取用户登录信息
* @return \think\response\Json
* @throws \think\Exception
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
*/
public function login(){
$userInfo = json_decode($this->request->post('userInfo'),true);
$code = $this->request->post('code');
$auth = $this->wexcxApp->auth;
$opendata = $auth->session($code);
if(isset($opendata['openid'])){
$openid = $opendata['openid'];
$type = 'weixcx';
$model = new DiyUserModel();
//查找获取微信小程序用户
$user = $model->where('openid',$openid)->where('type',$type)->find();
$data['openid'] = $openid;
$data['type'] = $type;
$data['nickname'] = $userInfo['nickName'];
$data['avatar'] = $userInfo['avatarUrl'];
$data['country'] = $userInfo['country'];
$data['province'] = $userInfo['province'];
$data['gender'] = $userInfo['gender'];
if($user){
$userId = $user->toArray()['id'];
$data['id'] = $userId;
$user->edit($data);
}else{
$model = new DiyUserModel();
$model->add($data);
$userId = $data['id'];
}
$token = "bearer".JWTAuth::builder(['uid' => $userId]);
$opendata['token'] = $token;
$data = array_merge($data,$opendata);
return $this->successData($data);
}else{
return $this->errorData($opendata,'登录失败');
}
}
/**
* 服务端签名,获取操作权限
*/
public function getSignPackage(){
$url = $this->request->param('url');
try {
return $this->successData($this->wexcxApp->jssdk->buildConfig([
'checkJsApi',
'onMenuShareTimeline',
'onMenuShareAppMessage',
'onMenuShareQQ',
'onMenuShareWeibo',
'hideMenuItems',
'showMenuItems',
'hideAllNonBaseMenuItem',
'showAllNonBaseMenuItem',
'translateVoice',
'startRecord',
'stopRecord',
'onRecordEnd',
'playVoice',
'pauseVoice',
'stopVoice',
'uploadVoice',
'downloadVoice',
'chooseImage',
'previewImage',
'uploadImage',
'downloadImage',
'getNetworkType',
'openLocation',
'getLocation',
'hideOptionMenu',
'showOptionMenu',
'closeWindow',
'scanQRCode',
'chooseWXPay',
'openProductSpecificView',
'addCard',
'chooseCard',
'openCard'
],false,false,false,['wx-open-launch-weapp'],'https://php.diygw.com/pay/index.html'));
}catch (Throwable | Exception $e){
return $this->error("获取用户失败,请重试");
}
}
}