公众号微信授权登陆,支付

1、安装微信SDK :npm install weixin-js-sdk

2、页面中引入sdk,封装微信授权模块代码,方便之后的支付接口调用

import wx from 'weixin-js-sdk'
import { geConfigJs } from '@api/home' // geConfigJs  获取授权数据接口
export default {
    /* 初始化wxjsdk各种接口 */
    init(apiList = []) {
        //需要使用的api列表
        return new Promise((resolve, reject) => {
			//initLink 在router.js存入vuex,用来验证URL
            geConfigJs(encodeURIComponent(store.state.initLink)).then(res => {
                    wx.config({
                        debug: false, // 开启调试模式,
                        appId: res.data.appId, // 必填,公众号的唯一标识
                        timestamp: res.data.timestamp, // 必填,生成签名的时间戳
                        nonceStr: res.data.nonceStr, // 必填,生成签名的随机串
                        signature: res.data.signature, // 必填,签名
                        jsApiList: apiList
                    })
                    wx.ready(res => {
                        // 微信SDK准备就绪后执行的回调。
                        resolve(wx, res)
                    })
                
            })
        })
    },
}

3、微信登录:

	// 01 触发登录事件,跳转微信授权,授权成功后会返回Host变量定义的URL地址
	export default {
		methods: {
			//微信登录
			wx_login(){
				let appId= this.$store.state.appId;
				let params = this.$route.query.id ? this.$route.query.id : 0;
				let Host = encodeURI('http://' + window.location.host + '/index.html');
				window.location.href =`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${Host}&response_type=code&scope=snsapi_userinfo&state=${params}&connect_redirect=1#wechat_redirect`
			},
		},
	}
// 02 router.js 拦截 从微信授权返回的数据
router.beforeEach(async (to, from, next) => {
	//该项目用户没有登录也可以正常访问,当接口返回-1后提示用户登录,并跳转登录页面。
	//没有登录,此时还没有token
	if (!localStorage.getItem("token")) {
		var code = to.query.code;
		var state = to.query.state ? to.query.state : 0;
		if (code) {
			let arr = state.split("-")
			let data = {
				"code": code,
				"fid": Number(state),
			}
			// 获取token,用户信息
			getToken(data).then(res => {
				if (res.errCode == 0) {
					localStorage.setItem('token', res.data.token)
					router.push('home')
				}
				next()
			})
		} else {
			next()
		}
	} else {
		let path = to.fullPath.slice(1) // 去除'/'
		if (!sessionStorage.getItem('initLink')) {
			// 解决ios微信下,分享签名不成功的问题,将第一次的进入的url缓存起来。
			sessionStorage.setItem('initLink', document.URL)
		}
		let url
		if (/ipad|iphone|mac/i.test(navigator.userAgent)) {
			//  苹果手机
			url = sessionStorage.getItem('initLink')
		} else {
			url = location.origin + process.env.BASE_URL + '/' + path
		}
		store.commit('setInitLink', url);//url存入vuex,支付的时候需要先验证URL
		next();
	}
});

4、微信支付

// 1、获取微信授权,引入封装好的模块
import wechatUtil from '@utils/wechatUtil.js'

// 2、支付,orderId支付id
to_pay(orderId){
		var _this = this;
		this.$toast.loading({ duration: 0, forbidClick: true, mask: false, message: '正在拉起微信支付', });
		//支付
		getWxPay(orderId).then(e => {
			var outNo = e.data.outNo;//outNo 是支付成功之后,需要拿该数据去轮询查看订单状态
			wechatUtil.init(['chooseWXPay']).then((wx, payres) => {
				wx.ready(function() {
					_this.$toast.clear();
					wx.chooseWXPay({
						timestamp: e.data.timeStamp, // 支付签名时间戳
						nonceStr: e.data.nonceStr, // 支付签名随机串,不长于32 位
						package: e.data.package, // 统一支付接口返回的prepay_id参数值,提交格式如:prepay_id=***)
						signType: "MD5", // 签名方式,默认为'SHA1',使用新版支付需传入'MD5'
						paySign: e.data.paySign, // 支付签名
						success: function(res) {
							//支付成功查询
							var num = 0;
							var auth_timetimer = setInterval(() => {
								num ++;
								getWxPayOrderQuery(outNo).then(val => {
									if(num == 5){
										clearInterval(auth_timetimer);
										_this.$toast.fail('支付失败,请重新支付');
									}else if(val.data){
										//val.data返回true,支付成功
										clearInterval(auth_timetimer);
										_this.$toast.success('支付完成!')
									}
								}).catch(e=>{
									console.log('接口报错,直接结束轮询')
									clearInterval(auth_timetimer);
								})
							}, 1500);
						},
						cancel: function(res) {}
					});
				});
				wx.error(function(res) {
					_this.$toast.clear();
				});
		
			})
		}).catch(e=>{
			_this.$toast.clear();
		})
	},

猜你喜欢

转载自blog.csdn.net/qq_40745143/article/details/106395964