前言
记录第一次微信网页开发
一、公众号开发测试号相关配置?
打开公众号平台选择公众平台测试账号
在本地调试调用微信公众号官方api获取相关数据可以使用测试号中的appID与appsecret
配置安全域名(例:网页项目运行的本地id域名192.***)扫描测试二维码关注该测试号
授权回调页面域名配置
二、调用微信授权相关api获取用户头像、名称等信息
1.用appID获取授权信息所用code
代码如下:
// 1. 获取授权信息所需code
getCode() {
let redirect = encodeURIComponent(window.location.href); //重定向回来的地址
this.wx_code = this.getUrlParam("code"); // 截取url中的code
//判断有没有code
if (!this.wx_code) {
//获取code的地址。获取成功重定向后地址栏中将会带有code,判断没有code的话,就跳转到微信官方链接上获取,获取成功后会再重定向回来
window.location.href =
`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${this.appid}&redirect_uri=${redirect}&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect`;
} else {
// 获取到了code
this.getAccessToken()
}
},
//截取地址栏里的code
getUrlParam: function(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg);
if (r != null) return unescape(r[2]);
return null;
},
2.获取AccessToken
代码如下:
// 2. 获取AccessToken
getAccessToken() {
getH5AccessToken().then(res => {
if (res.code === 0) {
if (res.data != null) {
this.access_token = res.data
this.wxGetUserInfo() // 第四步
} else {
this.getOpenId() // 第三步
}
} else {
uni.showToast({
title: res.message,
icon: 'none'
})
}
})
},
// 3. 如果服务端没有存储access_token,则通过 code 换取网页授权access_token
getOpenId() {
console.log(this.wx_code)
let that = this
let url =
`https://api.weixin.qq.com/sns/oauth2/access_token?appid=${this.appid}&secret=${this.appsecret}&code=${this.wx_code}&grant_type=authorization_code`;
uni.request({
type: "get", //请求类型
url: 'https://pay.nongmuren.com/nongMuRenZGTSec/common/thirdUrl?url=' + encodeURIComponent(
url),
success(data) {
let res = JSON.parse(data.data.data)
if (res.errcode) {
uni.showToast({
title: res.errmsg,
icon: 'none'
})
} else {
that.access_token = res.access_token
that.openid = res.openid
that.setAccessToken()
that.wxGetUserInfo()
}
}
})
},
3.获取用户信息
如果网页授权作用域为snsapi_userinfo,则此时开发者可以通过access_token和 openid 拉取用户信息了
// 4. 获取用户信息
wxGetUserInfo() {
let that = this
let userUrl =
`https://api.weixin.qq.com/sns/userinfo?access_token=${this.access_token}&openid=${this.userInfo.openid}&lang=zh_CN`
uni.request({
type: "get", //请求类型
url: 'https://pay.nongmuren.com/nongMuRenZGTSec/common/thirdUrl?url=' +
encodeURIComponent(userUrl),
success(userData) {
let resData = JSON.parse(userData.data.data)
saveGzhMember({
headPhoto: resData.headimgurl,
nickname: resData.nickname,
openId: resData.openid,
}).then(res => {
console.log(res)
if (res.code === 0) {
that.userData = res.data
that.userInfo = {
headPhoto: res.data.headPhoto,
isExist: true,
nickname: res.data.nickname,
openId: res.data.openId,
unionId: ''
}
uni.setStorageSync('userInfo', that.userInfo)
}
})
}
})
},
总结
以上就是今天要讲的内容,本文仅仅简单介绍了网页授权相关api的使用,具体细节可以去官网查看
微信官方文档