Introduce to Stripe API, simple PHP + WordPress example

The example will be a WordPress website where you can buy WordPress plugins (like mine) and where user registration is allowed. Step 1. HTML form. Everything begins with the form, right? Actually there are no required fields (except card information) but you can specify emails for new customers if you want the code to send […]

November 30, 2015

The example will be a WordPress website where you can buy WordPress plugins (like mine) and where user registration is allowed.

Step 1. HTML form.

Everything begins with the form, right? Actually there are no required fields (except card information) but you can specify emails for new customers if you want the code to send plugins on it.

<form id="pluginpurchase" action="<?php echo get_stylesheet_directory_uri() ?>/pay.php" method="POST">
 
	<!-- card information fields, no "name" attributes, so, our server won't receive card information -->
	<input type="text" size="20" data-stripe="number" placeholder="Card number" required />
	<input type="text" size="4" data-stripe="cvc" placeholder="Security code" required />
	<input type="text" size="2" data-stripe="exp-month" placeholder="Exp: Month" required />
	<input type="text" size="4" data-stripe="exp-year" placeholder="Exp: Year" required />
 
	<!-- if user is logged in, we get the email from his profile -->
	<?php 
		$email = '';
		if( is_user_logged_in() ) {
			$user = get_user_by('id', get_current_user_id() );
			$email = $user->user_email;
		}
	?>
	<input type="email" name="email" value="<?php echo $email ?>" required />
 
	<!-- plugin ID -->
	<input type="hidden" name="plugin_id" value="<?php the_id() ?>" />
 
	<button>Get this plugin</button>
</form>

Step 2. Get Stripe token

Enqueue Stripe Library stripe.js

The next code is for your theme functions.php file.

function rudr_enqueue_stripe_js(){
	// wp_enqueue_script('jquery'); // enqueue jQuery if you haven't done it yet
	wp_enqueue_script('stripe', 'https://js.stripe.com/v2/');
}
 
add_action( 'wp_enqueue_scripts', 'rudr_enqueue_stripe_js' );

Add token as a hidden field before form submit

You can insert this code after wp_head() section. Do not forget about <script> tags then.

Stripe.setPublishableKey('pk_YOUR_STRIPE_PUBLISH_KEY'); // you can get it in Stripe account settings
 
function createTokenHandler(status, response) {
	var plugin_form_purchase = jQuery('#pluginpurchase');
	if (response.error) {
		// Show the errors
		alert(response.error.message);
		// Enable the button
		plugin_form_purchase.find('button').prop('disabled', false);
	} else {
		var token = response.id;
		// Add the token to the form so it gets submitted to your server
		plugin_form_purchase.append(jQuery('<input type="hidden" name="stripeToken" />').val(token));
 		// And submit
		plugin_form_purchase.get(0).submit();
	}
};
 
jQuery(function($) {
	$('#pluginpurchase').submit(function(event) {
		var plugin_form_purchase = $(this);
		// Disable the submit button to prevent repeated clicks
 		plugin_form_purchase.find('button').prop('disabled', true);
		// Create the token hidden field
		Stripe.card.createToken(plugin_form_purchase, createTokenHandler);
		// Prevent default form submitting
		return false;
	});
});

Step 3. Process the form

First of all connect all necessary Stripe PHP classes. You can select some of them or just require init.php file.

require_once( dirname(__FILE__) . '/../../../../wp-load.php' );
require_once( dirname(__FILE__) . '/stripe-php/init.php' );
 
$plugin_id = $_POST['plugin_id'];
 
/* if your plugin price looks like 9.59, then you need to *100 it */
$price = get_post_meta( $plugin_id, '_plugin_price', true ) * 100;
/*
 * We can specify Stripe secret API key at the same time
 */
$secret = 'sk_YOUR_STRIPE_SECRET_KEY';  // you can get it in Stripe account settings
\Stripe\Stripe::setApiKey( $secret );
 
try {
	if (!isset($_POST['stripeToken']))
		throw new Exception('The Stripe Token was not generated correctly');
	\Stripe\Charge::create( array( 'amount' => $price, 'currency' => 'usd', 'source' => $_POST['stripeToken'], 'description' => 'Plugin (ID ' . $plugin_id . ') download for ' . $_POST['email'] ) );
 
	$success = 'Your payment was successful.';
	/* 
	 * do some stuff here - you can send the plugin by email or force download it
	 */
} catch (Exception $e) {
	/*
	 * if something went wrong
	 */ 
	echo $e->getMessage();
}

Only the best of WordPress

once a week, no spam

Leave your question or feedback

phpjsHTMLCSSSQLCode
Please, enter a comment
Please, enter a name
Incorrect email