How does PHP code get the user's openid from a web page (rev)

Transfer from https://www.cnblogs.com/changbin/p/5509913.html

public function getOpenid($appid, $appsecret)
    {
    
    
        $SERVER_NAME = $_SERVER['SERVER_NAME'];
        $REQUEST_URI = $_SERVER['REQUEST_URI'];
        $redirect_uri = urlencode('http://' . $SERVER_NAME . $REQUEST_URI);
        $code = $_GET['code'];
        if (! $code) {
    
    
            // 网页授权当scope=snsapi_userinfo时才会提示是否授权应用
            $autourl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";
            header("location:$autourl");
        } else {
    
    
            // 获取openid
            $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$appsecret&code=$code&grant_type=authorization_code";
            $row = $this->posturl($url);
            return ($row['openid']);
        }
    }
    public function posturl($url){
    
    
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        curl_close($ch);
        $jsoninfo = json_decode($output, true);
        return $jsoninfo;
    }


//使用方法:
        $appid = "wx18a554232c71513b";
        $secret = "662xxxxxxf9xxxxxxb6xxxxxx44xxxxx";
        $openid= $this->getOpenid($appid, $secret);


 当网页授权的scope=snsapi_userinfo时才会出现下面的界面:

Authorized web pages need to be configured in the official account first. First go to the configuration options of "Development-Interface Permission-Web Service-Web Account-Web Authorization to Obtain User Basic Information" in the official website of the official platform, and modify the authorized callback domain name.

Guess you like

Origin blog.csdn.net/weixin_42094764/article/details/114290451