21
votes

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.

3

3 Answers

27
votes

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.

18
votes

You don't need to create tokens with fake credit cards for testing anymore. Stripe now provides a list of pre-made tokens for this purpose :

Stripe docs : Test card numbers and tokens

-3
votes

Easiest way to generate Test Token for Stripe (PURE JS) no PHP required is use below code and run it on local by adding Test keys

    <html>
      <head>
        <title>create stripe  token in js</title>
        <script src="https://js.stripe.com/v3/"></script>
        <style type="text/css">

      .StripeElement {
        background-color: white;
        height: 40px;
        padding: 10px 12px;
        border-radius: 4px;
        border: 1px solid transparent;
        box-shadow: 0 1px 3px 0 #e6ebf1;
        -webkit-transition: box-shadow 150ms ease;
        transition: box-shadow 150ms ease;
      }

      .StripeElement--focus {
        box-shadow: 0 1px 3px 0 #cfd7df;
      }

      .StripeElement--invalid {
        border-color: #fa755a;
      }

      .StripeElement--webkit-autofill {
        background-color: #fefde5 !important;
      }

        </style>    
      </head>
      <body>
        <form action="/charge" method="post" id="payment-form">
            <div class="form-row">
              <label for="card-element">
                Credit or debit card
              </label>
              <div id="card-element">
                <!-- a Stripe Element will be inserted here. -->
              </div>

              <!-- Used to display form errors -->
              <div id="card-errors" role="alert"></div>
            </div>

            <button>Submit Payment</button>
          </form>    
          <textarea style="width:400px; height:200px;" id="stripeToken" placeholder="Stripe token will print here."></textarea>


          <script type="text/javascript">
           // Create a Stripe client
          var stripe = Stripe('pk_test_xpuKHHXWfW9eUw6DlmNZQI5N');

          // Create an instance of Elements
          var elements = stripe.elements();

          // Custom styling can be passed to options when creating an Element.
          // (Note that this demo uses a wider set of styles than the guide below.)
          var style = {
            base: {
              color: '#32325d',
              lineHeight: '18px',
              fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
              fontSmoothing: 'antialiased',
              fontSize: '16px',
              '::placeholder': {
                color: '#aab7c4'
              }
            },
            invalid: {
              color: '#fa755a',
              iconColor: '#fa755a'
            }
          };

          // Create an instance of the card Element
          var card = elements.create('card', {style: style});

          // Add an instance of the card Element into the `card-element` <div>
          card.mount('#card-element');

          // Handle real-time validation errors from the card Element.
          card.addEventListener('change', function(event) {
            var displayError = document.getElementById('card-errors');
            if (event.error) {
              displayError.textContent = event.error.message;
            } else {
              displayError.textContent = '';
            }
          });

          // Handle form submission
          var form = document.getElementById('payment-form');
          form.addEventListener('submit', function(event) {
            event.preventDefault();

            stripe.createToken(card).then(function(result) {
              if (result.error) {
                // Inform the user if there was an error
                var errorElement = document.getElementById('card-errors');
                errorElement.textContent = result.error.message;
              } else {
                // Send the token to your server
                console.log(result);
                document.getElementById('stripeToken').value=result.token.id;
              }
            });
          });

        </script>
      </body>
    </html>