微信公众号获取用户基本信息

php

浏览数:277

2019-1-7

AD:资源代下载服务


ThinkPHP开发

<?php
namespace Weixin\Controller;

use Think\Controller;

class WechatController extends Controller
{
    public $appId     = 'your AppID';
    public $appSecret = 'your AppSecret';

    /**
     * [getAccessToken description]
     * @return [type] [description]
     * 要在公众号后台添加服务器IP白名单
     */
    public function getAccessToken()
    {
        $url =  'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->appId.'&secret='.$this->appSecret;
        $jsonInfo = $this->http_curl($url);
        $access_token = $jsonInfo['access_token'];
        return $access_token;
    }

    /**
     * [getUserBaseInfo 获取关注者基本信息]
     * @param  [type] $openId [此账号下的用户openid]
     * @return [type]         [返回用户基本信息]
     */
    public function getUserBaseInfo($openId)
    {
        $access_token = $this->getAccessToken();
        $url = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token='.$access_token.'&openid='.$openId.'&lang=zh_CN';
        $jsonInfo = $this->http_curl($url);
        // var_dump($jsonInfo);
        return $jsonInfo;
    }

    public function http_curl($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);
        $jsonInfo = json_decode($output, true);
        return $jsonInfo;
    }
}