结合文档和百度整理出几个方法,记录一下
用户直接访问getcode这个方法就行
<?php
namespace app\common\controller;
use think\Controller;
class Getinfo extends Controller
{
//获取code
public function getcode()
{
$appid = '公众号APPID';
$huiurl = urlEncode('请求成功后的回调地址,具体到你的控制器方法中');//这里的url一定要用urlEncode处理一下
//scope参数:snsapi_base(不弹出授权页面,直接跳转,只能获取用户openid)snsapi_userinfo(弹出授权页面,可通过openid拿到昵称、性别、所在地。并且, 即使在未关注的情况下,只要用户授权,也能获取其信息 )
$url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'&redirect_uri='.$huiurl.'&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect';
header('location:'.$url);
}
//获取网页授权access_token,获取用户的openid
public function getopenid()
{
$appid = '公众号APPID';
$appsecret = '公众号的appsecret';
$code = $_GET['code'];//这里用来接收上一步回调回来的code
$url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$appsecret.'&code='.$code.'&grant_type=authorization_code';
$res = $this->http_curl($url,'get');
//进行到这里其实就可以做一下操作了,比如限制用户一天进入几次等操作;
//下面就是获取用户信息了
if(!empty($res['access_token'])){
$data = $this->getuser($res['access_token'],$res['openid']);
}
var_dump($data);//获取到的用户信息
}
//获取用户信息
public function getuser($access_token,$openid)
{
$url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';
$data = $this->http_curl($url,'get');
return $data;
}
//执行url请求
public function http_curl($url,$type='get',$res='json',$arr=''){
// $url 请求的url
// $type 请求类型
// $res 返回数据类型
// $arr post请求参数
$ch=curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
if($type=='post'){
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch,CURLOPT_POSTFIELDS,$arr);
}
$output = curl_exec($ch);
curl_close($ch);
if($res=='json'){
return json_decode($output,true);
}
}
}