可视化uniapp整合thinkphp6 EasyWeChat实现微信小程序支付

LK -
可视化uniapp整合thinkphp6 EasyWeChat实现微信小程序支付

可视化uniapp整合thinkphp6 EasyWeChat实现微信小程序、公众事情支付,调用tp6接口返回微信相关下单参数。

开源地址:https://gitee.com/diygw/diygw...
5$_]8$R5O8V7$%89B`N%B)1.jpg
image.png
image.png

//小程序支付相关方法
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("获取用户失败,请重试");
        }
    }

}
特别申明:本文内容来源网络,版权归原作者所有,如有侵权请立即与我们联系(cy198701067573@163.com),我们将及时处理。

php介绍

PHP即“超文本预处理器”,是一种通用开源脚本语言。PHP是在服务器端执行的脚本语言,与C语言类似,是常用的网站编程语言。PHP独特的语法混合了C、Java、Perl以及 PHP 自创的语法。利于学习,使用广泛,主要适用于Web开发领域。

Tags 标签

uniappphp小程序

扩展阅读

加个好友,技术交流

1628738909466805.jpg