youngmayor/web-service

一个用于连接外部服务的 Laravel 扩展包

2.0.1 2022-01-20 12:15 UTC

This package is auto-updated.

Last update: 2024-09-20 18:49:07 UTC


README

Latest Version on Packagist Total Downloads GitHub Actions

一个基于 Guzzle 封装的 Laravel 扩展包,用于连接外部服务/API

安装

您可以通过 composer 安装此扩展包

composer require youngmayor/web-service

用法

该扩展包使用自动发现,因此如果您使用 Laravel 5.5 或更高版本,安装扩展包将自动在您的应用程序中注册。

但是,如果您使用 Laravel 5.4 或更低版本,您需要在您的 config/app.php 中添加以下代码段以注册 Service Provider

'providers' => [
    ...
    YoungMayor\WebService\WebServiceServiceProvider,
    ...
],

接下来创建您的 Service 类以扩展 WebService 类

<?php

namespace App\Services;

use YoungMayor\WebService\WebService;

class MyExampleService extends WebService
{
    /**
    * The baseUri for the service. 
    * This is an important method that must be implemented when extending the WebService Class
    *
    * @return string
    */
    public function baseUri()
    {
        return "https://example.com";
    }

    public function demoAction(array $payload = [])
    {
        return $this->post("/demo/endpoint", [
            'json' => $payload
        ]);
    }
    // ...
}

您的服务可以在应用程序的任何位置运行。上面的只是一个示例

设置默认头部信息

可以为每个请求应用默认头部信息。示例

...
protected $headers = [
    'Accept' => 'application/json'
]

这也可以通过在构造函数中调用 setHeaders($headers) 方法来实现

...
public function __construct()
{
    parent::__construct(); 

    // $bearerToken = ...;
    $this->setHeaders([
        "Content-Type" => "application/json", 
        "Authorization" => "Basic {$bearerToken}"
    ]);
}

设置客户端配置

也可以使用 clientConfig() 方法设置客户端配置。通过返回要附加到请求的配置数组来实现

... 
public function clientConfig()
{
    // $apiKey = ...;

    return array_merge(parent::clientConfig(), [
        'auth' => [$apiKey, 'X'],
        'follow_redirects' => true
    ]);
}

然后您可以添加自己的方法来执行操作。WebService 提供以下方法

get($path, $options);
post($path, $options);
put($path, $options);
delete($path, $options);
patch($path, $options);

路径是我们想要调用的相对路径,选项是 Guzzle 请求选项

使用您的服务类

您的服务类现在可以在应用程序的任何位置注入或实例化。

<?php 

namespace App\Http\Controllers; 

// ...

class DemoController extends Controller
{
    public function demoMethod(Request $request, MyExampleService $myExampleService)
    {
        // Quickly send the request and render the response/error
        return $myExampleService->demoAction()->render();


        // Interact with the response 
        $response = $myExampleService->demoAction();

        // Render the response 
        return $response->render(); 

        //  Get the status code
        $statusCode = $response->getStatusCode(); 

        // Get the response body
        $responseBody = $response->getBody();

        // You can also handle the response/error
        $response->onComplete(
            // ...
        );


        // Handle response/error
        /**
         * The onComplete($onSuccessCallback, $onErrorCallback) method takes two parameters
         * 1. callback to execute on a successful request 
         * 2. callback to execute on a failed request
         * 
         * Both callbacks receive an object which has the following methods:
         * - render(): Renders the response/error to an array
         * - getStatusCode(): Get the status code of the error 
         * - getBody(): Get the body of the response/error as an array
         * 
         * The object passed to the onErrorCallback however has a method for retrieving the error message
         * - getMessage(): Get the error message
         */
        return $myExampleService->demoAction()->onComplete(function($response) {
            $result = $response->render(); 

            $body = $response->getBody(); 

            $statusCode = $response->getStatusCode();

            return [
                'status' => $statusCode, 
                'body' => $body, 
                'message' => "This is a successful call"
            ]
            // OR
            return $result;
        }, function ($error) {
            $result = $error->render(); 

            $body = $error->getBody(); 

            $statusCode = $error->getStatusCode();

            $message = $error->getMessage();

            return [
                'status' => $statusCode, 
                'body' => $body, 
                'message' => "An error occurred: $message"
            ]
            // OR
            return $result;
        });
    }
}

更新日志

请参阅 CHANGELOG 了解最近更改的详细信息。

贡献

请参阅 CONTRIBUTING 了解详细信息。

安全性

如果您发现任何与安全性相关的问题,请通过电子邮件 youngmayor.dev@gmail.com 而不是使用问题跟踪器来报告。

鸣谢

许可协议

MIT 许可协议(MIT)。有关更多信息,请参阅 许可文件

Laravel 扩展包模板

此扩展包使用 Laravel 扩展包模板 生成。