-
-
Save davewardle/b32510e840f000482328d311b7273183 to your computer and use it in GitHub Desktop.
Basic Stripe Checkout example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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