uniapp 微信小程序 获取openid,手机号进行登录,配合后端

在这里插入图片描述

流程:登录注册功能,通过uni.getUserProfile获取wxcode,通过wxcode传给后端获取openid,sessionkey,unionid。
通过<u-button type="success" open-type="getPhoneNumber" @getphonenumber="decryptPhoneNumber">一键登录</u-button>,
传到后端这些参数:
'session_key': $this.openidData.sessionKey,
'encryptedData': e.detail.encryptedData,
'iv': e.detail.iv
获取手机号,
再将手机号,unionid,openid传到后端进行登录
<template>
	<view class="page">
		<!-- 自定义头部 navbar -->
		<u-navbar back-icon-name="arrow-left" title=" " :custom-back="navbarBack"
			:background="{ backgroundColor: 'rgba(0,0,0,0)' }" :border-bottom="false"
			:is-back="pageStatus != 'home'"></u-navbar>
		<!-- logo -->
		<view class="logo-wrap" v-if="pageStatus == 'home' || pageStatus == 'getWxRole'">
			<image class="logo"
				src="xxxxxxxxxxxxxx/static/login/login_logo.png"></image>
			<view class="app-name">欢迎登录</view>
			<view class="app-title">弘云艺术中心</view>
		</view>

		<!-- 默认登录页面显示 -->
		<view style="width: 100%;" v-if="pageStatus == 'home'">
			<view class="text-area" @click="loginByWx">手机号快捷登录</view>
		</view>

		<!-- 微信授权登录,获取用户信息 -->
		<view style="width: 100%;" v-if="pageStatus == 'getWxRole'">
			<view class="info">为提供优质服务,需要获取你的以下信息 :</view>
			<view class="public">
				<view class="public-dot"></view>
				<view class="public-text">你的公开信息(头像、昵称等)</view>
			</view>
			<view class="text-enter" @click="getWxLoginRole">授权进入</view>
		</view>

		<!-- 微信登录小程序,再授权获取用户信息之后 -->
		<view class="loginWx" v-if="pageStatus == 'loginByWx'">
			<view class="title">欢迎使用 弘云艺术中心</view>
			<view class="desc">立即登录享受优质服务</view>
			<view class="avatar">
				<image mode="aspectFill" :src="wxLoginUserInfo.userInfo.avatarUrl"></image>
			</view>
			<u-button type="success" open-type="getPhoneNumber" @getphonenumber="decryptPhoneNumber">一键登录</u-button>
		</view>

		<!-- 协议勾选 -->
		<view class="agree" v-if="pageStatus == 'home' || pageStatus == 'getWxRole' ">
			<view class="agree_img" @click="changeAgreeFlag" v-show="!agree_flag">
				<image src="xxxxxxxxxxx/static/mine/check.png">
				</image>
			</view>
			<view class="agree_img" @click="changeAgreeFlag" v-show="agree_flag">
				<image src="xxxxxxxxxxxxxxxxx/static/operate/checked.png">
				</image>
			</view>
			<view class="agree_text">
				登录代表您已同意
				<span>《用户服务协议》《隐私权政策》</span>
			</view>
		</view>
	</view>
</template>

