微信小程序獲取openid
阿新 • • 發佈:2017-10-31
con 程序 data ica 返回 global quest decode 微信小程序 ({
url: ‘https://XXXXXXXXX/getopenid‘, //後臺獲取openid的鏈接,該鏈接域名需要添加到小程序request 合法域名
header: { "Content-Type": "application/x-www-form-urlencoded" },
method: "POST",
data: { code: res.code, appid: a.appid, appsecret:a.secret },
success: function (res) {
that.globalData.openid = res.data.openid;
console.log("openid:"+that.globalData.openid);
}
})
} else {
console.log(‘獲取用戶登錄態失敗!‘ + res.errMsg)
}
}
});
後臺獲取openid代碼:
";
$get_return = file_get_contents($get_url);
$get_return = (array)json_decode($get_return);
//$openid=$get_return[‘openid‘];
echo json_encode($get_return);exit();
通過登錄接口獲取登錄憑證,然後通過request請求後臺獲取openid,需要把後臺域名放到小程序後臺的request 合法域名內:
1.wx.login 獲取登錄憑證
2.wx.request
發起的是 HTTPS 請求
3.後臺處理請求並返回openid
下面是實現代碼:
小程序代碼:
wx.login({
success: function (res) { if (res.code) { console.log("我是登錄憑證:"+res.code); var a = that.globalData; //這裏存儲了appid、secret wx.request public function getopenid(){
$data = $_POST;
//echo json_encode($data);
$appid=$data[‘appid‘];
$appsecret=$data[‘appsecret‘];
$code=$data[‘code‘];
$get_url="https://api.weixin.qq.com/sns/jscode2session?appid=".$appid."&secret=".$appsecret."&js_code=".$code."&grant_type=authorization_code
$get_return = file_get_contents($get_url);
$get_return = (array)json_decode($get_return);
//$openid=$get_return[‘openid‘];
echo json_encode($get_return);exit();
}
以上就是小程序獲取openid的方法。
微信小程序獲取openid