官方文档地址: 微信公众号网页开发文档
Scope 权限有三种
- snsapi_base 默认允许授权,无须用户同意
- snsapi_userinfo 进入授权页需要用户同意才可进入
snsapi_login 只适用于网页扫码登录,并且是网站应用
需要注意的点
- 设置IP白名单
- 检查当前公众号是否为服务号
- 回调地址填写是否正确
- 回调地址需要url编码 如 https:// 为 http%3A%2F%2F
一.前端
第一步: 请求下方地址,拿到服务器回调的Code
请求地址: 自行修改 APPID,回调地址与scope类型
https://open.weixin.qq.com/connect/oauth2/authorizeappid=APPID&redirect_uri=回调地址&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect`
第二步: 将Code传给后端,换取acces_token,以便拿到用户的详细信息
二.后端
配置基础数据,APPID与AppSecret
getuserinfo.php 基础配置
<?php
require_once "getdata.php";
$code=$_POST['code']; //前台传入的回调Code
define("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 调用方法集
<?php
class 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.weixin.qq.com/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.weixin.qq.com/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;
}
}