Stripe Mock Testing in PHP

Stripe Mock

I’ve been setting up a Stripe integration for a project recently and I wanted to ensure my wrapper around the Stripe SDK was working well.

I’m doing things like creating a connected account and account link and will later be doing things like creating direct charges.

To make sure it’s all working well I want to write unit tests.

Normally I’d mock the Stripe SDK and get it to return hard-coded responses, however that’s a lot of work and Stripe already has a great Stripe Mock server.

I had some issues when using it however.

Firstly, it’s written in Go and needs a version of golang more up-to-date than the default Ubuntu package that’s available.

In Ubuntu 16.04 (yes I know that’s a bit old now, but I had similar issues on a new 20.04 machine) “go version” showed v1.6 but this doesn’t support slice so when running the install command “go get -u” I got the error:

src/ undefined: sort.Slice

I tried to install the more up-to-date versions in the Ubuntu apt repository e.g sudo apt-get install golang-1.13 but was having issues with the old version still being there even after trying to remove it. So I went with installing a much more recent version (v1.16) of it myself.

Now I can run stripe-mock and get the local server running.

However now I had issues with the Stripe PHP SDK. It kept accessing the Stripe API.

Of course I was using test credentials, however it’s obviously not what I wanted.
Online all I could find was a suggestion to use something like:

 Stripe::$apiBase = "http://localhost:" . MOCK_PORT; 

However that didn’t cut it. It seems they’ve migrated to the stripeClient since then and the old advice didn’t help.

Instead, if you are using the Stripe client you’ll want to do something like:

The key point is that you need to set the curl client with the CURLOPT_SSL_VERIFYPEER set off and when creating the Stripe Client you need to set the api_base.

the 2 liner version is:

\Stripe\ApiRequestor::setHttpClient( new \Stripe\HttpClient\CurlClient([CURLOPT_SSL_VERIFYPEER => 0]) );

$stripe = new \Stripe\StripeClient([ 'api_base' => 'https://localhost:12112', 'api_key' => 'sk_test_***************************************************************************************************' ]);

Hopefully that saves some other people some work in the future.

Unfortunately because none of the POST data is saved when creating a connected account things like the metadata didn’t come through from the mock-server, but it does from the actual API, so there’s some catching up for them to do. But overall it should make it easier for me to test my code.


By Michael Kubler

Photographer, cinematographer, web master/coder.

Leave a comment

Your email address will not be published. Required fields are marked *