使用PHP请求获取用户的信息,前后端分离getCode方法前端使用获取code
<?php
namespace app\index\controller;
use think\Controller;
class Index extends Controller
{
private $appId;
private $appSecret;
public function __construct(){
$this->appId = '你的微信appid';
$this->appSecret= '你的微信appSecret';
}
public function index()
{
return 'index';
}
//获取code
//1、以snsapi_base为scope发起的网页授权,是用来获取进入页面的用户的openid的,并且是静默授权并自动跳转到回调页的。用户感知的就是直接进入了回调页(往往是业务页面)
//2、以snsapi_userinfo为scope发起的网页授权,是用来获取用户的基本信息的。但这种授权需要用户手动同意,并且由于用户同意过,所以无须关注,就可在授权后获取该用户的基本信息。
public function getCode(){
//scope=snsapi_base 实例
$unique_id = $_GET["unique_id"];
$appid = $this->appId;
$redirect_uri = urlencode ('https://ticiapi.hdn.cn/index/index/getUserInfo?unique_id='.$unique_id);
$url ="https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_base&state=1#wechat_redirect";
header("Location:".$url);
}
//获取用户信息
public function getUserInfo(){
$appid = $this->appId;
$secret = $this->appSecret;
$code = $_GET["code"];
//第一步:取全局access_token
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
$token = $this->getJson($url);
//第二步:取得openid
$oauth2Url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code";
$oauth2 = $this->getJson($oauth2Url);
//第三步:根据全局access_token和openid查询用户信息
$access_token = $token["access_token"];
$openid = $oauth2['openid'];
$get_user_info_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$openid&lang=zh_CN";
$userinfo = $this->getJson($get_user_info_url);
var_dump($userinfo);
}
//请求
public function getJson($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
return json_decode($output, true);
}
}