微信浏览器里的code来源:
let redirect_uri = 'https://.../login'; //指定授权登录后跳转的页面,用于解析code,一般是登录页面
let appid = this.$appid;//公众号id
//跳转微信授权页并获取code,然后他会通过redirect_rui来重新跳回你指定的页面
let url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + appid + '&redirect_uri=' + link +
'&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect'
location.href = url;
login 回调页面
_getParam(path, name) {
var reg = new RegExp("(^|\\?|&)" + name + "=([^&]*)(\\s|&|$)", "i");
if (reg.test(path)) {
return unescape(RegExp.$2.replace(/\+/g, " "));
}
return '';
},
checkIfWeixinLoginBack(){
let thsUrl = location.href;//拿取当前url
// console.log('thsUrl', thsUrl);
let code = this._getParam(thsUrl, 'code');
if(code.length>5) {
let array_ = thsUrl.split('?');//将url截开
let gobackToUsUrl = localStorage.getItem('wxLoginBeforeUrl');
if(!gobackToUsUrl) {
gobackToUsUrl = array_[0] +'/#/pages/home/index';
}
localStorage.removeItem('wxLoginBeforeUrl');
// console.log('wxCode', code);
// 提交code给php解析openid
this.$api.wxCodeUpdateUser({code: code})
.then(res =>{
// console.log('res', res);
// return;
uni.hideLoading()
//hash模式链接会有#
//当链接带有#去请求code值,code会一直跟在链接后面
//解决拿到code值后,每次跳转页面路径都会带有code值的问题
window.location.href = gobackToUsUrl;
})
.catch(err =>{
// console.log('resErr', err);
// return;
uni.hideLoading()
//hash模式链接会有#
//当链接带有#去请求code值,code会一直跟在链接后面
//解决拿到code值后,每次跳转页面路径都会带有code值的问题
window.location.href = gobackToUsUrl;
})
}
},
appid和密钥获取方式:
php需要解析前端授权登录后提交的code
//获取用户openid
protected function _getOpenID($appid, $appsecret, $code)
{
$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $appid . "&secret=" . $appsecret . "&code=" . $code . "&grant_type=authorization_code";
$weixin = file_get_contents($url);//通过code换取网页授权access_token
$jsondecode = json_decode($weixin); //对JSON格式的字符串进行编码
$array = get_object_vars($jsondecode);//转换成数组
if (isset($array["openid"])) {
$openid = $array["openid"];//输出openid
} else {
$openid = 0;
}
return $openid;
}
$params = $this->request->post();
if (!isset($params['code']) || empty($params['code'])) {
$this->error('缺失参数code');
}
$myUid = $this->auth->id;
//获取用户Openid
$appid = Env::get('weixin.appId');
$secret = Env::get('weixin.secret');
// $appid = 'wx01eb21debee79a37';
// $secret = 'add4d54b11f7a52b47ded252b4da0706';
$openId = $this->_getOpenID($appid, $secret, $params['code']);