March 25, 2015 5:54 pm

How to Integrate Stripe Payment Gateway in PHP

Integrating payments with Stripe is easy. You would need a quick registration on http://www.stripe.com, after which you can use the test version of the Stripe API until your web app is deployed and the live version afterwards. Stripe is responsible for processing and keeping clients’ credit/debit card data so no information of essence would be stored on your server and you would not have to comply with all the rules that come with storing credit/debit cards.
How to Integrate Stripe Payment Gateway in PHP

[wpdm_file id=131]DEMO

Let’s start integration:

Step 1.

Create account on https://dashboard.stripe.com/register.

Signup on stripe

Step 2.

Now login to your account and go to Account Settings -> API Keys.

Stripe dashboard

Stripe dashboard api keys

Step 3.

Edit charge.php file and replace with your Secret Key

try {
  require_once('Stripe/lib/Stripe.php');
  Stripe::setApiKey("secret_key_here"); //Replace with your Secret Key

  $charge = Stripe_Charge::create(array(
  "amount" => 1500,
  "currency" => "usd",
  "card" => $_POST['stripeToken'],
  "description" => "Charge for Facebook Login code."
));

Edit index.php file and replace with your Publishable Key

<script
    src="https://checkout.stripe.com/checkout.js" class="stripe-button"
    data-key="publishable_key_here" // Replace with your Publishable key
    data-image="favicon.png"
    data-name="PHPGang"
    data-description="Download Script ($15.00)"
    data-amount="1500">
</script>

The test version does not entail actual transfer of funds and you can teste transfer if you have set up everything necessary to charge a customer by entering the following credit card number: 4242424242424242.

The only thing you would have to worry is Man-in-the-middle attacks and that is why Stripe highly recommends using HTTPS but no data about a card will be stored in your server.

First, we create a basic static web page and create a form that includes a script from Stripe (Checkout.js).

main page stripe integrated

This script will create a button which when clicked would urge the users to enter an email, credit/debit card number and optionally choose to remember them.

We also set several variables.

Data-key would hold your publishable key, data-image would hold a link to your company’s logo, data-name would hold the company’s name and data-description – the description of the product being bought. Data-image, data-name and data-description will be shown when users click on the button created by Checkout.js and will make the modal feel like customers are in your site (they are optional but highly recommended).

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Payments using Stripe</title>	
</head>
<body>
<h1>Buy Facebook login Script</h1>
<p>Price: 15.00$</p>
<p>Name: How to Login with Facebook Graph API in PHP</p>

<form action="charge.php" method="POST">
  <script
    src="https://checkout.stripe.com/checkout.js" class="stripe-button"
    data-key="publishable_key_here" // your publishable keys
    data-image="logo.png" // your company Logo
    data-name="PHPGang.com"
    data-description="Download Script ($15.00)"
    data-amount="1500">
  </script>
</form>

</body>
</html>

Here is an image of the modal that this code displays:

stripe fill charge form and buy

When the users fill out the modal and click on “Pay …” they will be redirected to the action attribute of the form, which is “charge.php” in this case. Thus, in charge.php we will actually retrieve 15$ from the client’s card. When redirecting to the form’s action attribute you would have two variables that you could use -> $_POST[‘stripeEmail’] (you could use it to send an email to the customer after a purchase or whatever) and $_POST[‘stripeToken’] (which is used for retrieving funds from the customer in the script displayed after form submission). Of course, this is considering our form’s method attribute is set to POST.

Note that the last two digits of data-amount are actually the cents. 1500 is equal to $15.00 and 15000 is equal to $150.00.

In the script responsible for changing, we load the Stripe library which is available in download code or it could be downloaded at: https://github.com/stripe/stripe-php/releases or set up using Composer: https://stripe.com/docs/libraries.

require_once('Stripe/lib/Stripe.php');

Afterwards we set our secret API key using the static method setApiKey of the Stripe class:

Stripe::setApiKey("secret_key_here");

Afterwards, we actually charge the customer 15.00 bucks:

We set up a try and catch block. In the try block we attempt to charge the customer:

  $charge = Stripe_Charge::create(array(
  "amount" => 1500,
  "currency" => "usd",
  "card" => $_POST['stripeToken'],
  "description" => "Charge for Facebook Login code."
));

We tell Stripe the currency we want the 15.00 bucks to be in, we give the token received from the Checkout.js script when the user entered his data and provide a description of the charge.

Now, we are done and could execute any code that we want executed after a purchase has been made,we just place it below the $charge variable, it will be executed only if the payment has been successful. (no exceptions were thrown when charging)

Here is the whole charge.php file:

<?php

//let's say each article costs 15.00 bucks

try {
  require_once('Stripe/lib/Stripe.php');
  Stripe::setApiKey("secret_key_here"); //Replace with your Secret Key

  $charge = Stripe_Charge::create(array(
  "amount" => 1500,
  "currency" => "usd",
  "card" => $_POST['stripeToken'],
  "description" => "Charge for Facebook Login code."
));
	//send the file, this line will be reached if no error was thrown above
	echo "<h1>Your payment has been completed. We will send you the Facebook Login code in a minute.</h1>";


//you can send the file to this email:
echo $_POST['stripeEmail'];
}
//catch the errors in any way you like

catch(Stripe_CardError $e) {
	
}


catch (Stripe_InvalidRequestError $e) {
// Invalid parameters were supplied to Stripe's API

} catch (Stripe_AuthenticationError $e) {
// Authentication with Stripe's API failed
// (maybe you changed API keys recently)

} catch (Stripe_ApiConnectionError $e) {
// Network communication with Stripe failed
} catch (Stripe_Error $e) {

// Display a very generic error to the user, and maybe send
// yourself an email
} catch (Exception $e) {

// Something else happened, completely unrelated to Stripe
}
?>

Here is what happens when a payment has been successful:

Stripe Card charged sucessfully

Author Ivan Dimov

Ivan is a student of IT, a freelance web designer/developer and a tech writer. He deals with both front-end and back-end stuff. Whenever he is not in front of an Internet-enabled device he is probably reading a book or traveling. You can find more about him at: http://www.dimoff.biz. facebook, twitter


Tutorial Categories:

49 responses to “How to Integrate Stripe Payment Gateway in PHP”

  1. Programmer says:

    Hi!
    Please, can you tell me which editor do you use to edit php files? Thanks for the great tutorial! 🙂

  2. zara says:

    Hi!
    I followed up your tutorial but i got following fatal error. could you please help me?

    • Huzoor Bux says:

      Facing this issue because of localhost try to run this code on live server.

      • zara says:

        thnx for reply..I am a beginner in PHP . i dont have any   stipe account. and i cant run this code .plz tel me way to run this code on test mode

        #yiv8969097938 a:hover, #yiv8969097938 a:hover span {color:#1188d2!important;}#yiv8969097938 .yiv8969097938button-cta:hover {color:#ffffff!important;background-color:#1188d2!important;}#yiv8969097938 .yiv8969097938button-cta:hover span {color:#ffffff!important;}#yiv8969097938 #yiv8969097938outlook a {padding:0;}#yiv8969097938 body {width:100% !important;}#yiv8969097938 .yiv8969097938ReadMsgBody {width:100%;}#yiv8969097938 .yiv8969097938ExternalClass {width:100%;display:block;}#yiv8969097938 @media screen and (){#yiv8969097938 html {}#yiv8969097938 .yiv8969097938content {width:100%;}#yiv8969097938 table {border-collapse:collapse;}#yiv8969097938 h2.yiv8969097938headline {font-weight:700;font-size:20px!important;margin-bottom:5px;}#yiv8969097938 .yiv8969097938button-cta {display:block!important;padding:0!important;}#yiv8969097938 div.yiv8969097938header {padding-top:20px;}#yiv8969097938 div.yiv8969097938footer {padding-bottom:20px;}}#yiv8969097938 #yiv8969097938 p.yiv8969097938mod-tools a:hover {color:white!important;background:#8c989f!important;}#yiv8969097938 @media screen and (){#yiv8969097938 td.yiv8969097938avatar, #yiv8969097938 td.yiv8969097938spacer {width:38px!important;}#yiv8969097938 td.yiv8969097938avatar img, #yiv8969097938 td.yiv8969097938spacer img {width:28px!important;}}”Facing this issue because of localhost try to run this code on live server.” | |
        | |  Settings | |
        |   |

        | |

        | |
        |
        A new comment was posted on phpgang
        |
        | |
        |
        | |
        Huzoor Bux
        Facing this issue because of localhost try to run this code on live server. 1:04 p.m., Thursday May 28 | Other comments by Huzoor Bux |   |
        |
        |   | Reply to Huzoor Bux |   |

        |
        |   |

        |

        | Huzoor Bux’s comment is in reply to zara: |
        |   |
        | | Hi!
        I followed up your tutorial but i got following fatal error. could you please help me?Read more |
        |
        | |

        | |

        | |
        | You’re receiving this message because you’re signed up to receive notifications about replies to disqus_52DUgyDx6v. You can unsubscribe from emails about replies to disqus_52DUgyDx6v by replying to this email with “unsubscribe” or reduce the rate with which these emails are sent by adjusting your notification settings. | | |

        | |

  3. Muhammad Babar Zaman says:

    Hello Sir,

    This was Awesome thing ever i searched on internet.

    Sir I wish to follow dynamic prices. How i can do it. In your Tutorial we can only process a fixed payment. But i want to get prices from my database already saved. I use $price = $row[‘price’]; to call price from Database.

    $charge = Stripe_Charge::create(

    array(

    “amount” => $price, // I write this price veriable here but it dont process payment But when i add a fixed price then it process payment.. What should i do.

    “currency” => “usd”,

    “card” => $_POST[‘stripeToken’],

    “description” => ‘This is Different Thing’

    )

    );

    Please reply me so that i can fix my issue.

  4. Mahmoud says:

    you are one of the best in the web so far.

  5. Mahmoud says:

    I wish you can make a video lessons, so you can share your knowledge by videos

  6. Thiru says:

    sir, can i use indian bank account in stripe?

  7. mehedihassan121 says:

    Many many thanks, after 2 days i fixed my stripe Payment Methods .

  8. mehedihassan121 says:

    Many many thanks, after 2 days i fixed my stripe Payment Methods .

  9. sammy says:

    how to add shipping and billing address in this stripe gateway

  10. DIVYA NARAYANAN says:

    how can I retrieve funding parameter from saved stripe card?

  11. Shubham says:

    Parse error: syntax error, unexpected T_STRING Stripe/lib/Stripe.php on line 3

    please help

  12. siva says:

    Hi

    Could you give me wordpress format…

  13. siva says:

    Hi

    Could you give me wordpress format…

  14. siva says:

    Hi

    Could you give me wordpress format…

  15. siva says:

    Hi

    Could you give me wordpress format…

  16. siva says:

    Hi

    Could you give me wordpress format…

  17. Varun joshi says:

    Hi i want to transfer stripe money to other bank account.Is it possible ?.

  18. Avinash Tripathi says:

    Hi thanks for the code.
    Can you tell me how can i use refund ?
    i’m using
    Stripe::setApiKey($stripe_secret_key);
    $ref = $charge->refunds->create(array(‘amount’ => 100));

    i’m unable to understand that how can i use “$charge “?
    please help me out

  19. avinash says:

    Hi,

    i use stripe payment gateway but give this error.

    Class ‘StripeStripe’ not found in.
    Please any help me.

    Thank’s

  20. Rajeev Kumar says:

    How do we pay recurring payment by stripe gateway

  21. avinash says:

    Please tell me how to integrate custom stripe payment gateway in codeigniter.

  22. Mayur Pande says:

    How would I add an additional charge button and get the total of both of the charges. So for example, I have one button that charges for a t-shirt and another optional postage and packaging but it would then add the two charges up and charge for that. Is this possible?

  23. kannu Priya says:

    please help me to make transfer as well while PAy Now to bank account I set for transfer

  24. Faysal Maqsood says:

    i have integrate this stripe API all works fine in test account but
    when i switched to live it show me error everytime “Your card was
    declined.” Somebody please help me out how can i resolve this

  25. Hassan Ali says:

    Thanks for sharing, it is helpful, but can somebody guide me that when i turned my account from test to live, it wanted me to activate it, but country doesn’t shows Pakistan? how to tackle it?

  26. Aaron Bennett says:

    Thank you, this is cheaper than moonclerk and I am getting fed up trying to figure out how to add stripe to my websites!

  27. Nadia Kerr says:

    Thank you for sharing this. Much more helpful that the documentation on Stripes website. I went around in circles on their website. Your test files worked perfectly on my server and then I ammended them to integrate with my code as required. The only thing I noticed is the Stripe folder differs from the current Stripe release package. When I tried updating the folder to the latest package your code didnt work. Not sure why. :-S I just dont like using older package content if I can help it.

  28. Hkm Sadek Hossain says:

    How can I create a monthly subscription charge?

  29. Jeya Priya says:

    How do we perform recurring payment in stripe?

  30. bhavesh says:

    Hi sir,
    this module can’t download

  31. Bleron Spahiu says:

    great

  32. Raja Das says:

    Couldn’t able to download the code :'(

  33. Asimsagir Abbasi says:

    Please let me know about refund functionality with refund stripe API..

  34. Manpreet Kumar says:

    I am facing a Problem with your site I am not able to Subscribe my Email with you. That is why i am not able to download any code from your site. Please solve this issue as soon as possible

  35. Ashish says:

    Hello everyone,
    i am new in stripe and i want to create users ,card and get list of all created users and cards through stripe apis in php. How i integrate?

  36. Anil says:

    What happens next? What return values do you get so you can update your own database with a successful transaction and give access? Is there a “webhook” for that/

Leave a Reply

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