微信公众号实现网页授权登录

微信公众平台接口测试号地址:https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login

开发文档地址:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842

第一步:用户同意授权,获取code

<?php
$appid = 'APPID';
$redirect_uri = urlencode('http://www.phpzhi.com/test.php');//重定向地址

$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
header("Location:" . $url);

第二步:通过返回的code获取网页授权的access_token

<?php
$appid = "APPID";
$secret = "APPSECRET";
$code = $_GET["code"];

$oauth2Url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code";
$oauth2 = getJson($oauth2Url);

//access_token和openid
$access_token = $oauth2["access_token"];
$openid = $oauth2['openid'];

function getJson($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);
    return json_decode($output, true);
}

第三步:通过access_token和openid获取用户的信息

$get_user_info_url = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN";
$userinfo = getJson($get_user_info_url);

//打印用户信息
print_r($userinfo);
//array('openid' => 'oiuH-xxxxxxxxxxxxx',
        'sex' => 1,
        'language' => 'zh_CN',
        'city' => '南宁',
        'province' => '广西',
        'country' => '中国',
        'headimgurl' => 'http://thirdwx.qlogo.cn/mmopen/vi_32/LyJOXEvevuUTicVz0LCibBzQw9FI8iaAp6bzN4Q6R1YHd3Sa2nsiaqjtN5kSMgHl4wL1VYf0t4IacY6KaqrN8aJCibA/132',
        'privilege' => array()
);

猜你喜欢

转载自blog.csdn.net/phpzhi/article/details/81837565