gpt4 book ai didi

php - 在 Laravel 中测试 Stripe

转载 作者:行者123 更新时间:2023-12-02 03:33:34 25 4
gpt4 key购买 nike

我正在 Laravel 中创建一个基于订阅的 SaaS 平台,但 Laravel Cashier 不适合我的需求。因此我需要使用 Stripe 库自己实现订阅引擎。

我发现通过 Hook Subscription 类的创建和删除事件,可以轻松实现 Laravel 和 Stripe 之间的连接,然后相应地创建或取消 Stripe 订阅。

遗憾的是,Stripe 库很大程度上基于对某些预定义类调用静态方法(例如 \Stripe\Charge::create())。

这让我很难测试,因为您通常会允许依赖注入(inject)一些自定义客户端来进行模拟,但由于 Stripe 库是静态引用的,因此没有要注入(inject)的客户端。有没有什么方法可以创建 Stripe 客户端类或类似的类,以便我可以模拟?

最佳答案

来自 future 的你好!

我只是在研究这个。所有这些类都扩展自 Stripe 的 ApiResource 类,继续挖掘,您会发现当库即将发出 HTTP 请求时,它会调用 $this->httpClient()httpClient 方法返回对名为 $_httpClient 的变量的静态引用。方便的是,Stripe ApiRequestor 类上还有一个名为 setHttpClient 的静态方法,它接受一个应该实现 Stripe 的对象HttpClient\ClientInterface(此接口(interface)仅描述一个名为 request 的方法)。

Soooooo,在您的测试中,您可以调用 ApiRequestor::setHttpClient 并向其传递您自己的 http 客户端模拟的实例。然后,每当 Stripe 发出 HTTP 请求时,它都会使用您的模拟而不是默认的 CurlClient。然后,您的责任是让您的模拟返回格式良好的 Stripe 式响应,并且您的应用程序将不会变得更明智。

这是我在测试中开始使用的一个非常愚蠢的假货:

<?php

namespace Tests\Doubles;

use Stripe\HttpClient\ClientInterface;

class StripeHttpClientFake implements ClientInterface
{
private $response;
private $responseCode;
private $headers;

public function __construct($response, $code = 200, $headers = [])
{
$this->setResponse($response);
$this->setResponseCode($code);
$this->setHeaders($headers);
}

/**
* @param string $method The HTTP method being used
* @param string $absUrl The URL being requested, including domain and protocol
* @param array $headers Headers to be used in the request (full strings, not KV pairs)
* @param array $params KV pairs for parameters. Can be nested for arrays and hashes
* @param boolean $hasFile Whether or not $params references a file (via an @ prefix or
* CURLFile)
*
* @return array An array whose first element is raw request body, second
* element is HTTP status code and third array of HTTP headers.
* @throws \Stripe\Exception\UnexpectedValueException
* @throws \Stripe\Exception\ApiConnectionException
*/
public function request($method, $absUrl, $headers, $params, $hasFile)
{
return [$this->response, $this->responseCode, $this->headers];
}

public function setResponseCode($code)
{
$this->responseCode = $code;

return $this;
}

public function setHeaders($headers)
{
$this->headers = $headers;

return $this;
}

public function setResponse($response)
{
$this->response = file_get_contents(base_path("tests/fixtures/stripe/{$response}.json"));

return $this;
}
}

希望这有帮助:)

关于php - 在 Laravel 中测试 Stripe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48598278/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com