modify to use Checkout form

This commit is contained in:
Nathan Coad
2016-07-21 15:17:11 +10:00
parent cab49b68f5
commit 3e6ea4936b
4 changed files with 269 additions and 139 deletions

View File

@@ -768,6 +768,7 @@ function booking_library() {
'version' => '1.0', 'version' => '1.0',
'js' => array( 'js' => array(
'https://js.stripe.com/v1/' => array(), 'https://js.stripe.com/v1/' => array(),
'https://checkout.stripe.com/checkout.js' => array(),
$module_path . '/booking.stripe.js' => array(), $module_path . '/booking.stripe.js' => array(),
), ),
); );

65
booking.stripe-old.js Normal file
View File

@@ -0,0 +1,65 @@
(function($) {
$(function() {
Stripe.setPublishableKey(Drupal.settings.booking_stripeform.pubkey);
});
Drupal.behaviors.booking_stripeform = {
attach: function(context, settings) {
$("#" + settings.booking_stripeform.form_selector, context).submit(function(e) {
e.preventDefault();
var $form = $(this);
var $obj;
var $submitBtn = $("#edit-submit", context);
settings.booking_stripeform.submitBtnText = $submitBtn.val();
try {
var $ccnum = $(':input[data-stripe="number"]', $form);
var $exp_month = $(':input[data-stripe="exp-month"]', $form);
var $exp_year = $(':input[data-stripe="exp-year"]', $form);
var $cvc = $(':input[data-stripe="cvc"]', $form);
if(!Stripe.card.validateCardNumber($(':input[data-stripe="number"]', $form).val())) {
$obj = $ccnum;
throw "Invalid credit card number";
}
if(!Stripe.card.validateExpiry($exp_month.val(), $exp_year.val())) {
$obj = $exp_month;
throw "Invalid expiration month/year";
}
if(!Stripe.card.validateCVC($cvc.val())) {
$obj = $cvc;
throw "Invalid CVC";
}
} catch(err) {
$.each([$ccnum, $exp_month, $exp_year, $cvc], function(i, e) {
e.addClass('error');
});
$obj.parents('div.control-group').toggleClass('error');
reportError(err, $obj);
return false;
}
$submitBtn.val('Please wait...').attr('disabled', true);
Stripe.createToken($form, stripeResponseHandler);
return false;
});
}
}
var stripeResponseHandler = function(status, response) {
var $form = $("#" + Drupal.settings.booking_stripeform.form_selector);
if (response.error) {
alert(response.error.message);
} else {
// token contains id, last4, and card type
var token = response.id;
// Insert the token into the form so it gets submitted to the server
$('input[name=stripeToken]', $form).val(token);
// and submit
$form.get(0).submit();
}
};
/**
* Uses Bootstrap's popover to alert the user.
*/
function reportError(msg, $el) {
console.log([$el, msg]);
}
}(jQuery));

View File

