thinkPHP5 微信公众号获取微信用户信息

定义获取文件


namespace app\index\controller;

use app\common\controller\Frontend;
use think\Cache;
use think\Session;
use think\Request;
use think\Controller;
use fast\Http;
/**
 * 微信授权
 *
 */
class Wechatlogin extends Controller
{   

    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    private $app_id = '';
    private $app_secret = '';
    private $scope = 'snsapi_userinfo';

    public function __construct()
    {
        $this->app_id = '这里写公众号的openID';
        $this->app_secret = 'appsecret';
    }

    /**
     * 获取微信授权链接
     *
     * @return string
     */
    public function getAuthorizeUrl()
    {
        $redirect_uri = urlencode(Request::instance()->domain().Request::instance()->url());
        //halt($redirect_uri);
        // $state = \fast\Random::alnum();
        $state = $redirect_uri;
        Session::set('state', $state);
        return "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->app_id}&redirect_uri={$redirect_uri}&response_type=code&scope={$this->scope}&state={$state}#wechat_redirect";
    }

   

    /**
     * 获取微信用户信息
     *
     * @return mixed|string
     */
    public function getUserInfo($openid, $access_token)
    {
        $url = "https://api.weixin.qq.com/sns/userinfo";
        $params = [
            'access_token'=>$access_token,
            'openid'=>$openid,
            'lang'=>'zh_CN'
        ];
        $res = Http::sendRequest($url, $params, 'GET');
        // if($res){
        //     $res = json_decode($res, true);
        // }
        return $res;
    }


    /**
     * 获取授权token网页授权
     *
     * @param string $code
     * @return mixed|string
     */
    public function getAccessToken($code = '')
    {
        $params = [
            'appid'      => $this->app_id,
            'secret'     => $this->app_secret,
            'code'       => $code,
            'grant_type' => 'authorization_code'
        ];
        $ret = Http::sendRequest('https://api.weixin.qq.com/sns/oauth2/access_token', $params, 'GET');

        if ($ret['ret']) {
            $ar = json_decode($ret['msg'], true);
            return $ar;
        }
        return [];
    }
}

在获取用户信息的文件中加入以下代码

public function _initialize(){
        $code = input('code','');
         //halt($code);
        $fromUrl = input('state','');
       // dump(Session::get('wechat_user'));die;
        if(!Session::get('wechat_user')){
            $this->wxlogin($code, $fromUrl);
        }
    }
    /**

     * 获取微信公众号用户信息

     */
    public function wxlogin($code,$fromUrl){
        $wechat = new WechatLogin();
       // dump($code);
        if($code){
            $token = $wechat->getAccessToken($code);
            $openid = isset($token['openid']) ? $token['openid'] : '';
            $access_token = isset($token['access_token']) ? $token['access_token'] : '';
            $userinfo = $wechat->getUserInfo($openid, $access_token);
            if($userinfo['ret']){
                $user_data['userinfo'] = $userinfo['msg'];
                $userinfo_arr = json_decode($userinfo['msg'],true);
                $user_data['openid'] = isset($userinfo_arr['openid']) ? $userinfo_arr['openid'] : '';
                $user_data['username'] = isset($userinfo_arr['nickname']) ? $userinfo_arr['nickname'] : '';
                $user_data['nickname'] = $user_data['username'];
                $user_data['gender'] = isset($userinfo_arr['sex']) ? $userinfo_arr['sex'] : '';
                $user_data['avatar'] = isset($userinfo_arr['headimgurl']) ? $userinfo_arr['headimgurl'] : '';
                //做验证信息操作  自行修改
                $userInfo = \app\admin\model\User::get(['openid'=>$user_data['openid']]);
                if($userInfo){
                    \app\admin\model\User::where(['openid'=>$user_data['openid']])->update($user_data);
                }else{
                    \app\admin\model\User::create($user_data);
                }
                Session::set('wechat_user',$user_data);
                $this->redirect(urldecode(Session::get('state')));
                exit();
            }
        }else{
            $url = $wechat->getAuthorizeUrl();
           // dump($url);
            Header("Location: $url");
            exit();
        }
    }

你可能感兴趣的:(thinkPHP5 微信公众号获取微信用户信息)