共计 6198 个字符,预计需要花费 16 分钟才能阅读完成。
可视化 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
<?php
namespace app\api\controller;
use app\BaseController;
use app\common\model\DiyOrderModel;
use app\common\model\DiyUserModel;
use EasyWeChat\Factory;
use think\App;
use think\facade\Log;
/*
* 领取
*/
class WepayController extends BaseController
{
// 判断是否全副不须要登录
public $notNeedLoginAll = false;
public $isModel = false;
// 判断不须要登录的办法
public $notNeedLogin = ['notify'];
public $wepayApp;
/**
* 构造方法
* @access public
* @param App $app 利用对象
*/
public function __construct(App $app)
{parent::__construct($app);
$paymentConfig = config('wechat.payment');
$this->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;
}
}
<?php
namespace app\api\controller;
use app\BaseController;
use app\common\model\DiyUserModel;
use EasyWeChat\Factory;
use Overtrue\Socialite\AuthorizeFailedException;
use thans\jwt\facade\JWTAuth;
use think\App;
/*
* 微信小程序
*/
class WexcxController extends BaseController
{
// 判断是否全副不须要登录
public $notNeedLoginAll = true;
public $isModel = false;
// 判断不须要登录的办法
public $notNeedLogin = [];
public $wexcxApp = null;
/**
* 构造方法
* @access public
* @param App $app 利用对象
*/
public function __construct(App $app)
{parent::__construct($app);
$minConfig = config('wechat.mini_program');
$this->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("获取用户失败,请重试");
}
}
}
正文完