失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > PHP微信公众号开发(二)微信公众号授权登录

PHP微信公众号开发(二)微信公众号授权登录

时间:2020-10-22 12:51:31

相关推荐

PHP微信公众号开发(二)微信公众号授权登录

官方文档地址: 微信公众号网页开发文档

Scope 权限有三种

snsapi_base 默认允许授权,无须用户同意snsapi_userinfo 进入授权页需要用户同意才可进入snsapi_login 只适用于网页扫码登录,并且是网站应用

需要注意的点

设置IP白名单检查当前公众号是否为服务号回调地址填写是否正确回调地址需要url编码 如 https:// 为 http%3A%2F%2F

一.前端

第一步:请求下方地址,拿到服务器回调的Code

请求地址:自行修改 APPID,回调地址与scope类型

https://open./connect/oauth2/authorizeappid=APPID&redirect_uri=回调地址&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect`

第二步:将Code传给后端,换取acces_token,以便拿到用户的详细信息

二.后端

配置基础数据,APPID与AppSecret

getuserinfo.php 基础配置

<?phprequire_once "getdata.php";$code=$_POST['code']; //前台传入的回调Codedefine("APPID","xxxxxxx");define("APPSECRET","xxxxxxxxxxxx");$wx=new wx(APPID,APPSECRET);$returnInfo=$wx->getAccesstoken($code);$userInfo=$wx->getUserinfo($returnInfo->access_token,$returnInfo->openid);echo json_encode($userInfo);

getData.php 调用方法集

<?phpclass wx{private $_appid;private $_appsecret;public function __construct($appid, $appsecret){$this->_appid = $appid;$this->_appsecret = $appsecret;}public function getAccesstoken($code){// $file = './accesstoken'; //用于保存access token// if (file_exists($file)) { //判断文件是否存在// $content = file_get_contents($file); //获取文件内容// $content = json_decode($content); //json解码// if (time() - filemtime($file) < $content->expires_in) //判断文件是否过期// {//return $content;// }返回access token// }$content = $this->_request("https://api./sns/oauth2/access_token?appid=" . $this->_appid . "&secret=" . $this->_appsecret . '&code=' . $code . '&grant_type=authorization_code'); //获取access token的json对象// file_put_contents($file, $content); //保存json对象到指定文件$content = json_decode($content); //进行json解码return $content; //返回access token}public function getUserinfo($access_token, $openid){$urlid = 'https://api./sns/userinfo?access_token=' . $access_token . '&openid=' . $openid . '&lang=zh_CN';$userInfo = $this->_request($urlid);file_put_contents("./userinfo", $userInfo);$content = json_decode($userInfo); //进行json解码return $content;}public function _request($curl, $https = true, $method = 'get', $data = null, $headers = null){$ch = curl_init(); //初始化curl_setopt($ch, CURLOPT_URL, $curl); //设置访问的URL// curl_setopt($ch, CURLOPT_HEADER, false); //设置不需要头信息curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //只获取页面内容,但不输出curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //不做服务器认证curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); //不做客户端认证if ($method == 'post') {curl_setopt($ch, CURLOPT_POST, true); //设置请求是POST方式curl_setopt($ch, CURLOPT_POSTFIELDS, $data); //设置POST请求的数据}$str = curl_exec($ch); //执行访问,返回结果curl_close($ch); //关闭curl,释放资源return $str;}}

如果觉得《PHP微信公众号开发(二)微信公众号授权登录》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。