Skip to content

Instantly share code, notes, and snippets.

@luk3thomas
Created February 16, 2013 02:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luk3thomas/4965229 to your computer and use it in GitHub Desktop.
Save luk3thomas/4965229 to your computer and use it in GitHub Desktop.
form.html is the payment form. main.js is the javascript to intercept the payment form and encode the credit card. payment.php charges the card and sends out any emails.
<table class="team sponsor">
<thead>
<tr>
</tr>
</thead>
<tr>
<td>Business Name</td>
<td><input class="name" type="text" value="" name="s_name" /></td>
</tr>
<tr>
<td>Address Line 1</td>
<td><input class="name" type="text" value="" name="s_addy1" /></td>
</tr>
<tr>
<td>Address Line 2</td>
<td><input class="name optional" type="text" value="" name="s_addy2" /></td>
</tr>
<tr>
<td>City</td>
<td><input class="phone" type="text" value="" name="s_city" /></td>
</tr>
<tr>
<td>Zip</td>
<td><input class="phone" type="text" value="" name="s_zip" /></td>
</tr>
<tr>
<td> <label>Card Number</label></td>
<td> <input type="text" size="20" autocomplete="off" class="card-number"/></td>
</tr>
<tr>
<td> <label>CVC</label></td>
<td> <input type="text" size="4" autocomplete="off" class="card-cvc" /></td>
</tr>
<tr>
<td> <label>Expiration (MM/YYYY)</label></td>
<td>
<input type="text" size="2" class="card-expiry-month" placeholder="MM" />
<span> / </span>
<input type="text" size="4" class="card-expiry-year" placeholder="YYYY" />
</td>
</tr>
</table>
(function($) {
var API_KEY = 'pk_ENqJ6L1zkH01T5WQG29yqnUAHzvTF' ;
/**
* Stripe
* -------------------------------------------- */
$("#payment-form").submit(function(event) {
/**
* Validate the form first
* -------------------------------------------- */
/** Reset errors */
$('.payment-errors .text').text('');
$('.register input[type="text"], .register input[type="email"]').removeClass('error');
var error_count = 0;
$('.register input[type="text"], .register input[type="email"], .register select option:selected').not('.optional').each(function(i, el){
var $el = $(el),
type = $el.attr('type'),
test = validateText( $el.val() ),
email = validateEmail( $el.val() );
if(type == 'email')
test = email;
if(test) {
error_count += 1;
$el.addClass('error');
$('.payment-errors .text').text('Please correct the highlighted fields');
}
});
// disable the submit button to prevent repeated clicks
$('.submit').attr("disabled", "disabled");
/** Bail if validation errors */
if(error_count) {
$('.submit').removeAttr("disabled");
return false;
}
$('.ajax-loading').fadeIn();
// createToken returns immediately - the supplied callback submits the form if there are no errors
Stripe.createToken({
number: $('.card-number').val(),
cvc: $('.card-cvc').val(),
exp_month: $('.card-expiry-month').val(),
exp_year: $('.card-expiry-year').val()
}, stripeResponseHandler);
return false; // submit from callback
});
/**
* Stripe functions
* -------------------------------------------- */
// this identifies your website in the createToken call below
/** Test */
//Stripe.setPublishableKey('pk_SsEYzhfl3yUPTBLwD15hQbk6MsItZ');
/** Live */
Stripe.setPublishableKey( API_KEY );
function stripeResponseHandler(status, response) {
if (response.error) {
// re-enable the submit button
$('.submit').removeAttr("disabled");
// show the errors on the form
$('.ajax-loading').fadeOut(400, function() {
$(".payment-errors .text").html(response.error.message);
});
} else {
var form$ = $("#stripe");
// token contains id, last4, and card type
var token = response['id'];
// insert the token into the form so it gets submitted to the server
form$.append("<input type='hidden' name='stripeToken' value='" + token + "' />");
// and submit
$.ajax({
url: window.base_url + '/wp-content/themes/neptune/payment.php',
type: 'POST',
data: form$.serialize(),
success: function( data ) {
var msg = $.parseJSON(data)
$('.ajax-loading').fadeOut(400, function() {
$('.payment-errors .text').html('<div class="' + msg.code + '">' + msg.message + '</div>');
if(msg.code == 'decline') {
$('.submit').removeAttr('disabled');
$('input[name="stripeToken"]').remove();
}
});
}
})
}
}
})(this.jQuery);
function validateEmail(email) {
var re = /^(@|)$/;
return re.test(email);
}
function validateText(text) {
var re = /^((First |Last |Team )Name||Phone|Email)$/;
return re.test(text);
}
<?php
$API_SECRET = 'xxxxxxxxxxxxxxxxxxxx';
// Load up wordpress
$p = preg_replace( ';(.*)(/wp-content/.*);', '\1', $_SERVER['SCRIPT_FILENAME'] );
include( $p . '/wp-load.php' );
require_once("$p/wp-content/themes/neptune/lib/stripe-php-1.7.1/lib/Stripe.php");
// set your secret key: remember to change this to your live secret key in production
// see your keys here https://manage.stripe.com/account
/** Live */
Stripe::setApiKey( $API_SECRET );
// get the credit card details submitted by the form
$token = $_POST['stripeToken'];
// create a Customer
$customer = Stripe_Customer::create(array(
"card" => $token,
"email" => $team['contact']['email'],
"description" => implode(' ', $team['contact'])
));
// charge the Customer instead of the card
try {
$charge = Stripe_Charge::create(array(
"amount" => $amount,
"currency" => "usd",
"customer" => $customer->id)
);
} catch(Exception $e) {
/** notify the user payment faild */
$return['code'] = 'decline';
$return['message'] = 'Payment not processed:<br> ' . $e->json_body['error']['message'];
switch($e->http_status) {
case 400:
case 402:
$subject = 'Unable to process payment';
$message = sprintf('Payment was failed'
, print_r($e->json_body['error']['message'], true)
, $_POST['type']
);
@mail($to, $subject, $message);
break;
case 401:
case 404:
case 500:
case 502:
case 503:
case 504:
/** email me */
$to = 'me@example.com';
$subject = 'Error processing payment';
$message = print_r( $e );
@mail($to, $subject, $message);
break;
}
echo json_encode($return);
exit;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment