微信小程序獲取openid


通過登錄接口獲取登錄憑證,然后通過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({
                 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代碼:

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的方法。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM