<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/12/28
 * Time: 12:28
 */
namespace Modules\Base\Services\OpenLogin;

class Weixin
{
    public static function getAccessToken($code = null)
    {
        if ($code == null) {
            $code = request('code');
        }
        abort_unless($code, 500, 'code必须');

        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.config('wechat.app.appid').'&secret='.config('wechat.app.secret').'&code='.$code.'&grant_type=authorization_code';
        $info = file_get_contents($url);

        abort_unless($info, 500, '获取TOKEN错误');

        $data = @json_decode($info, true);

        if (!$data || isset($data['errmsg'])) {
            \Log::error('获取微信TOKEN返回信息错误');
            \Log::error($info);
            $msg = $data['errmsg'] ?? '';
            abort(500, '获取微信TOKEN返回信息错误'.$msg);
        }

        return $data;
    }

    public static function getUserInfo($accessToken, $openId)
    {
        $url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$accessToken.'&openid='.$openId;

        $info = file_get_contents($url);

        abort_unless($info, 500, '获取用户信息错误');

        $data = @json_decode($info, true);

        if (!$data || isset($data['errmsg'])) {
            \Log::error('获取微信TOKEN返回信息错误');
            \Log::error($info);
            $msg = $data['errmsg'] ?? '';
            abort(500, '获取微信TOKEN返回信息错误'.$msg);
        }

        return $data;
    }
}
