Generate a Stripe test card token for testing

harryg picture harryg · Jan 5, 2016 · Viewed 20.9k times · Source

I am using Stripe in my app. I want to write an integration test for placing a payment that checks Stripe that a payment was created. I'm using Stripe.js.

In my test I need a card token to perform the test charge. Usually this token would be generated client side with stripe.js and sent in the request to perform the charge. As this is a server-side only test is there some way I can generate a token from within the test?

For reference the test would be something like this (uses php but the principle is the same):

/** @test **/
public function it_creates_a_charge()
{
    $order = factory(Order::class)->create();
    $stripe_token = Stripe::generateToken([
                                          'card' => '4242424242424242'
                                          'exp'  => '04/2017',
                                          'cvc'  => '123'
                                          ]); // does not exist afaik

    $response = $this->post('charges/store', [
                'stripe_token' => $stripe_token,
                'order_id' => $order->id,
                //etc
                ]);

    // assertions...
}

Essentially I'm asking if there's something within the Stripe API that allows server-side token generation.

Answer

ceejayoz picture ceejayoz · Jan 5, 2016

Stripe provides an API call to create tokens from the server:

\Stripe\Stripe::setApiKey("sk_test_BQokikJOvBiI2HlWgH4olfQ2");

\Stripe\Token::create(array(
  "card" => array(
    "number" => "4242424242424242",
    "exp_month" => 1,
    "exp_year" => 2017,
    "cvc" => "314"
  )
));

edit: Stripe now provides ready-to-use test tokens like tok_visa at https://stripe.com/docs/testing#cards.