Skip to content

Instantly share code, notes, and snippets.

@davewardle
Last active December 23, 2016 11:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davewardle/b32510e840f000482328d311b7273183 to your computer and use it in GitHub Desktop.
Save davewardle/b32510e840f000482328d311b7273183 to your computer and use it in GitHub Desktop.
Basic Stripe Checkout example
<?php
/*
Class set initialisation etc
Include stripe-php/init.php
.
.
.
*/
public static function charge_card() {
// token is set in class initialisation
// basic WordPress nonce check - prevents reload
if ( self::$token && wp_verify_nonce( $_POST['treat-nonce'], 'charge_card' ) ) {
// Get the credit card details submitted by the form
// ..
// Data validation
// ..
// Set secret key for correct environment
// ..
// Create new customer (Optional)
$new_customer = \Stripe\Customer::create( [
'email' => $_POST['stripeEmail'],
'card' => $token,
] );
// Create the charge on Stripe's servers - this will charge the user's default card
try {
$charge = \Stripe\Charge::create( [
'amount' => $amount, // amount in pence, again
'currency' => $currency, // eg GBP
'customer' => $new_customer['id'], // if you created customer above
'description' => $description, // order title
'metadata' => $meta, // array of custom fields
] );
// Add Stripe charge ID to querystring.
// From https://developer.wordpress.org/reference/functions/add_query_arg/:
$query_args = [
'charge' => $charge->id,
'venue' => rawurlencode( $venue ), // Data to be passed to success page (as GET variable)
];
} catch( \Stripe\Error\Card $e ) {
// There was an error in creating the charge
$e = $e->getJsonBody();
// Add failure indicator to querystring.
$query_args = [
'charge' => $e['error']['charge'],
'charge_failed' => true,
];
}
unset( $_POST['stripeToken'] );
self::$token = false;
// Redirect user to success page (or error page)
$redirect_url = esc_url_raw( add_query_arg( $query_args, $redirect ) );
wp_redirect( $redirect_url );
exit;
}
}
/*
Other utitlity functions, etc
.
.
.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment