以下代码兼容微信H5、支付宝H5、微信小程序、支付宝小程序

1.微信H5和支付宝H5是跳转第三方链接获取code,获取到code跳转回来原来页面,再进行执行登录逻辑,登录成功后跳转页面需要用href跳转,否则url会带着code参数

微信H5参考文档:网页授权 | 微信开放文档

支付宝H5参考文档:小程序文档 - 支付宝文档中心

2.微信小程序先调用uni.login获取code,再触发按钮事件获取参数code、encryptedData、iv

参考文档:获取手机号 | 微信开放文档

3.支付宝小程序调用my.getAuthCode接口获取authCode

参考文档:小程序文档 - 支付宝文档中心

<template>
	<view class="login">
		<!-- #ifdef H5 -->
		<view class="auth-login-btn" @click="handleH5AuthLogin()">
			授权登录
		</view>
		<!-- #endif -->

		<!-- #ifdef MP-WEIXIN -->
		<button class="auth-login-btn" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">
			授权登录
		</button>
		<!-- #endif -->

		<!-- #ifdef MP-ALIPAY -->
		<button class="auth-login-btn" open-type="getAuthorize" scope="userInfo" @getAuthorize="onGetAuthorize">
			授权登录
		</button>
		<!-- #endif -->
	</view>
</template>

<script>
	export default {
		data() {
			return {
				code: '',
			}
		},
		onLoad() {
			//#ifdef H5
			if (this.isWechat()) {
				this.code = this.getUrlCode().code;
			}
			if (this.isAlipay()) {
				this.code = this.getQueryVariable('auth_code');
			}
			if (this.code) {
				uni.showLoading({
					title: "正在请求登录..."
				})
				this.h5Login()
			}
			//#endif
		},
		mounted() {},
		methods: {
			// 支付宝小程序登录
			async onGetAuthorize() {
				my.getAuthCode({
					scopes: 'auth_base',
					success: async (res) => {
						if (res.authCode) {
							let result = await this.$http('/accounts/wxlogin/wxopenid', {
								code: res.authCode,
							});
							if (result.code === 200) {
								// 登陆成功
							} else {
								this.toast(result.message)
							}
						} else {
							this.toast("获取code失败")
						}
					},
					fail: err => {
						console.log('my.getAuthCode 调用失败', err)
					}
				});
			},

			// 微信小程序登录
			async getPhoneNumber(e) {
				uni.login({
					success: async res => {
						if (res.errMsg === "login:ok") {
							if (e.detail.errMsg == "getPhoneNumber:ok") {
								let params = {
									code: e.detail.code,
									encryptedData: encodeURIComponent(e.detail.encryptedData),
									iv: encodeURIComponent(e.detail.iv),
									js_code: res.code,
								}
								let res = await this.$http('/accounts/wxlogin/weixinLogin', params)
								if (res.code === 200) {
									// 登陆成功
								} else {
									this.toast(res.message)
								}
							}
						} else {
							this.toast(res.errMsg)
						}
					}
				})
			},

			// H5登录
			handleH5AuthLogin() {
				uni.showModal({
					title: "提示",
					content: '确定进行要授权登录吗?',
					showCancel: true,
					success: (res) => {
						if (res.confirm) {
							if (this.isWechat()) {
								// 微信h5获取code登录
								this.getWxH5UrlCode()
							}

							if (this.isAlipay()) {
								// 支付宝h5获取code登录
								this.getAliH5UrlCode()
							}
						}
					}
				})
			},

			// H5登录
			async h5Login() {
				let res = await this.$http('/accounts/wxlogin/wxopenid', {
					code: this.code,
				});
				if (res.code === 200) {
					// 登录成功
					window.location.href = "/"
				} else if (res.code === 0) {
					uni.showModal({
						content: res.message,
						showCancel: false,
						success: async (result) => {
							// #ifdef H5
							if (this.isWechat()) { // 非微信环境下,不做处理
								setTimeout(function() {
									//安卓手机
									document.addEventListener("WeixinJSBridgeReady",
										function() {
											WeixinJSBridge.call("closeWindow");
										}, false);
									//ios手机
									WeixinJSBridge.call('closeWindow'); // 关闭微信页面窗口
								}, 100);
							}

							if (this.isAlipay()) { // 非支付宝环境下,不做处理
								setTimeout(function() {
									//安卓手机
									document.addEventListener("AlipayJSBridgeReady",
										function() {
											AlipayJSBridge.call("closeWindow");
										}, false);
									//ios手机
									AlipayJSBridge.call('closeWebview'); // 关闭支付宝页面窗口
								}, 100);
							}
							// #endif
						}
					})
				}
				uni.hideLoading()
			},

			getWxH5UrlCode() {
				uni.showLoading({
					title: "正在获取code"
				})
				// location.href.split('#')[0] + "#/pages/login/login";
				let loc_href = location.href.split('#')[0] + location.hash
				var redirect_uri = encodeURIComponent(loc_href);
				var appid = '你的appid'
				let url =
					`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect`;
				window.location.href = url;
			},

			getAliH5UrlCode() {
				uni.showLoading({
					title: "正在获取auth_code"
				})
				// location.href.split('#')[0] + "#/pages/login/login";
				let loc_href = location.href.split('#')[0] + location.hash
				var redirect_uri = loc_href;
				var app_id = '你的appid'

				let urls =
					`https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=${app_id}&scope=auth_user&redirect_uri=${redirect_uri}`;
				let aliUrl = `alipays://platformapi/startapp?appId=20000067&url=${encodeURIComponent(urls)}`
				window.location.href = aliUrl;
			},

			getUrlCode() {
				var url = location.search
				var theRequest = new Object()
				if (url.indexOf("?") != -1) {
					var str = url.substr(1)
					var strs = str.split("&");
					for (var i = 0; i < strs.length; i++) {
						theRequest[strs[i].split("=")[0]] = (strs[i].split("=")[1])
					}
				}
				return theRequest
			},

			// 截取支付宝H5code
			getQueryVariable(variable) {
				var query = window.location.search.substring(1);
				var vars = query.split("&");
				for (var i = 0; i < vars.length; i++) {
					var pair = vars[i].split("=");
					if (pair[0] == variable) {
						return pair[1];
					}
				}
				return (false);
			},
		}
	}
</script>

<style lang="scss" scoped>
	.login {
		.auth-login-btn {
			position: absolute;
			left: 50%;
			top: 50%;
			transform: translate(-50%, -50%);
			width: 80%;
			height: 90rpx;
			line-height: 90rpx;
			color: #FFFFFF;
			font-size: 28rpx;
			text-align: center;
			border-radius: 15rpx;
			background: #ff6a00;
		}

	}
</style>

更多推荐