公众号之授权登录

提示:本文介绍了点击头像进行公众号授权登录,如需用到微信的其他功能可以使用弹窗授权登录

目录

一、网页授权流程?

二、点击授权案例

1.APPID,重定向

2.读入数据

总结


提示:以下是本篇文章正文内容,下面案例可供参考

一、网页授权流程?

网页授权流程分为四步:

  1. 引导用户进入授权页面同意授权,获取code
  2. 通过 code 换取网页授权access_token(与基础支持中的access_token不同)
  3. 如果需要,开发者可以刷新网页授权access_token,避免过期
  4. 通过网页授权access_token和 openid 获取用户基本信息(支持 UnionID 机制)

二、点击授权案例

1.APPID,重定向

(原谅无法透露,大家按需写就ok)

 

2.读入数据

  • HTML部分   /pages/tabbar/mine
	<view class="Box flex_column_center" @click="info" v-if="dataList.avatar">
		<u--image width="180" height="180" shape="circle" :src="dataList.avatar">
				<view slot="error" style="font-size: 24rpx;color: #333;">加载失败</view>
		</u--image>
		<view class="text">{
   
   {dataList.nickname}}</view>
	</view>

	<view class="Box flex_column_center" @click="info" v-else>
		<u--image width="180" height="180" shape="circle" src="/static/logo.png">
				<view slot="error" style="font-size: 24rpx;color: #333;">加载失败</view>
		</u--image>
		<view class="text">微信昵称</view>
	</view>
  • JS部分
//不要忘记引入
import {APPID,redirect_uri} from "@/public/env.js"

methods:{

    info() {
		// 微信登陆
		let wx =`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${APPID}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`
		window.location.href = wx
	},
}

  • JS部分   /pages/tabbar/index
 //不要忘记引入 
   import {
		IMG_URL,
	    PARAMS
   } from '@/public/env';


// 注意:按项目需求截取,此处只截取了code
onLoad(options) {
		console.log(window.location.href);
		console.log('1112233', window.location.href?.split('=')[1]?.split('&')[0]);
		try {
		// 微信授权后执行
		    let token1 = uni.getStorageSync('token')
		    if (window.location.href?.split('?')[1]?.split('=')[0] == 'code' && !token1)                     
            {
				this.getOpenId(window.location.href?.split('=')[1]?.split('&')[0])
			}

		} catch (e) {
			//TODO handle the exception
			console.log('22222222', e);
		}

},


methods:{
     // 获取openid  并绑定
	getOpenId(code) {
		let that = this;
		let sendData = {
			code: code
		};
		that.apifun.unirequest(that.apifun.getOpenId, 'post', sendData, (res) =>             
        {
			console.log('000', res)
			if (res.code === 1) {
				let datas = res.data;
				this.getLogin(res.data)
			} else {
				that.apifun.toast(res.msg)
			}
		})
	},

	getLogin(box) {
		let that = this;
		let sendData = {
			openid: box.openid,
			avatar: box.headimgurl,
			nickname: box.nickname
		};
		that.apifun.unirequest(that.apifun.login, 'post', sendData, (res) => {
			console.log('121212', res)
			if (res.code === 1) {
				let datas = res.data;
                //存token,个人信息
				uni.setStorageSync("usermessage", res.data.userinfo)
				uni.setStorageSync("token", res.data.userinfo.token)
			} else {
				that.apifun.toast(res.msg)
			}
		})
	}
}


更多请参考文档:

网页授权


总结

以上就是今天要讲的内容啦,本文仅仅简单介绍了授权登录的使用,而微信其他的功能比如扫一扫,定位,客服等更多功能可以使用弹窗授权登录更为方便。

Guess you like

Origin blog.csdn.net/z_2183441353/article/details/127286615