uni-app微信小程序支付流程

最近在用 uni-app 开发微信小程序,涉及到微信支付功能的开发,在此记录一下。

微信支付流程

首先,要开发微信支付功能,得知道要知道微信支付的整个支付流程,话不多说直接上图: 具体流程:

  • 进入微信小程序,对商品进行下单
  • 进入到支付页面,点击支付,先判断当前用户有没有 openId ,可以通过后端接口,查询当前用户信息判断
  • 一般如果首次注册登录,进行过微信注册的用户都是有 openId 的,如果没有 openId ,则需要进入微信授权页面
  • 进入授权页面,绑定手机号,授权成功后,返回支付页面
  • 点击支付,此时用户信息中存在 openId ,后端需要 openId 获取微信支付所需的参数
  • 调用后端接口查询微信支付所需要的参数,使用 uni.requestPayment 调用微信小程序支付功能
  • 输入密码,支付成功,返回支付结果,发微信消息提醒,进入订单详情页面

代码实现

  1. 断当前用户是否存在 openId
dart 复制代码
// 获取用户信息
async queryUserInfo {
    await this.$http.get(url).then(r => {
        const { openId } = r; // 获取openId
        // 判断是否存在
        if (!openId) {
            this.$router.push(url); // 不存在进入授权页面
        } else {
            this.queryPayParams(); // 存在直接查询微信支付所需要的参数
        }
    }).catch(err => {
        console.log(err);
    });
};
  1. 进入授权页面
ini 复制代码
// 微信授权
authLogin(phone) { // phone为调接口获取
    // 判断是否是微信小程序
    let isWeChat = false
    let ua = window.navigator.userAgent.toLowerCase();
    if (ua.match(/micromessenger/i) == 'micromessenger') {
        isWeChat = true;
    } else {
        isWeChat = false;
    };
    if (isWeChat) {
        const href = window.location.href;
        // weixinAppId为当前小程序的AppId
        window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${weixinAppId}&redirect_uri=${href}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`;
    } else {
        this.toast('当前平台不支持授权登录');
    };
    let authApi;
    plus.oauth.getServices(function(services) {
        let weixinService;
        if (services && services.length) {
            for (let i = 0, len = services.length; i < len; i++) {
                if (services[i].id === 'weixin') {
                    weixinService = services[i];
                    break;
                }
            };
            if (!weixinService) {
                this.$mHelper.toast('没有微信登录授权服务');
                return;
            };
            let group = 'tinyShopIos';
            if (uni.getSystemInfoSync().platform === 'android') {
                group = 'tinyShopAndroid';
            };
            weixinService.authorize(e => {
                authApi = `${thirdPartyWechatOpenPlatform}?code=${e.code ||''}&group=${group}&promo_code=${_this.promoCodeParams.promo_code || ''}`;
                this.thirdPartyAuthLogin(authApi);
                },
                function(err) {
                    // 授权失败 error
                    this.toast(err.message.split(',')[0]);
                }
            );
         }
      }
    };
    uni.login({
        provider: 'weixin',
        success: function(loginRes) {
            uni.getUserInfo({
                provider: 'weixin',
                success: function(infoRes) {
                    let params = this.promoCodeParams;
                    authApi = mpWechatLogin; // 后端提供接口
                    params = {
                        ...infoRes,
                        ...params
                    };
                    params.code = loginRes.code;
                    params.mobile = phone;
                    this.thirdPartyAuthLogin(authApi, params);
                },
                fail: function() {
                    this.btnLoading = false;
                }
            });
        },
        fail: function() {
            this.btnLoading = false;
            this.$mHelper.log('暂不支持小程序登录');
        }
    });
};
thirdPartyAuthLogin(authApi, params = {}) {
    const _this = this;
    _this.$http.post(authApi, params).then(async r => {
        _this.btnLoading = false;
        _this.toast('已为您授权登录');
        _this.$router.push(url); // 返回支付页面
    }).catch(() => {
        _this.btnLoading = false;
    });
};
  1. 返回支付页面,获取支付参数,调用 uni.requestPayment
csharp 复制代码
// 获取支付参数
async getPayParams() {
    await this.$http.get(wechatappletpayparams, { // 后端提供接口
        type: 1,
        orderCode: this.orderCode,
    }).then(r => {
        const params = r.data
        let _this = this
        uni.requestPayment({
            provider: 'wxpay', // 微信支付
            timeStamp: params.time_stamp,
            nonceStr: params.nonce_str,
            package: params.package_,
            signType: params.sign_type,
            paySign: params.pay_sign,
            success: function () {
                _this.toast('支付成功');
                _this.$router.push(url); // 跳转订单详情
            },
            fail: function (err) {
                console.log('err', err);
                _this.toast('支付已取消');
            }
          });
        }).catch(() => {});
}

总结

支付功能大致就是这样实现的,具体细节还需要跟后端沟通,希望能帮到大家!

相关推荐
qq_424409194 小时前
uniapp的app项目,添加全局弹窗
uni-app
七夜zippoe6 小时前
uniapp跳转页面时如何带对象参数
uni-app·携带参数
racerun7 小时前
UniApp中的pages.json 和 tabBar
uni-app·json
铲子Zzz7 小时前
Java使用接口AES进行加密+微信小程序接收解密
java·开发语言·微信小程序
春哥的研究所14 小时前
AI人工智能名片小程序源码系统,名片小程序+分销商城+AI客服,包含完整搭建教程
人工智能·微信小程序·小程序
Bruce_Json16 小时前
微信小程序ts+sassjlin-ui
微信小程序·小程序·sass
来碗盐焗星球18 小时前
记一次微信小程序AI开发的血泪史
前端·微信小程序
The_era_achievs_hero1 天前
微信小程序71~80
微信小程序·小程序
米粒宝的爸爸1 天前
uniapp在app端,在导航栏设置自定义按钮
uni-app
dssxyz1 天前
uniapp打包微信小程序主包过大问题_uniapp 微信小程序时主包太大和vendor.js过大
javascript·微信小程序·uni-app