Skip to content

Instantly share code, notes, and snippets.

@bkrausz
Forked from maccman/charge.php
Last active September 24, 2021 17:13
Show Gist options
  • Star 34 You must be signed in to star a gist
  • Fork 14 You must be signed in to fork a gist
  • Save bkrausz/a76f9d7a9b446337d470 to your computer and use it in GitHub Desktop.
Save bkrausz/a76f9d7a9b446337d470 to your computer and use it in GitHub Desktop.
Please see https://stripe.com/docs/checkout/php for updated code examples
// Please see https://stripe.com/docs/checkout/php for updated code examples
@harshadkhade
Copy link

Warning: require_once(vendor/autoload.php): failed to open stream: No such file or directory in ,
Fatal error: require_once(): Failed opening required 'vendor/autoload.php
i have this error ,what is the solution

@delpino73
Copy link

I include the init file instead of autoload.php which seems to work (require './stripe-php/init.php';)
Is there a reason this isn't a good idea?

@jmarus
Copy link

jmarus commented May 31, 2015

I agree, it would be nice to get around having to use composer. It used to work that way. Why do we have to reply on Composer now?

@alteredorange
Copy link

Does $email = $_POST['stripeEmail']; no longer work? I can't find any documentation on this anywhere, but it's not working on my current setup!

@willcate
Copy link

I was able to set it up w/o Composer. Manually download the latest PHP libraries (2.3.0 at this moment) and put the folder (stripe-php-2.3.0) on the same level as your PHP files. Then put

require_once('stripe-php/init.php');

... wherever needed. Works like a charm.

@thepcdoctor2012
Copy link

I really hate to sound like a noob here but can someone do a youtube walkthrough my problem is I can't figure out where to put the code I have already uploaded the stripe-php-2.3.0 folder to my server. Now I am trying to figure out where to put the above code index,config and charge.

@gatorvet01
Copy link

I've followed the directions verbatim and the code crashes. I get the token, but then the code breaks on $customer = \Stripe\Customer::create(array(
'email' => 'customer@example.com',
'card' => $token
));
What am I missing?

@DanielBickley
Copy link

I'm able to set this up using Composer or the straight require_once('stripe-php/init.php') method. However, I'm just wondering if anyone here can provide any input on which method is best. For example, does the straight require_once('stripe-php/init.php') method load in ALL the classes regardless of what is used vs the Composer autoloader only loading in called classes as you're using them? If the latter, then I'd think Composer is the going to be the way in terms of speed and processing a given page. Is anyone here able to verify this?

@razaumer
Copy link

i am getting Fatal error: Class 'Stripe_ApiResource' not found how to resolve this even i placed all file in correct location

@stumpfl335
Copy link

What is the significance of 'email' => 'customer@example.com' ?

@madikarizma
Copy link

@stumpfl335 Stripe requires an email address to create a new customer record. In this example both a charge and customer record are being created—primarily used to create a relationship customer and charge data.

@daniel-lucio
Copy link

Is it valid to say:
$currency = $_POST['currency'];
from the charge.php file?

@ajck
Copy link

ajck commented Jan 30, 2016

You don't need to use Composer (relief!) - the PHP API docs on github offer a manual method:
https://github.com/stripe/stripe-php#manual-installation

@mohamamdkalim
Copy link

After Getting the new updated version 3.9.2

got an error in config.php so i just replace

require_once('./lib/Stripe.php');
with this:
require_once('stripe-php/init.php');

work awesome thanks... !!

@ralf00
Copy link

ralf00 commented Jun 14, 2016

Sorry, maybe i didn't understand something... i'm integrating Stripe with a Custom Ecommerce engine, i don't understand how to do the last step.
I write the form calling the .js files, it asks me a "charge.php" page to execute the transaction. Of course, speaking about an ecommerce website i will have that page that handle all the stripe transactions.
My question is that: how can I get that stripeToken to match it with my current order/transaction? If my charge.php is called with that parameter, that parameter does not mean anything for me, because i couldn't save it referred to an order in this way.

I try to clarify using an example:
my user has done the order nr 123, i show the form (actions is charge.php), he does the stripe procedure, but when can i get that stripeToken back to store it to my 123 order on my database?
Of course i can put charge.php?order=123 or an hidden field name=idorder on that form but it makes useless that stripeToken and malicious user can easily modify it.

