uni-app微信登录(公众号)

uni-app微信登录(公众号)

简述微信公众号与uniapp的登录鉴权

uniapp集成了app与小程序的登录,确没有h5版本的微信登录,这里简要阐述微信公众号时候的登录鉴权,废话不多话直接步入主体

第一步uniapp端

首先请保证在微信开发平台上申请过微信公众号,并拥有了appid和AppSecret参数,为保证用户体验,请在需要登录的时候单独跳转一个第三方页面来做微信登录

<template>
	<view></view>
</template>

<script>
	export default {
		data() {
			return {
				code: '',
				appid: "********",
			}
		},
		onLoad() {
			this.wechatLogin();
		},
		methods: {
			GetUrlParam(paraName) {
			//微信回调 回回调当前请求的域名 所以需要从链接后获取参数
				var url = document.location.toString();
				var arrObj = url.split("?");
				if (arrObj.length > 1) {
					var arrPara = arrObj[1].split("&");
					var arr;
					for (var i = 0; i < arrPara.length; i++) {
						arr = arrPara[i].split("=");
						if (arr != null && arr[0] == paraName) {
							return arr[1];
						}
					}
					return "";
				} else {
					return "";
				}
			},
			wechatLogin() { 
			  
				this.code = this.GetUrlParam('code'); 
				this.sid = window.localStorage.getItem("sid");
				this.pid = window.localStorage.getItem("pid");
				if (!this.code) {
					 //第一步获取微信code 1个code只允许使用一次
					 // url 是当前链接 encodeURIComponent字符串作为 URI 组件进行编码 来做可识别的回调链接
					let uri = encodeURIComponent(window.location.href);
					window.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + this.appid +
						"&redirect_uri=" +
						uri + "&response_type=code&scope=snsapi_userinfo&state=state&wechat_redirect&connect_redirect=1#wechat_redirect";
				} else {
					this.$Request.post('*************', { //获取code后 带给后台做登录
						code: this.code,
					}).then(res => {
					window.location.href = '*********';//成功后 因为uniapp的路由有#号 微信回调参数也在#后面 所以这里重新请求当前域名 
						
					})

				}
			}
		},
	}
</script>

<style>
</style>

第二步 后端 这里采用php

通过code获取微信的用户信息

    public function get_user_info($code)

    {
        $site = config('app'); //作者把配置写入了config 所以从配置中 读取 appid 和appsecret
        
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $site['appid'] . '&secret=' . $site['appsecret'] . '&code=' . $code . '&grant_type=authorization_code';
		//获取accesstoken 和用户的openid 
        $res = $this->Get($url);

        $data = json_decode($res, true);

        $url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $data['access_token'] . '&openid=' . $data['openid'] . '&lang=zh_CN';
		//通过openid 获取用户信息 然后进行DB操作
        $res = $this->Get($url);

        return json_decode($res, true);

    }

结语

代码并不多,但由于微信文档的简陋以及调试需要设置js安全域名和发布到线上进行调试,所以作者也是摸索了许久做出了简陋的总结。希望后面的朋友少走弯路,第一次写文章写的不好,请大家见谅。

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值