<script>
	import FunUniappTheme from '@/theme.scss';
	export default {
		data() {
			return {
				// 页面状态,默认为 home
				// getWxRole:获取微信权限页,loginByWx:微信授权登录页
				// loginByCode:手机号+验证码登录页,loginByPwd:手机号+密码登录
				// forgetPwd:找回密码页面,resetPwd,重置密码页面
				pageStatus: 'home',
				// 协议是否勾选
				agree_flag: false,
				// 微信授权的用户信息
				wxLoginUserInfo: {},
				// openid
				openId: '',
				// 系统内用户信息
				userInfo: {},
				//openid
				openidData: {}
			};
		},
		onShow() {
		},
		onLoad(ops) {
			if (ops && ops.interceptcard && ops.interceptcard === "true") {
				uni.showToast({
					title: '购买商品,请先登录注册。',
					icon: 'none',
					duration: 4000,
				});
			}
			if (ops && ops.goods_id_detail) {
				console.log(ops.goods_id_detail, '二维码商品详情')
				uni.setStorageSync('goods_id_detail', ops.goods_id_detail)
			}
			console.log(FunUniappTheme);
		},
		onReady() {
		},
		methods: {
			// 勾选/取消用于协议
			changeAgreeFlag() {
				this.agree_flag = !this.agree_flag;
			},

			// 微信登录
			loginByWx() {
				if (!this.agree_flag) {
					uni.showToast({
						icon: 'none',
						title: '请先阅读并勾选协议'
					});
					return;
				}
				this.getUserInfoByWx(() => {
					this.getWxCode(code => {
						let $this = this;
						console.log('执行了吗', code)
						uni.request({
							url: "xxxxxxxxxxxxxx/mobile/index.php?m=user&c=indexapi&a=oauth2",
							method: 'POST',
							header: {
								'Content-Type': 'application/x-www-form-urlencoded'
							},
							data: {
								'wxcode': code,
								'parent_unionid': uni.getStorageSync('unionid')
							},
							success(res) {

								$this.openidData = res.data.data;
								console.log(res.data.data, 9999, $this.openidData);
								uni.setStorageSync('OPEN_ID', res.data.data.openid)
							}
						});
					});
				});
			},

			// 自定义navbar的返回方法
			navbarBack() {
				if (this.pageStatus == 'getWxRole' || this.pageStatus == 'loginByWx' ) {
					this.pageStatus = 'home';
				} else if (this.pageStatus == 'forgetPwd' || this.pageStatus == 'resetPwd') {
					this.pageStatus = 'loginByPwd';
				} else if (this.pageStatus == 'loginByPwd') {
					this.pageStatus = 'loginByCode';
				}
			},

			// 微信授权
			getWxLoginRole() {
				if (!this.agree_flag) {
					uni.showToast({
						icon: 'none',
						title: '请先阅读并勾选协议'
					});
					return;
				}
				this.getUserInfoByWx(() => {
					this.getWxCode(code => {
						let $this = this;
						console.log('执行了吗', code)
						uni.request({
							url: "xxxxxxxxxxxxxxx/mobile/index.php?m=user&c=indexapi&a=oauth2",
							method: 'POST',
							header: {
								'Content-Type': 'application/x-www-form-urlencoded'
							},
							data: {
								'wxcode': code,
								'parent_unionid': uni.getStorageSync('unionid')
							},
							success(res) {


								$this.openidData = res.data.data;
								console.log(res.data.data, 9999, $this.openidData);
								uni.setStorageSync('OPEN_ID', res.data.data.openid)
							}
						});
					});
				});
			},
			//个人中心
			userinfo() {
				uni.request({
					url: "xxxxxxxxxxxxxindex.php?m=user&c=indexapi&a=userinfo",
					method: 'POST',
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					data: {
						'open_id': uni.getStorageSync('OPEN_ID')
					},
					success(res) {
						console.log(res.data.data, '个人中心222');
						uni.setStorageSync('USER_ID', res.data.data.info.user_id)
						uni.setStorageSync('user_rank', res.data.data.info.user_rank)
						if (uni.getStorageSync('goods_id_detail')) {
							uni.reLaunch({
								url: '/pages-mall/pages/goods/detail?goods_id_detail=' + uni
									.getStorageSync('goods_id_detail')
							});
						} else {
							uni.reLaunch({
								url: '/pages/home/index'
							});
						}
					}
				});
			},

			// 基于uni的获取code方法
			getWxCode(callBack) {
				uni.login({
					provider: 'weixin',
					onlyAuthorize: true,
					success: loginRes => {
						console.log(loginRes, '获取信息')
						callBack(loginRes.code);
					},
					fail(e) {}
				});
			},

			// 获取openId
			getOpenId(code, callBack) {
				this.$u.api.getOpenId(code).then(res => {
					// uni.setStorageSync('OPEN_ID', res.openid);
					callBack(res);
				});
			},

			// 获取个人信息
			getUserInfoByWx(callBack) {
				let $this = this;
				uni.getUserProfile({
					desc: '获取你的昵称、头像',
					success: function(data) {
						console.log(data, '用户信息')
						uni.setStorageSync({
							key: 'APP_WX_USERINFO',
							data: data
						});
						$this.wxLoginUserInfo = data;
						$this.pageStatus = 'loginByWx';
						callBack();
					},
					fail: function(error) {}
				});
			},

			// 获取手机号回调
			decryptPhoneNumber(e) {
				let $this = this;
				console.log(e.detail, 9898)
				uni.request({
					url: "xxxxxxxxxxxxxxx/index.php?m=user&c=indexapi&a=decryptwechatdata",
					method: 'POST',
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					data: {
						'session_key': $this.openidData.sessionKey,
						'encryptedData': e.detail.encryptedData,
						'iv': e.detail.iv
					},
					success(res) {
						console.log(res.data, '手机号');
						uni.request({
							url: "xxxxxxxxxxxxxxxxxxxxxx/index.php?m=oauth&c=indexapi&a=bind_register",
							method: 'POST',
							header: {
								'Content-Type': 'application/x-www-form-urlencoded'
							},
							data: {
								'mobile': res.data.data.phoneNumber,
								'unionid': $this.openidData.unionid,
								'openid': $this.openidData.openid
							},
							success(res) {
								console.log(res.data, '登录成功');
								if (res.data.code === 0) {
									$this.userinfo()
									uni.setStorageSync('IS_LOGIN', true);
									uni.setStorageSync('fh_type',0)
									console.log(uni.getStorageSync('IS_LOGIN'), '成功了?', uni.getStorageSync(
										'USER_ID'))
								}
							}
						});
					}
				});
			},

			// 微信小程序手机号登录
			loginByOpenId() {
				const openid = uni.getStorageSync('OPEN_ID');
				this.$u.api.loginByOpenId(openid).then(res => {
					this.userInfo = res;
				});
			},
		}
	};
</script>

