微信授权 登录


一、微信公众号授权登录

1.跳转微信授权页面

toWXAuth(){
  	var uri = window.location.href;  当前页面
  	//去除当前页面链接参数
  	var index = uri.indexOf('?');
	if(index != '-1'){
		uri = uri.substring(0, index);
	}
  	let appid = '公众号APPId';
  	//uri 授权成功后,跳转页面
  	let redirect_uri = encodeURIComponent(uri);
  	var path = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=3#wechat_redirect`
  	window.location.href = path;
  }

2.授权成功获取code去获取用户信息(openId等信息)

//this.userInfo用户信息  optObj页面传参对象
if(!this.userInfo && optObj.code){
	this.wxCode = optObj.code;
	_self.authorization();
}
async authorization(){
	// wxCode 授权后取到的code,走后端接口取到用户信息
	var res = await this.$store.dispatch('getUserInfo', this.wxCode);
		if(!res.success){
			//授权失败,重新唤起微信授权
			this.$commonly.toWXAuth();
			return;
		}
		//如有需要调用微信的api还需要进行签名signature()
		// await _self.signature();
	}

3.签名

// 微信sdk config配置
async signature(url){
	var _self = this;
	//签名页的url
	var url  = this.signUrl = url ? url : location.href;
	// _self.$store.commit('install/updateAuthorizUrl', url);
	const success = function(res) {
		var result = res.result;
		if(res.success){
			jweixin.config({
				debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
				appId: result.appId, // 必填,公众号的唯一标识
				timestamp: result.timestamp, // 必填,生成签名的时间戳
				nonceStr:result. nonceStr, // 必填,生成签名的随机串
				signature: result.signature,// 必填,签名
				jsApiList: ['getLocation', 'startRecord', 'stopRecord', 'translateVoice'] // 必填,需要使用的JS接口列表
			});
			//完成签名后的回调函数
			jweixin.ready(function(){
				_self.getLocation();

			})
			// 通过error接口处理失败验证
			jweixin.error(function(res){
				console.log('-----------jweixin 失败验证 ------------------');
			})
		}
	}
	var sData = {
		opt: {
			data: {
				url: url
			},
			url: 'wechat/getWxConfig',
			method: 'GET'
		},
		success: success
	};
	await _self.$store.dispatch('request', sData);
}

签名成功后调用相关api或方法

// 获取定位
getLocation(){
	var _self = this;
	_self.$commonly.showLoading();
	jweixin.getLocation({  
		type: 'gcj02',
		success: function (res) {
			//初始化地图
			_self.initMap(res.longitude, res.latitude);
			//获取当前定位地址信息
			_self.getAdressInfo(res.latitude, res.longitude);
			_self.$commonly.hideLoading();
		},
		//调用api失败重新进行签名
		fail:async function (res) {
			await _self.signature();
			_self.getLocation();
		}
	});  
},
//获取定位信息
getAdressInfo(latitude, longitude){
	var _self = this;
	vm.$jsonp(
		'https://apis.map.qq.com/ws/geocoder/v1/',
		{
			key: _self.key,
			callbackName: "getJsonData",
			output: 'jsonp',
			location: `${latitude},${longitude}`,
		}
	).then(res => {
		if(res.status == 0){
			_self.sJson.address = res.result.address;
		}
	}).catch(err => {
		console.log('获取地址信息失败')
	})
},

获取定位地址信息(会跨域,要安装插件vue-jsonp)
安装插件

npm i vue-jsonp -S
//腾讯地图key
import {key} from '../../common/js/http.js'
import Vue from 'vue'
//使用jsonp解决获取地址信息跨域问题
import {VueJsonp} from 'vue-jsonp'
//引用出错则改    import * as VueJsonp from 'vue-jsonp'
Vue.use(VueJsonp)
const vm = new Vue();
//获取定位地址信息 key 腾讯地图的key
getAdressInfo(latitude, longitude){
	var _self = this;
	vm.$jsonp(
		'https://apis.map.qq.com/ws/geocoder/v1/',
		{
			key: _self.key,
			callbackName: "getJsonData",
			output: 'jsonp',
			location: `${latitude},${longitude}`,
		}
	).then(res => {
		if(res.status == 0){
			_self.sJson.address = res.result.address;
		}
	}).catch(err => {
		console.log('获取地址信息失败')
	})
},

二、微信小程序授权登录

1.先登录,在授权

uni.login({
	provider: 'weixin',
	success: function(loginRes) {
		_self.code = loginRes.code
	}
});
uni.getUserProfile({
	desc: '登录',
	success(res) {
		_self.wxAuthor(res, item)
		_self.closeTime()
	},
	fail(err) {
		_self.closeTime()
		_self.$commonly.showTip('您需要先登录')
	}
})

2.获取用户信息

//sJson 登录获取的数据
wxAuthor(sJson, item){
	const success = function (res) {
		let result = res.result
		//更新用户信息
		_self.$store.commit('updateUserInfo', result)
		_self.$store.commit('setLoginStatus', true)
		//登录成功跳转页面
		if (item.url) {
			_self.$commonly.nvt(item.url)
		}
	};
	var sData = {
		opt: {
			data: {
				code: _self.code,
				encryptedData: sJson.encryptedData,
				iv: sJson.iv
			},
			url: 'wechat/wxAuthor',
			method: 'get'
		},
		success: success
	}
	_self.$store.dispatch('request', sData);
}

总结

来自两个微信项目的总结,穿插个人业务。当中含有微信签名和跨域问题。

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值