微信公众号获取openid(php实例)

微信公众号获取openid

公众号获取openid的方法跟小程序获取openid其实是一样的,只是code获取的方式不一样

小程序获取code:

  用户授权登录时调用wx.login即可获取到code

公众号获取code:

  公众号想要获取code 必须先要用户打开了你的网页,你在菜单栏设置了一个栏目,而链接如:

  https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect

  那么用户点开了你的这个栏目则会跳到  redirect_uri 的路径上面去,同时也会把code传递过去,只需要接收即可

  获取code后,请求以下链接即可获取openid: https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code

  具体详情大家看一下微信文档 :https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html

  相关代码如下:

    public function openid($code){
        $secret = "appsecret";
        $appid = "appid";
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$secret."&code=".$code."&grant_type=authorization_code";

        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch,CURLOPT_TIMEOUT,30);

        $content = curl_exec($ch);
        $status = (int)curl_getinfo($ch,CURLINFO_HTTP_CODE);
        if ($status == 404) {
            return $status;
        }
        curl_close($ch);
        return json_decode($content,true);
    }

  

原文地址:https://www.cnblogs.com/junyi-bk/p/12402789.html