当前位置: 首页 > 工具软件 > node-openid > 使用案例 >

uniapp使用node获取微信openid

况野
2023-12-01

页面

登录按钮

<button width="70%" id="login" height="70upx" @click="loginProfile" v-else>登录</button>

 登录请求函数

	//用户登陆
			loginProfile() {
				console.log('登录函数')
				uni.getUserProfile({
					desc: '登录',
					success: async (res) => {
	                    console.log('第一次请求到的用户信息', this.user);
						this.user = JSON.parse(res.rawData)
						let address = this.user.address

						let code = await this.$http.getCode()
						console.log("@@@@@@@@@@@@@@@@@@获取开放ID")
						let data = await this.$http.getOpenId(code)
						const openID = data.data.openid
						getApp().globalData.openid = openID
						getApp().globalData.islogin = true
	                    console.log("@@@@@@@@@@@@@@@@@@")

						this.getposition()//获取地理位置
					},
					fail: (res) => {
						console.log(res)
					}
				});
			}

这里有一个百度地图获取当前位置的方法,需要自己申请钥匙

getposition() {
				uni.getLocation({
					success: (res) => {
						const url = 'https://api.map.baidu.com/reverse_geocoding/v3/';
						const ak = '自己获取自己获取自己获取自己获取自己获取自己获取ak';
						wx.request({
							url,
							data: {
								ak,
								location: `${res.latitude},${res.longitude}`,
								output: 'json',
							},
							success: (res) => {
								this.user.address = res.data.result.formatted_address
							}
						});
					}
				})
			},

封装的请求函数

const BASE_URL = 'http://127.0.0.1:3007'
export const http = {	
    getCode: function(data) { //wx.login,获取code
		return new Promise((resolve, reject) => {
			uni.login({
				provider: 'weixin',
				success: function(loginRes) {
					resolve(loginRes.code);
				}
			});
		})
	},
	getOpenId: function(data) {//获取openid
		return new Promise((resolve, reject) => {
			uni.request({
				header: {
					'content-type': 'application/x-www-form-urlencoded'
				}, //否则无法申请成功
				url: BASE_URL + '/my/loginByWx',
				data,
				method: 'POST',
				success: (res) => {
					resolve(res);
				}
			});
		})
	},
}

ndoe代码

本质上就是一个请求,纯前端也可以请求到,但是没必要,id还是要存在后台 。

const express = require('express')
const router = express.Router()
const multer = require('multer')//解析multipart/form-data 格式的表单数据。
const request = require("request");
const APP_ID = "自己的自己的自己的自己的"  //开发者的appid
const APP_SECRET = "自己获取自己获取自己获取自己获取"   //开发者的appsecret 登入小程序公共平台内查看


router.post("/loginByWx", (req, res) => {
    const code = req.body //拿到传过来的code
    console.log(Object.keys(code)[0])
    // 根据code进行获取openid
    let APP_URL = 'https://api.weixin.qq.com/sns/jscode2session'
    request(`${APP_URL}?appid=${APP_ID}&secret=${APP_SECRET}&js_code=${Object.keys(code)[0]}&grant_type=authorization_code`,
        (error, response, body) => {
            if (error) {
                console.log(error)
                return;
            }
            console.log('statusCode:', response && response.statusCode)
            console.log(body)
            res.send(body)
        })
})

页面完整代码

<template>
	<view class="content">
		<!-- 登录显示 -->
		<view class="content" v-if="islogin">
			<view class="mid">
				<image :src="user.avatarUrl" class="head"></image>
				<view class="right" v-if="islogin">
					<view class="name">
						{{user.nickName}}
					</view>
					<view class="address">
						{{user.address}}
					</view>
				</view>
			</view>

			<view class="ismaster" v-if="ismaster">
				<button width="40%" id="login" height="60upx" @click="changemaster">业主信息修改</button>
			</view>
			<view class="ismaster" v-else>
				您还不是业主,可以申请成为业主
				<button width="40%" id="login" height="60upx" @click="putmaster">业主申请</button>
			</view>
		</view>


		<!-- 没有登录 -->
		<button width="70%" id="login" height="70upx" @click="loginProfile" v-else>登录</button>


		<!-- 弹窗 无 -->
		<view class="popup" :style="{display:popshow}">
			<view class="window">
				<uni-icons color="white" type="plus" class="off" size="45" @click="popOff" :style="{display:popshow}">
				</uni-icons>
				<view class="tit">
					说明
				</view>
				<view class="content">
					这是说明这是说明这是说明这是说明这是说明这是说明这是说明

				</view>
			</view>
		</view>
	</view>
