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

1,222次阅读
没有评论

这是一个基本的简单版本。如果需要更加复杂的功能还需要在此代码基础上进行再次的修改

第一步:index.php 页面,用户同意授权,获取  code

<?php
$appid = ‘APPID’;
$redirect_uri = urlencode(‘http://example.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);

第二步:test.php 页面,通过返回的  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_tokenopenid获取用户的信息

$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’ => ”,
        ‘privilege’ => array()
);

正文完
 0
飞翔的mouse
版权声明:本站原创文章,由 飞翔的mouse 于2020-04-16发表,共计1379字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。