Stripe: Validating Publishable and Secret API Keys

spg picture spg · May 5, 2013 · Viewed 11.9k times · Source

I'm builiding a web application that allows our users to sell tickets for music shows. In order to handle the payments between ticket buyers and show instigators, I use Stripe. Basically, the show instigator creates his show's page on my application, and the users can buy tickets for this show.

In order to create a show, the instigator fills in a form (Show's name, show's date, where the show will take place, what bands will be playing, etc.) This form also requires the show instigator to provide both his Publishable and Secret Stripe keys. My app uses both these tokens to retrieve credit cart information (on the client side) and process payments (on the server side).

The problem is, I want to make sure that show instigators provide valid and existing Stripe keys. I wouldn't want my users to stumble across payments errors because show instigators did not provide valid Stripe keys.

So, my question is: How can I verify that Publishable and Secret keys are valid and existing? What's the best strategy to achieve this? Thanks!

Answer

Etienne Martin picture Etienne Martin · Mar 12, 2014

Got it!

To validate your publishable keys you need to ask stripe for a new token using cURL. If the given key is invalid the response will contain an error message starting with "Invalid API Key provided".

Here's an example written in PHP:

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://api.stripe.com/v1/tokens");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "card[number]=4242424242424242&card[exp_month]=12&card[exp_year]=2017&card[cvc]=123");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_USERPWD, $publishableKey . ":");

$response = json_decode(curl_exec($ch),true);

if( curl_errno($ch) ){
    echo 'Error:' . curl_error($ch);
}
curl_close ($ch);

if(substr($response["error"]["message"],0, 24 ) == "Invalid API Key provided"){
    echo "Invalid API Key provided";
}

Same idea for validating your secret keys.