Skip to content

Instantly share code, notes, and snippets.

@davewardle

davewardle/basic-stripe-example.php Secret

Last active Dec 23, 2016
Embed
What would you like to do?
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
You can’t perform that action at this time.