热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

PHP实现微信网页登陆授权开发

官方开发文档地址https:open.weixin.qq.comcgi-binshowdocument?actiondir_list&tresourceres_

官方开发文档地址
https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419316505&token=&lang=zh_CN

  1. 第三方发起微信授权登录请求,微信用户允许授权第三方应用后,微信会拉起应用或重定向到第三方网站,并且带上授权临时票据code参数;

  2. 通过code参数加上AppID和AppSecret等,通过API换取access_token;

  3. 通过access_token进行接口调用,获取用户基本数据资源或帮助用户实现基本操作。

/*
返回 code state
*/

$appid = 'wxea1xxxxxxxx20cb62';

$url = "https://open.weixin.qq.com/connect/qrconnect?appid=$appid&redirect_uri=http://zhiliaoke.com.cn/weixin.php&response_type=code&scope=snsapi_login&state=1&connect_redirect=1#wechat_redirect";

header('location:'.$url);

php处理文件


$code = $_GET['code'];
$state = $_GET['state'];
//换成自己的接口信息
$appid = 'XXXXX';
$appsecret = 'XXXXX';
if (empty($code)) $this->error('授权失败');
$token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$appsecret.'&code='.$code.'&grant_type=authorization_code';
$token = json_decode(file_get_contents($token_url));
if (isset($token->errcode)) {
echo '

错误:

'
.$token->errcode;
echo '

错误信息:

'
.$token->errmsg;
exit;
}
$access_token_url = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid='.$appid.'&grant_type=refresh_token&refresh_token='.$token->refresh_token;
//转成对象
$access_token = json_decode(file_get_contents($access_token_url));
if (isset($access_token->errcode)) {
echo '

错误:

'
.$access_token->errcode;
echo '

错误信息:

'
.$access_token->errmsg;
exit;
}
$user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token->access_token.'&openid='.$access_token->openid.'&lang=zh_CN';
//转成对象
$user_info = json_decode(file_get_contents($user_info_url));
if (isset($user_info->errcode)) {
echo '

错误:

'
.$user_info->errcode;
echo '

错误信息:

'
.$user_info->errmsg;
exit;
}

$rs = json_decode(json_encode($user_info),true);//返回的json数组转换成array数组

//打印用户信息
echo '
';
print_r($rs);
echo '
'
;


?>

推荐阅读
author-avatar
拍友2602923913
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有