</template>
<script>
	// 引入nav方法
	export default {
		data() {
			return {
				islogin: false,
				ismaster: false,
				selecttab: 0,
				popshow: 'none',
				test: {
					"code": "",
					"userInfo": {
						"avatarUrl": "",
						"nickName": ""
					}
				},
				user: {
					avatarUrl: "../../static/user.png",
					nickName: "用户",
					position: "",
					address: "地址"
				},
			}
		},
		mounted() {
			let address = "";
			uni.authorize({
				scope: 'scope.userLocation',
				success: () => {
					this.getposition()
				}
			})
		},
		onShow() {
			if (this.ismaster ==false) {
				this.ismaster = getApp().globalData.ismaster
			}
		},
		methods: {
			// 请求例子
			async changegtab(value) {
				this.selecttab = value;
				if (value == 0) {
					// 第一部分
					let li = await this.$http.getTopic({
						userId: getApp().globalData.id
					})
					this.li = li.dataList;
				} else {
					// 第二部分
					let res = await this.$http.getlikelist({
						userId: getApp().globalData.id
					});
					console.log(res)
					this.li = res.dataList;
				}
			},


			putmaster() {
				uni.navigateTo({
					url: `../center/putmaster?`
				});
			},

			changemaster() {
				uni.navigateTo({
					url: `../center/baseInfo?`
				});
			},

			getposition() {
				uni.getLocation({
					success: (res) => {
						const url = 'https://api.map.baidu.com/reverse_geocoding/v3/';
						const ak = 'FsV3NczHY6QgEUf8eGPZkzi7wt5BO4mC';
						wx.request({
							url,
							data: {
								ak,
								location: `${res.latitude},${res.longitude}`,
								output: 'json',
							},
							success: (res) => {
								this.user.address = res.data.result.formatted_address
							}
						});
					}
				})
			},



			//用户登陆
			loginProfile() {
				console.log('登录函数')
				uni.getUserProfile({
					desc: '登录',
					success: async (res) => {
						let address = this.user.address
						let code = await this.$http.getCode()
						console.log('code:=', code);
						console.log("@@@@@@@@@@@@@@@@@@获取开放ID")
						let data = await this.$http.getOpenId(code)
						const openID = data.data.openid
						getApp().globalData.id = openID
						console.log("@@@@@@@@@@@@@@@@@@")
						getApp().globalData.islogin = true

						this.user = JSON.parse(res.rawData)
						this.user.address = address
						this.islogin = true //本页面是否登录
						console.log('user', this.user);
						this.getposition()

						let IsMaster = await this.$http.getIsMaster(openID)
						console.log('IsMaster:')
						console.log(IsMaster.data.data[0]["count (*)"])
						if (IsMaster.data.data[0]["count (*)"] === 1) {
							getApp().globalData.ismaster = true;
							this.ismaster = true
						}
						console.log(getApp().globalData.ismaster)
						console.log(this.ismaster)
					},
					fail: (res) => {
						console.log(res)
					}
				});
			}

		}

	}
</script>

<style lang="less">
	page {
		background-color: #f7f7f7;
		background-size: 100% 100%;
		background-repeat: no-repeat;
		background-attachment: fixed;
	}

	#login {
		width: 80%;
		padding: 0;
		background-color: #1989f9;
		color: #FFFFFF;
	}

	// 弹窗
	.popup {
		.window {
			display: flex;
			flex-direction: column;
			align-items: center;
			height: 600rpx;

			.tit {
				font-size: 40rpx;
				margin: 40rpx 0;
			}

			.content {

				margin: 40rpx 20rpx;
				font-style: 30rpx;
				line-height: 60rpx;
			}
		}
	}

	.content {
		padding: 20rpx;
		border-radius: 10rpx;

		.content {

			display: flex;
			flex-direction: column;

			.master {
				border-radius: 10rpx;
				height: 240rpx;
				display: flex;
				justify-content: space-around;
				flex-direction: column;
				background-color: #FFFFFF;
				padding: 30rpx;
				margin-top: 20rpx;
			}

			.mid {
				border-radius: 10rpx;
				background-color: #FFFFFF;
				padding: 30rpx;
				display: flex;

				.head {
					border-radius: 50%;
					width: 140rpx;
					height: 140rpx;
					background-color: rgb(100, 220, 170);
				}

				.right {
					padding-left: 30rpx;
					display: flex;
					color: white;
					justify-content: space-around;
					align-items: flex-start;
					flex-direction: column;

					.name {
						margin-right: 20rpx;
						font-size: 40rpx;
						color: #000000;
					}

					.address {
						margin-right: auto;
						color: #000000;
					}
				}

				.bottom {
					margin-top: 10rpx;
					display: flex;

					>view {
						background-color: #1989f9;
						padding: 10rpx 20rpx;
						font-size: 25rpx;
						margin-right: 20rpx;
						border-radius: 30rpx;
					}
				}
			}
		}
	}


	>.bottom {
		.li {
			margin-top: 20rpx;
			background-color: white;
			display: flex;
			box-sizing: border-box;
			border-radius: 10rpx;
			padding: 15rpx 20rpx;
			justify-content: space-between;

			.left {

				.text {
					overflow: hidden;
					width: 500rpx;
				}

				display: flex;
				flex-direction: column;
				justify-content: space-between;

				.bottom {
					margin-top: 10rpx;
					display: flex;
					font-size: 25rpx;
				}
			}

			.right {
				width: 120rpx;
				height: 100rpx;
			}
		}
	}
</style>

 类似资料: