PHP代码 如何网页获取用户的openid

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时才会出现下面的界面:

非常感谢大神的指点,让我走了很少的弯路,我也想让看到的朋友少走弯路哈。

posted @ 2016-03-12 11:16  风琴~云淡  阅读(2099)  评论(0编辑  收藏  举报