<?php

namespace App\Services;

use GuzzleHttp\Client;

class HttpService
{
    /**
     * 提取get请求公共代码
     * @param $url
     * @return \Illuminate\Http\JsonResponse|mixed
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function getData($url){
        $headers = [
            'Key' => config("app.shop_key"), // 自定义头部参数（示例）
        ];
        $client = new Client();
        $response = $client->get($url, [
            'headers' => $headers,
        ]);
        $code = $response->getStatusCode();
        if($code != 200){
            return ['message'=>'请求失败','code'=>1];
        }
        $body = $response->getBody()->getContents(); // 获取响应内容
        $list = json_decode($body, true);
        return $list;
    }

    /**
     * 提取post请求公共代码
     * @param $url
     * @param $params
     * @return \Illuminate\Http\JsonResponse|mixed
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function postData($url,$params){
        $headers = [
            'Key' => config("app.shop_key"), // 自定义头部参数（示例）
        ];

        $client = new Client();
        $response = $client->post($url, [
            'headers' => $headers,
            'json' => $params
        ]);
        $code = $response->getStatusCode();
        if($code != 200){
            return ['message'=>'请求失败','code'=>1];
        }
        $body = $response->getBody()->getContents(); // 获取响应内容
        $list = json_decode($body, true);
        return $list;
    }
}
