您的位置:首页 > 移动开发 > 微信开发

微信H5授权获取code,拿取用户信息(前端部分)

2020-02-03 09:47 2715 查看

微信H5授权获取code,拿取用户信息

##如果用户在微信客户端中访问第三方网页,公众号可以通过微信网页授权机制,来获取用户基本信息,进而实现业务逻辑。

这是微信给的说明文档,但实际上,我们首先要做的是去微信公众平台设置一些配置

  1. 开发–>基础配置

    这里我们就可以拿到AppIDAppSecret(后台会用到)及ip白名单
  2. 开发–>接口权限


    设置js接口安全域名与网页授权域名

到这里前期的基础工作就已经完成了

下面就开始代码部分

// 判断是否为公众号模拟器环境
const isWechat = () => {
return String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) === "micromessenger";
}

我们要拿code,就必须先访问这个地址,其中appid 是必填(可以把这串地址直接放到微信浏览器中打开,就会出现授权提示)

https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect

访问微信给的链接地址,就可以拿取到code,下面这部分代码就是拿取code

// 判断公众号截取code
const getUrlParam = (name) => {
let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
let r = window.location.search.substr(1).match(reg);
if (r != null) {
return unescape(r[2]);
}
return null;
}

参数说明

参数 是否必须 说明
appid 公众号的唯一标识
redirect_uri 授权后重定向的回调链接地址,请使用urlencode对链接进行处理
response_type 返回类型,请填写code
scope 应用授权作用域,snsapi_base (不弹出授权页面,直接跳转,只能获取用户openid),snsapi_userinfo (弹出授权页面,可通过openid拿到昵称、性别、所在地。并且,即使在未关注的情况下,只要用户授权,也能获取其信息)
state 重定向后会带上state参数,开发者可以填写a-zA-Z0-9的参数值,最多128字节

下面我自己上写的一个测试demo代码

// 判断是否为公众号模拟器环境
const isWechat = () => {
return String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) === "micromessenger";
}
// 判断公众号截取code
const getUrlParam = (name) => {
let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
let r = window.location.search.substr(1).match(reg);
if (r != null) {
return unescape(r[2]);
}
return null;
}export default {
data() {
return {
code: ''
}
},
onLoad() {
this.getWxCode()
},
methods: {
getWxCode(){
if (isWechat()) {
let appid = "wxae048f1b059e77c0"; //为测试号id
let code = getUrlParam("code"); //是否存在code
let local = window.location.href;
// let local = 'http://h5.x*****o.com/'		//测试路径
if (code == null || code === "") {
//不存在就打开上面的地址进行授权
window.location.href =
`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodeURIComponent(local)}&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect`;
// https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxae048f1b059e77c0&redirect_uri=http://devapi.xingyeqiao.com/&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
}else{
this.code = code
}
}
}
}
}

local路径要和授权域名对应上
window.location.href跳转去授权,授权成功后会重定向之前的页面,这样我们就拿到code,然后把code给后台,就可以拿到openid,获取到用户信息了

  • 点赞
  • 收藏
  • 分享
  • 文章举报
了多想 发布了1 篇原创文章 · 获赞 0 · 访问量 35 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: