微信公众号嵌入项目开发基本操做php
第三方发起微信受权登陆请求,微信用户容许受权第三方应用后,微信会拉起应用或重定向到第三方网站,而且带上受权临时票据code参数;前端
经过code参数加上AppID和AppSecret等,经过API换取access_token;ios
经过access_token进行接口调用,获取用户基本数据资源或帮助用户实现基本操做。web
连接地址:open.weixin.qq.com/cgi-bin/sho…axios
1.微信公众号开发后端
appid:公司配置时自动生成
encodeURIComponent()用来转码的 http://微信公众号配置的回调域名/路径
snsapi_userinfo:手动确认受权
snsapi_base:自动确认受权
https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxf0e81c3bee622d60&redirect_uri=http%3A%2F%2Fnba.bluewebgame.com%2Foauth_response.php&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
getOpenId(code) { //获取openId
this.$indicator.open("受权获取中");
this.$axios({
method: "post",
url: 'weChat/getWeChatUserInfo',
params: {
code: code,
recommederId: this.recommederId,//此字段根据项目入参自行定义,非必传
sourceBusiness: this.$route.query.sourceBusiness || 2, //业务来源字段
}
})
.then(reg => {
this.$indicator.close();
localStorage.setItem('openId', reg.responseBody.openId || '');
localStorage.setItem('token', reg.responseBody.token || '');
localStorage.setItem('headimgurl', reg.responseBody.headimgurl || '');
localStorage.setItem('nickname', reg.responseBody.nickname || '');
localStorage.setItem('userId', reg.responseBody.userId || '');
this.isRouterAlive = true;
this.reload();
}, ero => {
this.isRouterAlive = true;
console.log(ero);
})
},
getCode() { //若是是微信公众号进入,获取code
if(!localStorage.getItem("openId")) {
this.code = getParams("code");
if(!this.code) {
window.location.replace("https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + _config.appId + "&redirect_uri=" + encodeURIComponent(location.href) + '&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect');
} else {
this.getOpenId(this.code);
}
} else {
this.openId = localStorage.getItem("openId");
this.isRouterAlive = true;
}
},
复制代码
2.根据code值前端获取openid,传给后端api
window.location.href='https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=appsecret&code=CODE&grant_type=authorization_code';
复制代码
错误状态:微信
{"errcode":40030,"errmsg":"invalid refresh_token"}app
刷新access_token有效期post
access_token是调用受权关系接口的调用凭证,因为access_token有效期(目前为2个小时)较短,当access_token超时后,能够使用refresh_token进行刷新,access_token刷新结果有两种:
若access_token已超时,那么进行refresh_token会获取一个新的access_token,新的超时时间;
若access_token未超时,那么进行refresh_token不会改变access_token,但超时时间会刷新,至关于续期access_token。
refresh_token拥有较长的有效期(30天),当refresh_token失效的后,须要用户从新受权。
正确返回参数以下: { "access_token":"ACCESS_TOKEN", "expires_in":7200, "refresh_token":"REFRESH_TOKEN", "openid":"OPENID", "scope":"SCOPE", "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL" }
实际项目运用: getCode(){//若是是微信公众号进入,获取code if(!localStorage.getItem("openId")){ this.code = getParams("code"); if(!this.code){ window.location.href = "open.weixin.qq.com/connect/oau…"+encodeURIComponent(location.href)+'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect'; }else{ this.getOpenId(this.code); } }else{ this.openId = localStorage.getItem("openId"); } }