@@ -10,45 +10,130 @@
* Get the current stripe api public key * Get the current stripe api public key
*/ */
function _booking_get_stripe_public_key() { function _booking_get_stripe_public_key() {
if (variable_get('booking_stripe_testmode', 0) == 1) { if (variable_get('booking_stripe_testmode', 0) == 1) {
return variable_get('booking_stripe_test_public_key', ''); return variable_get('booking_stripe_test_public_key', '');
} }
else { else {
return variable_get('booking_stripe_live_public_key', ''); return variable_get('booking_stripe_live_public_key', '');
} }
} }
/** /**
* Get the current stripe api private key * Get the current stripe api private key
*/ */
function _booking_get_stripe_private_key() { function _booking_get_stripe_private_key() {
if (variable_get('booking_stripe_testmode', 0) == 1) { if (variable_get('booking_stripe_testmode', 0) == 1) {
return variable_get('booking_stripe_test_secret_key', ''); return variable_get('booking_stripe_test_secret_key', '');
} }
else { else {
return variable_get('booking_stripe_live_secret_key', ''); return variable_get('booking_stripe_live_secret_key', '');
} }
} }
/** /**
* Sample Stripe Form. * Helper function to generate paypal form for payments
*/ */
function booking_stripeform_form($form, &$form_state) { function _booking_stripe_form($person, $invoiceid, $amount_owing, $button_text) {
// Let's make sure you have the stripe library installed. $payment_form = drupal_get_form('booking_stripe_form', $person, $invoiceid, $amount_owing, $button_text);
if($path = libraries_get_path('stripe')) { return drupal_render($payment_form);
if(!is_file($path . '/lib/Stripe.php')) { }
form_set_error('form', t('You need to install the stripe library from !link before you can use this form.',
array('!link' => l('here', 'https://stripe.com/docs/libraries')))); function booking_stripe_form($node, &$form_state, $person, $invoiceid, $amount_owing, $button_text) {
} global $event;
} else { $settings = array();
form_set_error('form', t('You need to install the stripe library from !link before you can use this form.', $form = array();
array('!link' => l('here', 'https://stripe.com/docs/libraries'))));
} //get our current path so we can send the user back here if they cancel
//load the main stripe library //$path = isset($_GET['q']) ? $_GET['q'] : '<front>';
libraries_load('stripe');
//set some values for our internal stripe library to help process the form //set some values for our internal stripe library to help process the form
//these will be used by the attached js from booking-strip library to identify which parts of the form to process
// @todo set name and image in the admin page
$setting['booking_stripe'] = array(
'pubkey' => _booking_get_stripe_public_key(),
'form_selector' => str_replace('_', '-', __FUNCTION__),
'name' => 'Study Week',
'image' => '',
);
//attach settings and javascript to the form
$form['#attached'] = array(
'js' => array(
array('data' => $setting, 'type' => 'setting'),
),
'library' => array(
array('booking', 'booking-stripe'),
),
);
//paypal specific settings
$vars = array(
'module' => 'Booking System',
'type' => $event->booking_eventname,
'nid' => $person->nid,
'email' => $person->booking_email,
'description' => $event->booking_eventname . ' ' . $person->booking_price_descrip,
'invoice' => $invoiceid,
'amount' => $amount_owing,
'last_name' => $person->booking_lastname,
'first_name' => $person->booking_firstname,
'token_id' => '',
'token_email' => ''
);
/*
$form['#id'] = 'booking_stripe_form';
$form['#attached']['js'] = array(
array(
'data' => 'https://checkout.stripe.com/checkout.js',
'type' => 'external',
),
array(
'data' => drupal_get_path('module', 'booking') . '/booking.stripe.js',
'type' => 'file',
),
);
*/
//turn the array into a form
foreach($vars as $name => $value) {
$form[$name] = array(
'#type' => 'hidden',
'#value' => $value,
);
};
$form['submit'] = array(
'#id' => 'stripe-submit',
'#type' => 'button',
'#value' => t($button_text),
);
$form['#after_build'][] = 'booking_stripe_add_final_validation';
//watchdog('booking', 'Booking Balance payment: @info', array ('@info' => var_export($form, TRUE)));
return $form;
}
/*
function booking_stripe_form($form, &$form_state, $person, $invoiceid, $amount_owing, $button_text) {
global $event;
$setting = array(); $setting = array();
$form = array();
// Try to load the library and check if that worked.
if (($library = libraries_load('stripe')) && !empty($library['loaded'])) {
// Do something with the library here.
}
else {
//library can be downloaded from https://stripe.com/docs/libraries
form_set_error('form', t('The required stripe library is not installed. Please contact your site adaministrator'));
}
//set some values for our internal stripe library to help process the form
//these will be used by the attached js from booking-strip library to identify which parts of the form to process
$setting['booking_stripeform'] = array( $setting['booking_stripeform'] = array(
'pubkey' => _booking_get_stripe_public_key(), 'pubkey' => _booking_get_stripe_public_key(),
'form_selector' => str_replace('_', '-', __FUNCTION__), 'form_selector' => str_replace('_', '-', __FUNCTION__),
@@ -56,7 +141,6 @@ function booking_stripeform_form($form, &$form_state) {
$form['#attached'] = array( $form['#attached'] = array(
'js' => array( 'js' => array(
array('data' => $setting, 'type' => 'setting'), array('data' => $setting, 'type' => 'setting'),
//drupal_get_path('module', 'booking') . '/booking.stripe.js',
), ),
'library' => array( 'library' => array(
array('booking', 'booking-stripe'), array('booking', 'booking-stripe'),
@@ -69,18 +153,15 @@ function booking_stripeform_form($form, &$form_state) {
); );
$form['amount'] = array( $form['amount'] = array(
'#type' => 'textfield', '#type' => 'hidden',
'#title' => t('Amount to charge'), '#value' => $amount_owing,
'#description' => t('NOTE: Normally, you would calculate amount on the back end unless the user really can choose their own amount'),
'#size' => 6,
'#required' => TRUE,
); );
$form['credit_card'] = array( $form['credit_card'] = array(
'#type' => 'fieldset', '#type' => 'fieldset',
'#title' => t('Credit Card Information'), '#title' => t('Credit Card Information'),
'#description' => t('<p>This credit card information is securely processed via <a href="https://stripe.com">stripe.com</a>. No credit card information is stored or processed on our server.</p>');
); );
$cc = &$form['credit_card']; $cc = &$form['credit_card'];
$cc['card_number'] = array( $cc['card_number'] = array(
@@ -94,68 +175,68 @@ function booking_stripeform_form($form, &$form_state) {
); );
$cc['exp_month'] = array( $cc['exp_month'] = array(
'#type' => 'select', '#type' => 'select',
'#title' => t('Expiration Month'), '#title' => t('Expiration Month'),
'#options' => drupal_map_assoc(array(1,2,3,4,5,6,7,8,9,10,11,12)), '#options' => drupal_map_assoc(array(1,2,3,4,5,6,7,8,9,10,11,12)),
'#pre_render' => array('booking_stripeform_remove_name'), '#pre_render' => array('booking_stripeform_remove_name'),
'#attributes' => array( '#attributes' => array(
'data-stripe' => 'exp-month', 'data-stripe' => 'exp-month',
), ),
'#empty_option' => t('- Select -'), '#empty_option' => t('- Select -'),
); );
$cc['exp_year'] = array( $cc['exp_year'] = array(
'#type' => 'select', '#type' => 'select',
'#title' => t('Expiration Year'), '#title' => t('Expiration Year'),
'#options' => array(), '#options' => array(),
'#pre_render' => array('booking_stripeform_remove_name'), '#pre_render' => array('booking_stripeform_remove_name'),
'#attributes' => array( '#attributes' => array(
'data-stripe' => 'exp-year', 'data-stripe' => 'exp-year',
), ),
'#empty_option' => t('- Select -'), '#empty_option' => t('- Select -'),
); );
$year = date('Y'); $year = date('Y');
for($i = $year; $i <= ($year + 10); $i++) { for($i = $year; $i <= ($year + 10); $i++) {
$cc['exp_year']['#options'][$i] = $i; $cc['exp_year']['#options'][$i] = $i;
} }
$cc['cvc'] = array( $cc['cvc'] = array(
'#type' => 'textfield', '#type' => 'textfield',
'#title' => t('CVC Number'), '#title' => t('CVC Number'),
'#pre_render' => array('booking_stripeform_remove_name'), '#pre_render' => array('booking_stripeform_remove_name'),
'#attributes' => array( '#attributes' => array(
'size' => 4, 'size' => 4,
'data-stripe' => 'cvc', 'data-stripe' => 'cvc',
), ),
); );
$cc['submit'] = array( $cc['submit'] = array(
'#type' => 'submit', '#type' => 'submit',
'#value' => t('Charge It'), '#value' => t('Charge It'),
'#attributes' => array( '#attributes' => array(
'class' => array('btn', 'btn-large', 'btn-primary'), 'class' => array('btn', 'btn-large', 'btn-primary'),
), ),
); );
// Adds our validation at the end of the build process. // Adds our validation at the end of the build process.
$form['#after_build'][] = 'booking_stripeform_add_final_validation'; $form['#after_build'][] = 'booking_stripe_add_final_validation';
return $form; return $form;
} }
*/
/** /**
* Tries to add final validation after all else has been added through alters. * Tries to add final validation after all else has been added through alters.
*/ */
function booking_stripeform_add_final_validation($form) { function booking_stripe_add_final_validation($form) {
$form['#validate'][] = 'booking_stripeform_validate_form_payment'; $form['#validate'][] = 'booking_stripe_validate_form_payment';
return $form; return $form;
} }
/** /**
* Form validation callback. * Form validation callback.
*/ */
function booking_stripeform_checkout_form_validate($form, &$form_state) { function booking_stripe_checkout_form_validate($form, &$form_state) {
// Validate normal form elements as needed. // Validate normal form elements as needed.
} }
@@ -167,26 +248,34 @@ function booking_stripeform_checkout_form_validate($form, &$form_state) {
* early. If success, we'll pass the charge on * early. If success, we'll pass the charge on
* to the submission callback. * to the submission callback.
*/ */
function booking_stripeform_validate_form_payment($form, &$form_state) { function booking_stripe_validate_form_payment($form, &$form_state) {
global $event;
if($errors = form_get_errors()) { if($errors = form_get_errors()) {
return; return;
} }
$path = libraries_get_path('stripe'); $path = libraries_get_path('stripe');
require_once($path . '/init.php'); require_once($path . '/init.php');
\Stripe\Stripe::setApiKey(_booking_get_stripe_private_key()); \Stripe\Stripe::setApiKey(_booking_get_stripe_private_key());
//$token = $form_state['values']['stripeToken'];
$token = $form_state['values']['stripeToken']; //$amount = $form_state['values']['amount'] * 100;
$amount = $form_state['values']['amount'] * 100; $token = (isset($form_state['input']['token_id']) ? $form_state['input']['token_id'] : '');
$amount = (isset($form_state['input']['amount']) ? $form_state['input']['amount'] : '');
$invoice = (isset($form_state['input']['invoice']) ? $form_state['input']['invoice'] : '');
watchdog('booking_debug', "<pre>Stripe payment form :\n@info</pre>", array('@info' => print_r( $form_state, true))); watchdog('booking_debug', "<pre>Stripe payment form :\n@info</pre>", array('@info' => print_r( $form_state, true)));
// Create the charge on Stripe's servers - this will charge the user's card // Create the charge on Stripe's servers - this will charge the user's card
try { try {
$charge = \Stripe\Charge::create(array( $charge = \Stripe\Charge::create(array(
"amount" => $amount, "amount" => $amount * 100,
"currency" => "usd", "currency" => "aud",
"card" => $token, "card" => $token,
"description" => 'test charge', "description" => $form_state['input']['description'],
"receipt_email" => $form_state['input']['email'],
"metadata" => array(
"invoice" => $invoice,
),
)); ));
if ($charge && $charge->paid) { if ($charge && $charge->paid) {
watchdog('booking', 'Charge created successfully'); watchdog('booking', 'Charge created successfully');

View File

@@ -1,65 +1,40 @@
(function($) { jQuery(document).ready(function($) {
$(function() { var settings = Drupal.settings.booking_stripe;
Stripe.setPublishableKey(Drupal.settings.booking_stripeform.pubkey); var $form = $("#" + settings.form_selector);
}); var handler = StripeCheckout.configure({
Drupal.behaviors.booking_stripeform = { key: settings.pubkey,
attach: function(context, settings) { image: settings.image,
$("#" + settings.booking_stripeform.form_selector, context).submit(function(e) { locale: 'auto',
e.preventDefault(); token: function(token) {
var $form = $(this); // Use the token to create the charge with a server-side script.
var $obj; // You can access the token ID with `token.id`
var $submitBtn = $("#edit-submit", context); if (currentForm === undefined)
settings.booking_stripeform.submitBtnText = $submitBtn.val(); return;
try { currentForm.find('input[name="token_id"]').val(token.id);
var $ccnum = $(':input[data-stripe="number"]', $form); currentForm.find('input[name="token_email"]').val(token.email);
var $exp_month = $(':input[data-stripe="exp-month"]', $form); currentForm.submit();
var $exp_year = $(':input[data-stripe="exp-year"]', $form);
var $cvc = $(':input[data-stripe="cvc"]', $form);
if(!Stripe.card.validateCardNumber($(':input[data-stripe="number"]', $form).val())) {
$obj = $ccnum;
throw "Invalid credit card number";
}
if(!Stripe.card.validateExpiry($exp_month.val(), $exp_year.val())) {
$obj = $exp_month;
throw "Invalid expiration month/year";
}
if(!Stripe.card.validateCVC($cvc.val())) {
$obj = $cvc;
throw "Invalid CVC";
}
} catch(err) {
$.each([$ccnum, $exp_month, $exp_year, $cvc], function(i, e) {
e.addClass('error');
});
$obj.parents('div.control-group').toggleClass('error');
reportError(err, $obj);
return false;
} }
$submitBtn.val('Please wait...').attr('disabled', true); });
Stripe.createToken($form, stripeResponseHandler); var currentForm = undefined;
return false;
});
}
}
var stripeResponseHandler = function(status, response) { $('.form-submit').click(function (e) {
var $form = $("#" + Drupal.settings.booking_stripeform.form_selector); currentForm = $(this).closest('form');
if (response.error) { if (currentForm === undefined)
alert(response.error.message); return;
} else { handler.open({
// token contains id, last4, and card type name: settings.name,
var token = response.id; description: currentForm.find('input[name="description"]').val(),
// Insert the token into the form so it gets submitted to the server email: currentForm.find('input[name="email"]').val(),
$('input[name=stripeToken]', $form).val(token); currency: "aud",
// and submit amount: currentForm.find('input[name="amount"]').val() * 100,
$form.get(0).submit(); closed: function() {
} //document.getElementById("booking_stripe_form").submit();
}; }
});
/** e.preventDefault();
* Uses Bootstrap's popover to alert the user. });
*/ // Close Checkout on page navigation
function reportError(msg, $el) { //$(window).on('popstate', function() {
console.log([$el, msg]); // handler.close();
} //});
}(jQuery)); });