namespace Weixin\Controller;
use Think\Controller;
use Think\Model;
session_start;//打开session
class TestController extends Controller //继承的这个控制器没用 你可以继承其他的任意一个
{
//第一步:用户同意授权,获取code
function accept()
{
//这个链接是获取code的链接 链接会带上code参数
$REDIRECT_URI = BASE_URL.'/weixin/test/getcode';
$REDIRECT_URI = urlencode($REDIRECT_URI);
$scope = "snsapi_userinfo";
$state = md5(mktime());
$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . C('weixin.appid') . "&redirect_uri=" . $REDIRECT_URI . "&response_type=code&scope=" . $scope . "&state=" . $state . "#wechat_redirect";
header("location:$url");
}
//用户同意之后就获取code 通过获取code可以获取一切东西了 机智如我
function getCode()
{
$code = $_GET["code"];
$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . C('weixin.appid') . "&secret=" . C('weixin.appsecret'). "&code=" . $code . "&grant_type=authorization_code";
$res = $this->https_request($url);
$res = json_decode($res, true);
$openid = $res["openid"];
echo "<pre>";
$access_token = $res["access_token"];
$url = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $access_token . "&openid=" . $openid . "&lang=zh_CN";
$res = $this->https_request($url);
$res = json_decode($res, true);
print_r($res);
//把用户的信息写入session 以备查用
$weixin = $res["openid"];
$nickname = $res["nickname"];
$_SESSION["weixin"] = $weixin;
$_SESSION["nickname"] = $nickname;
$model = new Model();
$model->table(C('DB_PREFIX').'user')->add(['openid'=>$res['openid'],'nickname'=>$res['nickname']]);
echo "<pre>";
header("location:".U('User/index'));
}
function https_request($url)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
// if (!empty($data)) {
// curl_setopt($curl, CURLOPT_POST, 1);
// curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
// }
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($curl);
curl_close($curl);
return $output;
}
}
微信用户登录
最新推荐文章于 2024-02-01 09:56:37 发布