原生PHP实现微信授权并获取用户信息

微信公众号授权获取用户信息一共分为三部:

1:用户同意授权,获取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

get参数说明:

appid:微信公众号的唯一标识appid

redirect_uri:授权回调地址

response_type:返回类型,填code

scope:授权方式:snsapi_base:静默授权(不弹出授权页面,直接跳转,只能获取用户openid), snsapi_userinfo:获取用户的详细信息

state:回调时带的参数

wechat_redirect:无论直接打开还是做页面302重定向时候,必须带此参数

2:通过code换取网页授权access_token

调取获取access_token接口

https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code

get参数说明:

appid:微信公众号的唯一标识appid

secret:微信公众号的appsecret

code:微信授权返回的code值

grant_type:固定填写:authorization_code

调取上面的接口返回数据如下:

{
  "access_token":"ACCESS_TOKEN",
  "expires_in":7200,
  "refresh_token":"REFRESH_TOKEN",
  "openid":"OPENID",
  "scope":"SCOPE" 
}

如果使用的是静默授权的话到此就可以了

3:获取用户信息

调取获取用户信息接口

https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN

get参数说明:

access_token:上面接口获取的access_token

openid:上面接口获取的openid,即用户的唯一标识

lang:返回国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语

调取上面的接口返回数据如下:

{   
  "openid":" OPENID",
  " nickname": NICKNAME,
  "sex":"1",
  "province":"PROVINCE"
  "city":"CITY",
  "country":"COUNTRY",
  "headimgurl":       "http://thirdwx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/46",
  "privilege":[ "PRIVILEGE1" "PRIVILEGE2"     ],
  "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
}

根据上面的步骤原生php时间代码如下:

public function actionGetMember()
{
    //开启session
    session_start();
    if (!isset($_SESSION['member'])) {
        //appid
        $appId = 'wx73d0c47a64aa5315';
        //secret
        $appSecret = 'aba2793c10623350f6aeee5a728099d3';
        if (!isset($_GET['code'])) {
            //授权
            $this->authorize($appId);
        } else {
            $code = $_GET['code'];
            //获取access_token和openID
            $res = $this->getAccessToken($appId, $appSecret, $code);
            $accessToken = $res['access_token'];
            $openId = $res['openid'];
            //获取用户信息
            $this->getMember($accessToken, $openId);
        }
    }
    $member = isset($_SESSION['member']) ? $_SESSION['member'] : [];
    var_dump($member);
}
/*
 * 获取用户信息
 */
public function getMember($accessToken, $openId)
{
    $params = [];
    $params['access_token'] = $accessToken;
    $params['openid'] = $openId;
    $params['lang'] = 'zh_CN';
    $urlParams = $this->urlParams($params);
    $memberUrl = 'https://api.weixin.qq.com/sns/userinfo?' . $urlParams;
    $member = $this->http_curl($memberUrl);
    $member = json_decode($member, true);
    $_SESSION['member'] = $member;
}
/*
 * 授权
 */
public function authorize($appId)
{
    //获取当前url
    $redirectUrl = $this->getUrl();
    $params = [];
    $params['appid'] = $appId;
    $params['redirect_uri'] = $redirectUrl;
    $params['response_type'] = 'code';
    $params['scope'] = 'snsapi_userinfo';
    $params['state'] = 'STATE';
    $urlParams = $this->urlParams($params);
    $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?'. $urlParams .'#wechat_redirect';
    header('location:' . $url);
}
/*
 * 字符串拼接
 */
public function urlParams($params)
{
    $options = '';
    foreach ($params as $key => $value) {
        $options .= $key . '=' . $value .'&';
    }
    $options = rtrim($options, '&');
    return $options;
}
/*
 * 获取当前url
 */
public function getUrl()
{
    //获取协议类型
    $protocalPort = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
    //获取当前执行脚本的url
    $phpSelf = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
    $pathInfo = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '';
    $queryString = isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : '';
    $relateUrl = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : $phpSelf . (!empty($queryString) ? '?' . $queryString : $pathInfo);
    $url = $protocalPort . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '') . $relateUrl;
    return $url;
}
/*
 * 获取access_token
 */
public function getAccessToken($appId, $appSecret, $code)
{
    $params = [];
    $params['appid'] = $appId;
    $params['secret'] = $appSecret;
    $params['code'] = $code;
    $params['grant_type'] = 'authorization_code';
    $urlParams = $this->urlParams($params);
    $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?' . $urlParams;
    $result = $this->http_curl($url);
    $result = json_decode($result, true);
    return $result;
}
/*
 * curl接口调用
 */
public function http_curl($url, $data=null) {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    $result = curl_exec($curl);
    curl_close($curl);
    return $result;
}

你可能感兴趣的