I hope my doubt is clear enough, thank you.

@mateuszjarzewski
Copy link

mateuszjarzewski commented Aug 30, 2016

@ghost You're not a noob, composer is evil crapware from hell full of bugs and security holes...

@JonnyVaine
Copy link

JonnyVaine commented Sep 29, 2016

Hi there! How do I use the email address a customer has input as the customer email within the dashboard?

My form is here: http://www.nw1dentalcare.co.uk/pay-for-deposit/

My code is below:

<script src="https://checkout.stripe.com/checkout.js" ></script> <div class="payment-form"> <h2>Pay Your Deposit</h2> <div class="two-col"> <input name="patient_first_name" class="forms" type="text" placeholder="First Name"> <input name="patient_surname" class="forms" type="text" placeholder="Surname"> </div> <input name="patient_email" class="forms" type="text" placeholder="Your Email"> <input name="mobile_number" class="forms" type="text" placeholder="Mobile Number"> <script> var mobile_number = ''; var handler = StripeCheckout.configure({ key: 'pk_test_qF8hhUXpl4ufmGByYKqfvBEN', // publishable key token: function(token, args) { chargeToken(token, args); } }); jQuery(document).on('click', '#submitPayment', function(e) { var mobile_number = jQuery('input[name=mobile_number]').val(); var patient_first_name = jQuery('input[name=patient_first_name]').val(); var patient_surname = jQuery('input[name=patient_surname]').val(); var patient_email = jQuery('input[name=patient_email]').val(); if(patient_first_name == '') { alert("Your first name can't be left blank!"); return false; } if(patient_surname == '') { alert("Your surname can't be left blank!"); return false; } if(patient_email == '') { alert("Your Email can't be left blank !"); return false; } var regex = /^[0-9]\d*(((,\d{3}){1})?(.\d{0,2})?)$/; if(mobile_number == "") { alert("Mobile Number can't be left blank !"); return false; } if (patient_first_name !== '' && patient_surname !== '' && mobile_number !== '' && patient_email !== '') { // Open Checkout with further options handler.open({ name: 'Appointment Deposit', email: patient_email, description: patient_first_name + ' ' + patient_surname + ' | ' + mobile_number, amount: 2500, currency: 'GBP', image: 'http://www.nw1dentalcare.co.uk/wp-content/uploads/2016/09/logo-square.png' }); } e.preventDefault(); }); // Close Checkout on page navigation jQuery(window).on('popstate', function() { handler.close(); }); function chargeToken(token, addresses) { var mobile_number = jQuery('input[name=mobile_number]').val(); var patient_first_name = jQuery('input[name=patient_first_name]').val(); var patient_surname = jQuery('input[name=patient_surname]').val(); var patient_email = jQuery('input[name=patient_email]').val(); jQuery.ajax({ type: 'POST', url: 'http://www.nw1dentalcare.co.uk/stripe/charge.php', data: {tokenid: token.id, email: patient_email, amount: 25, description: patient_first_name + ' ' + patient_surname + ' | ' + mobile_number}, dataType: 'json', success: function(response) { if (response['type'] == "1") { alert('Payment successfully made! Call us now to set an appointment.'); } else { alert('Payment could not be processed. Please try again.'); location.reload(); } } }); } </script> <button id="submitPayment" class="go-btn">Pay Your £25 Appointment Deposit</button> </div>

I've included the files above too!

It's also not accepting the test card details mentioned here: https://stripe.com/docs/testing#cards

@zanderwar
Copy link

If you don't know "how-to-code", I wouldn't advise diving into the deep end that is dealing with payment gateways. Especially with the comment that thought 5000cents was $5....

@sradhaa
Copy link

sradhaa commented Dec 8, 2016

I am getting this error {"error":"No such token: card_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(invalid_request_error)"}

@openconcept
Copy link

openconcept commented Jan 1, 2017

5000 cents is $50. The commenter mspivak pointed out that on the last line in charge.php it says $5, not $50. This was apparently misunderstood by subsequent commenters, who got it turned around. And the incorrect amount is still there as "Successfully charged $5" in the charge.php example.

@jcaruso001
Copy link

jcaruso001 commented Jan 19, 2017

Why is this all hard coded? Why isn't there any error handling for declined cards? This is very misleading...

For those of you looking for something with some error handling for declined cards just surround it in a try catch...

		try {
		
			\Stripe\Stripe::setApiKey("....");

			// Charge the user's card:
			$charge = \Stripe\Charge::create(array(
			"amount" => $Request->Get('amount'),
			"currency" => "usd",
			"description" => $Request->Get('description'),
			"source" => $Request->Get('charge_id'),
			));

		} catch (Exception $e) {
			//TODO: Error Handeling logic.
		}

@Bhlowe
Copy link

Bhlowe commented Apr 24, 2017

Someone at Stripe should update the charge.php source code and then reply to the comments.

  1. Add Error handling
  2. Change $5 to $50
  3. Use 'email' => $_POST['stripeEmail'], instead of 'email' => 'customer@example.com',

I added the following to charge.php to help show what was returned:

echo "post: <pre>"; print_r($_POST) ;  echo "</pre>";
echo "customer: <pre>"; print_r($customer) ;  echo "</pre>";
echo "charge: <pre>"; print_r($charge) ;  echo "</pre>";

The documentation for config.php should be changed to show that you can use init.php instead of autoload.php for those that don't use or know how to use composer.

@hemant-tivlabs
Copy link

The piece of code:

$customer = \Stripe\Customer::create(array(
      'email' => 'customer@example.com',

should actually be:

$customer = \Stripe\Customer::create(array(
      'email' => $_POST['stripeEmail'],

as that is the same email as submitted by the customer, and gets posted back with "stripeToken" and "stripeTokenType".

@EricKing1
Copy link

Someone needs to update the example. Having problems with the charge amount this does NOT work. I have tried both, what is the element name to capture?
$charge = \Stripe\Charge::create(array( 'customer' => $customer->id, 'amount' => $_POST['stripeAmount'] or $_POST['data-amount'], 'currency' => 'usd' ));

@emiled
Copy link

emiled commented May 29, 2017

This example does not work! 'card' is the wrong parameter, it should be 'source'

inside charge.php:

this:

  $customer = \Stripe\Customer::create(array(
      'email' => 'customer@example.com',
      'card'  => $token
  ));

should be:

  $customer = \Stripe\Customer::create(array(
      'email' => 'customer@example.com',
      'source'  => $token
  ));

@tegarkurniawan
Copy link

I am getting this error {"error":"No such token: card_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(invalid_request_error)"}

@JoysonAnto
Copy link

Hi Stripe Bitcoin team,
I need to charge the amount that varies dynamically each time how to manage that data-amount="5000"

 <script
			src="https://checkout.stripe.com/checkout.js" class="stripe-button"
			data-key="<?php echo $stripe_code['publishable_key']; ?>"
			data-amount="<?php echo $price; ?>"
			data-name="OfficeBnb"
			data-description="2 widgets (<?php echo  $this->session->userdata('currency_s').($price); ?>) Cents"
			data-image="images/logo/<?php echo $this->config->item('logo_image');?>"
			data-label="Pay with Card or Bitcoin"
			data-locale="auto"
			data-currency="<?php echo $this->session->userdata('currency_type'); ?>"
			data-bitcoin="true">
		</script>

@terrimorgan
Copy link

Same comment as @Bhlowe back in April ... updates to the examples are overdue.

Same comment as @JoysonAnto needs to be an option to get a variable amount. Can't use this with a store -- unless attached directly to products that can only be purchased individually at a set price.

Same for the Requirement to add "Composer" ..."assumes you’ve installed the Stripe PHP library via Composer. ..." which also assumes quite a bit.

For what is touted as "super simple" the implementation seems to be much more complicated than it should need to be. Granted, I'm not an expert, my skills are ok. For those of us who might want to use Stripe but don't live and breathe code every day the claim of "as little as one line of client side code" is seriously misleading. There's quite a bit more required to implement than "one line of client side code."

@ovvval
Copy link

ovvval commented Aug 10, 2017

This is really awesome. Straight to the point. I love it.

@aldcar2002
Copy link

How can I get the confirmation number or transaction number of the payment ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment