微信网页授权文档地址 : https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842

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

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

3 第三步:刷新access_token(如果需要)

4 第四步:拉取用户信息(需scope为 snsapi_userinfo)

<?php

//获取code
$code = $_GET[\'code\'];


// 在微信公众号请求用户网页授权之前,开发者需要先到公众平台官网中的“开发 - 接口权限 - 网页服务 - 网页帐号 - 网页授权获取用户基本信息”的配置选项中,修改授权回调域名。请注意,这里填写的是完整域名(是一个字符串),而不是URL,因此请勿加 http:// 等协议头;
$appid          = \'your appid\';        // 微信公众平台申请的APPID
$secret         = \'your secret\';       // 微信公众平台申请的AppSecret


// 前端访问以下地址进行授权登陆, 例子: https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxf0e81c3bee622d60&redirect_uri=http%3A%2F%2Fnba.bluewebgame.com%2Foauth_response.php&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect


//获取access_token
$token_url = \'https://api.weixin.qq.com/sns/oauth2/access_token?appid=\'.$appid.\'&secret=\'.$secret.\'&code=\'.$code.\'&grant_type=authorization_code\';
$token_res = https_request($token_url);

$token_data = json_decode($token_res,true);
$token = $token_data[\'access_token\'];
$openid = $token_data[\'openid\'];

//获取用户信息
$userinfo_url = \'https://api.weixin.qq.com/sns/userinfo?access_token=\'.$token.\'&openid=\'.$openid.\'&lang=zh_CN\';
$userinfo_res = https_request( $userinfo_url);

//转换用户信息
$userinfo_data  = json_decode($userinfo_res,true);

if (empty($userinfo_data[\'unionid\'])) {
    echo \'授权失败, 请重试\';
} else {
    // 数据处理
    $data[\'nickname\']       = $userinfo_data[\'nickname\'];       // 用户昵称
    $data[\'sex\']            = $userinfo_data[\'sex\'];            // 用户性别,1为男性,2为女性
    $data[\'province\']       = $userinfo_data[\'province\'];       // 用户个人资料填写的省份
    $data[\'city\']           = $userinfo_data[\'city\'];           // 用户个人资料填写的城市
    $data[\'country\']        = $userinfo_data[\'country\'];        // 国家,如中国为CN
    $data[\'headimgurl\']     = $userinfo_data[\'headimgurl\'];     // 用户头像,最后一个数值代表正方形头像大小(有0、46、64、96、132数值可选,0代表640*640正方形头像),用户没有头像时该项为空
    $data[\'unionid\']        = $userinfo_data[\'unionid\'];        // 用户统一标识。针对一个微信开放平台帐号下的应用,同一用户的unionid是唯一的。
    $data[\'openid\']         = $userinfo_data[\'openid\'];         // 用户唯一标识。

    echo \'授权登陆成功\';
}

 

版权声明:本文为howey原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/howey/p/10299170.html