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

总结

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

相关推荐
FungLeo26 分钟前
Taro 4 微信小程序:RootPortal CSS 变量继承问题与自建 PagePortal 解决方案
微信小程序·taro·css 变量
结网的兔子2 天前
【前端开发】Web端迁移至 uni-app 及鸿蒙扩展方案对比
前端·uni-app·harmonyos
2501_915909062 天前
iOS 应用反调试技详解术 检测调试器的原理与防护实践
android·ios·小程序·https·uni-app·iphone·webview
AI多Agent协作实战派2 天前
AI多Agent协作系统实战(二十八):顶栏统一战争——从1个页面异常到31个页面全量对齐
数据库·人工智能·uni-app
00后程序员张2 天前
iOS加固技术路线全面解析:Bitcode模式、源码模式与汇编模式对比及爱加密优势
android·汇编·ios·小程序·uni-app·cocoa·iphone
海纳百川·纳海川2 天前
租房行业数字化:换个思路解决“老问题”
大数据·微信小程序·小程序
2501_916008893 天前
iOS IPA文件反编译与打包操作方法,拆包分析防护和加固打包
android·macos·ios·小程序·uni-app·cocoa·iphone
name好难取诶3 天前
通过对云基座和离线基座的对比,帮助开发者理解如何在不同场景下选择合适的打包方案。 什么是“基座” 在 UniApp 中,基座(也称“ ...
开发语言·uni-app·php
2501_915921433 天前
iOS手游安全反外挂解决方案:基于Xcode的加固混淆特色详解
android·安全·ios·小程序·uni-app·iphone·xcode
2501_916007473 天前
iOS App分发教程 App Store、TestFlight 与 Ad Hoc 的配置与上传方法
android·ios·小程序·https·uni-app·iphone·webview