<?php
namespace Modules\Common\Support\Http;

use GuzzleHttp\Client;

class HttpRequest
{

    /**
     * 发送post请求
     * @param $url 请求地址
     * @param $accessToken 请求access_token
     * @param $postMessage 请求体
     * @return array
     */
    public static function simplePost($url, $postMessage) {
        $client = new Client(['timeout' => 10]);
        try {
            $res = $client->post(
                $url,
                [
                    'json' => $postMessage
                ]);
            $httpStatusCode = $res->getStatusCode();
            $httpContent = $res->getBody()->getContents();
            $parsedContent = json_decode($httpContent, true);
            if (200 == $httpStatusCode) {
                return $parsedContent;
            }
        } catch (\Exception $exception) {
            myLog('HttpRequest')->error('请求失败:', [
                'url' => $url,
                'json' => $postMessage,
                'exceptionMessage' => $exception->getMessage(),
            ]);
        }
        return false;
    }

    public static function simpleGet($url, $query) {
        $client = new Client(['timeout' => 10]);
        try {
            $response = $client->get($url, [
                'query' => $query
            ]);
            $httpStatusCode = $response->getStatusCode();
            $httpContent = $response->getBody()->getContents();
            $parsedContent = json_decode($httpContent, true);
            if (200 == $httpStatusCode)  {
                return $parsedContent;
            }
        } catch (\Exception $exception) {
            myLog('HttpRequest')->error('请求失败:', [
                'url' => $url,
                'query' => $query,
                'exceptionMessage' => $exception->getMessage(),
            ]);
        }
        return false;
    }
}
