,

Mocking stripe-php

An easy way to mock Stripe’s PHP library for unit tests.

stripe-php is a proxy layer for Stripe’s REST API. The official way to comprehensively test a Stripe integration is by using stripe-mock, which acts as a local API – in a separate process. This is not possible in every environment, though. Here’s an easier way to test PHP code which uses stripe-php.

Custom HTTP client

The library allows for setting a custom “HTTP client”. By default it will use HttpClient\CurlClient. It can be replaced by calling the setHttpClient method of ApiRequestor class.

The client has to implement the ClientInterface, which just means that it has to expose a request method, which returns an array containing the response data (body, status code, and HTTP headers). Putting it all together, a custom client might look like this:

class StripeMockHTTPClient {
	public function request( $method, $path, $headers, $params ) {
		$endpoint = str_replace( 'https://api.stripe.com', '', $path );
		$response = [];
		switch ( $endpoint ) {
			case '/v1/customers':
				switch ( $method ) {
					case 'get':
						$response = [
							'object'   => 'list',
							'data'     => [
								[
									'id'     => 'cus_1', 
									'object' => 'customer',
								],
							],
							'has_more' => false,
						];
						break;
				}
				break;
		}
		$code    = 200;
		$headers = [];
		return [ wp_json_encode( $response ), $code, $headers ];
	}
}

This one just handles one endpoint, the one listing customers. The shape of any response can be checked in the API docs.

With that class in hand, all that’s left is to tell Stripe to use it:

\Stripe\ApiRequestor::setHttpClient( new StripeMockHTTPClient() );

And that’s it. More endpoints handling can be added as needed.

Leave a comment

Comments (

0

)