公众号-获取用户信息


```php

```php
<?php
namespace app\index\controller;
use think\Controller;
class Index extends Controller
{

    public function index()
	{
		$appid = config('params.appid');//自己的appid
		if (!session('?userinfo')) {
			if (!isset($_GET['code'])) {//没有code,去微信接口获取code码

    			$redirect_uri = 'http://xxxx.cn';//自己的跳转地址
				$url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $appid . '&redirect_uri=' . $redirect_uri . '&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect';
				header("location:$url");
				exit();
			} else {//获取code后跳转回来到这里了
				$code = $_GET['code'];
				$data = $this->get_access_token($code);//获取网页授权access_token和用户openid
				$data_all = $this->get_user_info($data['access_token'], $data['openid']);//获取微信用户信息
				
				return json($data_all);
			}

		} else {
			$ret = session('userinfo');
			return json($ret); //返回的获取到的微信用户信息
		}

	}

	//获取access_token
	private function get_access_token($code)
	{
		$appid = config('params.appid');//自己的appid
		$appsecret = config('params.appSecret');//自己的
		$url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appid . '&secret=' . $appsecret . '&code=' . $code . '&grant_type=authorization_code';
		$user = json_decode(file_get_contents($url));
		if (isset($user->errcode)) {
			echo 'error:' . $user->errcode . '
			msg :' . $user->errmsg;
			exit;
		}

		$data = json_decode(json_encode($user), true);//返回的json数组转换成array数组
		return $data;

	}

	/**
	* 使用access_token获取用户信息
	* @param string access_token
	* @param string 用户的openid
	* @return array 用户信息数组
	*/
	private function get_user_info($access_token, $openid)
	{
		$url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $access_token . '&openid=' . $openid . '&lang=zh_CN';
		$user = json_decode(file_get_contents($url));
		if (isset($user->errcode)) {
			echo 'error:' . $user->errcode . 'msg :' . $user->errmsg;
			exit;
		}
		$data = json_decode(json_encode($user), true);//返回的json数组转换成array数组
		return $data;

	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值