<style lang="scss" scoped>
	.page {
		padding: 0 40rpx;
		background-color: $app-theme-bg-color;
	}

	.logo-wrap {
		display: flex;
		// justify-content: center;
		padding-top: 100rpx;
		padding-bottom: 52rpx;
		flex-wrap: wrap;

		.logo {
			height: 168rpx;
			width: 166rpx;
			margin-left: 76rpx;
			margin-top: 50rpx;
		}

		.app-name {
			width: 100%;
			padding-top: 80rpx;
			margin-left: 78rpx;
			font-size: 38rpx;
			font-weight: 600;
			color: #333333;
			line-height: 52rpx;
		}

		.app-title {
			width: 100%;
			padding-top: 16rpx;
			margin-left: 78rpx;
			font-size: 38rpx;
			font-weight: 600;
			color: #333333;
			line-height: 52rpx;
		}
	}

	.text-area {
		width: 100%;
		height: 96rpx;
		background: #19be6b;
		font-weight: 400;
		border-radius: 56rpx;
		color: $app-theme-text-white-color;
		line-height: 16px;
		font-size: 32rpx;
		text-align: center;
		line-height: 96rpx;
		/* background: url(../../static/img/logo_newhope.png); */
	}

	.info {
		font-size: 28rpx;
		font-weight: 400;
		color: $app-theme-text-black-color;
		line-height: 28rpx;
		margin-top: 180rpx;
	}

	.public {
		display: flex;
		align-items: center;
		margin-top: 30rpx;

		.public-dot {
			width: 6rpx;
			height: 6rpx;
			background: #999999;
			margin-right: 10rpx;
		}

		.public-text {
			font-size: 24rpx;
			font-weight: 400;
			color: #8f92a1;
			line-height: 24rpx;
		}
	}

	.text-enter {
		width: 100%;
		margin-top: 50rpx;
		height: 96rpx;
		background: $app-theme-color;
		font-weight: 400;
		border-radius: 56rpx;
		color: #ffffff;
		line-height: 16px;
		font-size: 32rpx;
		text-align: center;
		line-height: 96rpx;
	}

	.head {
		margin-top: 70rpx;
		width: 100%;
		display: flex;
		justify-content: space-between;
	}

	.back {
		width: 40rpx;
		height: 40rpx;
	}
	.agree {
		position: fixed;
		left: 50%;
		transform: translate(-50%, 0);
		bottom: 66rpx;
		width: 100vw;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.agree_img image {
		width: 32rpx;
		height: 32rpx;
		display: flex;
		align-items: center;
	}

	.agree_text {
		margin-left: 8rpx;
		font-size: 24rpx;
		font-weight: 400;
		color: #8f92a1;
		line-height: 24rpx;
		display: flex;
		align-items: center;

		span {
			color: $app-theme-color;
		}
	}

	.loginWx {
		width: 100%;
		padding-top: 64rpx;

		.title {
			text-align: left;
			font-size: 22px;
			font-family: PingFang-SC-Regular, PingFang-SC;
			font-weight: 400;
			color: #171717;
			line-height: 30px;
			margin-bottom: 12rpx;
		}

		.desc {
			text-align: left;
			font-size: 14px;
			font-family: PingFang-SC-Regular, PingFang-SC;
			font-weight: 400;
			color: #8f92a1;
			line-height: 14px;
		}

		.avatar {
			width: 160rpx;
			height: 160rpx;
			overflow: hidden;
			border-radius: 50%;
			display: flex;
			align-items: center;
			justify-content: center;
			margin: 128rpx auto 160rpx auto;

			image {
				width: 100%;
				height: 100%;
			}
		}
	}
</style>
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在uniapp微信小程序获取手机号,可以按照以下步骤进行操作: 1. 用户获取code:用户需要调用login方法获取code。可以在onLoad()生命周期函数中调用getuserNew()方法来获取code。代码示例如下: ``` onLoad() { this.getuserNew(); // 获取openid }, methods: { // 获取code getuserNew() { uni.login({ provider: 'weixin', success: res => { console.log(res.code); } }); }, } ``` 2. 通过微信官方接口获取openId和session_key:使用uni.request()方法来向微信官方接口发送获取openId和session_key的请求。代码示例如下: ``` uni.request({ url: 'https://api.weixin.qq.com/sns/jscode2session', method: 'GET', data: { appid: 'wx9*******214e0', //你的小程序APPID secret: '33c4d17e4********71253', //你的小程序的secret js_code: res.code, //wx.login登录成功后的code grant_type: 'authorization_code', }, success: (cts) => { // 换取成功后,暂存这些数据留作后续操作 this.openId = cts.data.openid; //openid 用户唯一标识 this.session_key = cts.data.session_key; //session_key 会话密钥 console.log(cts); console.log(this.openId, this.session_key); } }); ``` 3. 获取手机号码权限并传递相关信息:在前端进行手机号授权,并将encryptedData、iv、sessionKey和openId这四个字段传递给后端后端通过用户信息授权获取openid,通过手机授权获取手机号码。具体细节可以根据你的需求和后端逻辑进行调整。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [uniapp 微信小程序 获取手机号/用户授权(最详细)](https://blog.csdn.net/qq_42957741/article/details/117086865)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *3* [uniapp微信小程序授权登录获取手机号](https://blog.csdn.net/mrqi122/article/details/129520675)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值