微信小程序获取 openID

1.通过 wx.login接口获取code如:
wx.login({
    success: res => {
      console.log("code",res)
      // 发送 res.code 到后台换取 openId, sessionKey, unionId
      var wx_code=res.code

      
  wx.request({
 url: 'https://spreaddisc.checkba.net/index.php',
                   method: "POST",
                    data: {
                      wx_code:wx_code
                    },
                    header: {
                      'content-type': 'application/x-www-form-urlencoded' // 默认值
                    },
                    success: function (res) {
                      //这里可以获取数据;
                      console.log("openid", res);

                      var data = res.data;
                      var length = data.length;


}
PHP代码: index.php

$code=I("post.wx_code");
     $appid="************";
     $secret="*********";
 $api="https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$secret}&js_code={$code}&grant_type=authorization_code"; //调用官方接口
     $wx_code=$this->httpGet($api);
     $data=json_decode($wx_code,true);
     $openid=$data["openid"]; //用户的openid  
    echo $openid;

httpGet函数:
public function httpGet($url){
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_TIMEOUT,500);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST , true);
    curl_setopt($curl, CURLOPT_URL, $url);
    $res = curl_exec($curl);
    curl_close($curl);
    return $res;
}
--------------------- 
作者:he_Lucian 
来源:CSDN 
原文:https://blog.csdn.net/u012729832/article/details/79650531 
版权声明:本文为博主原创文章,转载请附上博文链接!

展开阅读全文

没有更多推荐了,返回首页