-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuc_stripe_js.module
530 lines (435 loc) · 19.7 KB
/
uc_stripe_js.module
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
<?php
/**
* @file
* A stripe.js payment gateway
* Developed by skulegirl
*/
function uc_stripe_js_payment_gateway() {
$gateways[] = array(
'id' => 'stripe_js_gateway',
'title' => t('Stripe JS Gateway'),
'description' => t('Process credit card payments using Stripe JS.'),
'stripe_js' => 'uc_stripe_js_charge',
'settings' => 'uc_stripe_js_settings_form',
'credit_txn_types' => array(UC_CREDIT_AUTH_ONLY, UC_CREDIT_PRIOR_AUTH_CAPTURE, UC_CREDIT_AUTH_CAPTURE),
);
return $gateways;
}
function uc_stripe_js_payment_method() {
$title = t('Credit card:');
$cc_types = array(
'visa' => t('Visa'),
'mastercard' => t('MasterCard'),
// 'discover' => t('Discover'),
'amex' => t('American Express'),
);
foreach ($cc_types as $type => $label) {
// ANNA - can't be bothered to implement this variable right now, just hardcode the 3 we accept
// if (variable_get('uc_credit_'. $type, TRUE)) {
$title .= ' ' . theme('image', drupal_get_path('module', 'uc_stripe_js') . '/images/' . $type . '.gif', $label, '', array('class' => 'uc-stripe-js-cctype uc-stripe-js-cctype-' . $type));
// }
}
$methods[] = array(
'id' => 'stripe_js',
'name' => t('Stripe.js credit processing'),
'title' => $title,
'review' => t('Credit card (Visa, Mastercard or American Express)'),
'desc' => t('Pay through Stripe.js gateway'),
'callback' => 'uc_stripe_js_method',
'weight' => 0,
'checkout' => TRUE,
'no_gateway' => FALSE,
);
return $methods;
}
function uc_stripe_js_order_pane() {
$panes[] = array(
'id' => 'stripe_js',
'callback' => 'uc_stripe_js_order_pane_stripe',
'title' => t('Stripe Customer Info'),
'desc' => t("Stripe Information"),
'class' => 'pos-left',
'weight' => 3,
'show' => array('view', 'edit'),
);
return $panes;
}
function uc_stripe_js_method($op, &$order) {
switch ($op) {
case 'settings':
$form['uc_stripe_js_checkout_image'] = array(
'#type' => 'textfield',
'#title' => t('Checkout Image Url'),
'#default_value' => variable_get('uc_stripe_js_checkout_image', ''),
'#description' => t('Url to the image to use at checkout. Should be square image, will be displayed in a circle'),
);
$form['uc_stripe_js_checkout_name'] = array(
'#type' => 'textfield',
'#title' => t('Title to use for checkout pane'),
'#default_value' => variable_get('uc_stripe_js_checkout_name', variable_get('uc_store_name', '')),
'#description' => t('Will be displayed under the checkout image, abvoe the cc fields'),
);
$form['uc_stripe_js_api_key_test_secret'] = array(
'#type' => 'textfield',
'#title' => t('Test Secret Key'),
'#default_value' => variable_get('uc_stripe_js_api_key_test_secret', ''),
'#description' => t('Your Development Stripe API Key. Must be the "secret" key, not the "publishable" one.'),
);
$form['uc_stripe_js_api_key_test_publishable'] = array(
'#type' => 'textfield',
'#title' => t('Test Publishable Key'),
'#default_value' => variable_get('uc_stripe_js_api_key_test_publishable', ''),
'#description' => t('Your Development Stripe API Key. Must be the "publishable" key, not the "secret" one.'),
);
$form['uc_stripe_js_api_key_live_secret'] = array(
'#type' => 'textfield',
'#title' => t('Live Secret Key'),
'#default_value' => variable_get('uc_stripe_js_api_key_live_secret', ''),
'#description' => t('Your Live Stripe API Key. Must be the "secret" key, not the "publishable" one.'),
);
$form['uc_stripe_js_api_key_live_publishable'] = array(
'#type' => 'textfield',
'#title' => t('Live Publishable Key'),
'#default_value' => variable_get('uc_stripe_js_api_key_live_publishable', ''),
'#description' => t('Your Live Stripe API Key. Must be the "publishable" key, not the "secret" one.'),
);
$form['uc_stripe_js_testmode'] = array(
'#type' => 'checkbox',
'#title' => t('Test mode'),
'#description' => 'Testing Mode: Stripe will use the development API key to process the transaction so the card will not actually be charged.',
'#default_value' => variable_get('uc_stripe_js_testmode', TRUE),
);
return $form;
}
}
//-------------------------------------------------------------------------------------------|
// Callback for stripe order pane
//-------------------------------------------------------------------------------------------|
function uc_stripe_js_order_pane_stripe($op, $arg1) {
if($op == 'view'){
$stripe_customer_id = _uc_stripe_js_get_customer_id($arg1->uid);
$output = "Stripe Customer ID: $stripe_customer_id";
return $output;
}
}
function uc_stripe_js_form_alter(&$form, $form_state, $form_id) {
if ($form_id == 'uc_cart_checkout_review_form' && ($order_id = intval($_SESSION['cart_order'])) > 0) {
$order = uc_order_load($order_id);
// Note that if this isn't unset, then the callbacks don't happen properly for some reason. Unable to
// figure out why so far. Can probably replace it with a link to the /cart/checkout page.
unset($form['back']);
if ($order->payment_method == 'stripe_js') {
// Collect some information about the order
$time = time();
$order_id = $order->order_id;
$order_total = number_format($order->order_total, 2, '.', '');
$customer_email = $order->primary_email;
$cart_id = uc_cart_get_id();
$external_js = 'https://checkout.stripe.com/checkout.js';
$apikey = variable_get('uc_stripe_js_testmode', TRUE) ? variable_get('uc_stripe_js_api_key_test_publishable', '') : variable_get('uc_stripe_js_api_key_live_publishable', '');
$checkoutimgpath = variable_get('uc_stripe_js_checkout_image', '//stripe.com/img/documentation/checkout/marketplace.png');
$data_name = variable_get('uc_stripe_js_checkout_name', '');
$contents = uc_cart_get_contents();
// ANNA - total hack in here to handle my product names being way too long.
foreach ($contents as $item) {
if (preg_match('/^.*1Year$/', $item->model))
{
$orderdsc .= '1 Year ';
}
elseif (preg_match('/^.*3Years$/', $item->model))
{
$orderdsc .= '3 Year ';
}
if (preg_match('/^FullMembership-BDA-.*$/', $item->model))
{
$orderdsc .= 'Discounted Full Membership';
}
elseif (preg_match('/^FullMembership-NoBDA-.*$/', $item->model))
{
$orderdsc .= 'Full Membership';
}
}
$stripe_js_script .= '<script ';
$stripe_js_script .= 'src="'. $external_js .'" ';
$stripe_js_script .= 'type="text/javascript" ';
$stripe_js_script .= 'class="stripe-button" ';
$stripe_js_script .= 'data-label="Pay Now!" ';
$stripe_js_script .= 'data-name="'. $data_name .'" ';
$stripe_js_script .= 'data-key="'. $apikey .'" ';
$stripe_js_script .= 'data-image="'. $checkoutimgpath .'" ';
$stripe_js_script .= 'data-description="'. $orderdsc .'" ';
$stripe_js_script .= 'data-amount="'. $order_total*100 .'" '; // note that total must be in cents
$stripe_js_script .= 'data-email="'. $customer_email .'" ';
$stripe_js_script .= 'data-billing-address="true" ';
$stripe_js_script .= '></script>';
// Build the data to send to my payment gateway
$data = array(
'timestamp' => time(),
'order_id' => $order->order_id,
'order_total' => number_format($order->order_total, 2, '.', ''),
'order_description' => $orderdsc,
'customer_email' => $order->primary_email,
'cart_id' => uc_cart_get_id(),
);
// This code goes behind the final checkout button of the checkout pane
foreach ($data as $name => $value) {
if (!empty($value)) {
$form[$name] = array('#type' => 'hidden', '#value' => $value);
}
}
//--Add our custom submit routine to the top of the submit array------------------------------------------------------------------------|
array_unshift($form['#submit'], "uc_stripe_js_checkout_form_customsubmit");
// $form['#submit'][] = 'uc_stripe_js_submit_form_submit';
$form['submit']['#prefix'] = '<div style="height:0px; width:0px; visibility:hidden">';
$form['submit']['#suffix'] = '</div>';
$form['hidden_submit'] = array('#type' => 'hidden', '#suffix' => $stripe_js_script);
// $form['#prefix'] = '<table style="display: inline; padding-top: 1em;"><tr><td>';
// $form['#suffix'] = '</td></tr></table>';
}
}
}
function uc_stripe_js_charge($order_id, $amount, $data) {
watchdog('uc_stripe_js', 'In uc_stripe_js_charge', NULL, WATCHDOG_DEBUG);
//-------------------------------------------------------------------------------------------|
// Load the stripe API
//-------------------------------------------------------------------------------------------|
if (!_uc_stripe_js_load_api()) {
$result = array(
'success' => FALSE,
'comment' => t('Stripe API not found.'),
'message' => t('Stripe API not found. Contact the site administrator.'),
'uid' => $user->uid,
'order_id' => $order_id,
);
return $result;
}
//-------------------------------------------------------------------------------------------|
// Sanitize some variables
//-------------------------------------------------------------------------------------------|
global $user;
$order = uc_order_load($order_id);
$context = array(
'revision' => 'formatted-original',
'type' => 'amount',
);
$options = array(
'sign' => FALSE,
'thou' => FALSE,
'dec' => FALSE,
'prec' => 2,
);
$amount = uc_price($amount, $context, $options);
//-------------------------------------------------------------------------------------------|
// Determine the user's stripe customer ID. If they don't have one, we'll create one.
// Since we can't use tokens multiple times, customer creation must come before
// Charging the user.
//-------------------------------------------------------------------------------------------|
// $stripe_customer_id = false;
//If the user running the order is not the order's owner (like if an admin is processing an order on someone's behalf)
//Then, load the customer ID from the user object.
//Otherwise, make a brand new customer each time a user checks out.
// if($user->uid != $order->uid){
$stripe_customer_id = _uc_stripe_js_get_customer_id($order->uid);
// }
// Create a new customer if one doesn't yet exist
if(!$stripe_customer_id){
try{
//Create the customer in stripe
$customer = Stripe_Customer::create(array(
"card" => $stripe_token,
'description' => "OrderID: {$order->order_id}",
'email' => "$order->primary_email"
)
);
//Store the customer ID in the session,
//We'll pick it up later to save it in the database since we might not have a $user object at this point anyway
$_SESSION['stripe']['customer_id'] = $customer->id;
$stripe_customer_id = $customer->id;
}
catch (Exception $e) {
$result = array(
'success' => FALSE,
'comment' => $e->getCode(),
'message' => t("Stripe Customer Creation Failed for order !order: !message", array("!order" => $order_id, "!message" => $e->getMessage())),
'uid' => $user->uid,
'order_id' => $order_id,
);
uc_order_comment_save($order_id, $user->uid, $result['message'], 'admin');
watchdog('uc_stripe_js', $result['message']);
return $result;
}
}
// Now update the customer to use the currently supplied card
try {
//If the token is not in the user's session, we can't set up a new customer
if(empty($_SESSION['stripe']['token'])){throw new Exception('Token not found');}
//Get the token for this card
$stripe_token = $_SESSION['stripe']['token'];
//Retrieve the customer in stripe
$customer = Stripe_Customer::retrieve($stripe_customer_id);
// Update the card info to that supplied
$customer->card = $stripe_token;
$customer->save();
}
catch (Exception $e) {
$result = array(
'success' => FALSE,
'comment' => $e->getCode(),
'message' => t("Stripe Customer card update failed for order !order: !message", array("!order" => $order_id, "!message" => $e->getMessage())),
'uid' => $user->uid,
'order_id' => $order_id,
);
uc_order_comment_save($order_id, $user->uid, $result['message'], 'admin');
watchdog('uc_stripe_js', $result['message']);
return $result;
}
//-------------------------------------------------------------------------------------------|
// Charge the stripe customer the amount in the order
//-------------------------------------------------------------------------------------------|
//--Handle transactions for $0------------------------------------------------------------------------|
// Stripe can't handle transactions < $0.50, but $0 is a common value
// so we will just return a positive result when the amount is $0.
if ($amount == 0) {
$result = array(
'success' => TRUE,
'message' => t('Credit card payment of $0 approved'),
'uid' => $user->uid,
'trans_id' => md5(uniqid(rand())),
);
uc_order_comment_save($order_id, $user->uid, $result['message'], 'admin');
return $result;
}
//--Charge the customer via stripe------------------------------------------------------------------------|
try {
//Bail if there's no customer ID
if(empty($stripe_customer_id)){throw new Exception('No customer ID found');}
// charge the Customer the amount in the order - will use the default card on file, which should
// have been updated above to the card supplied
$charge = Stripe_Charge::create(array(
"amount" => $amount,
"currency" => "usd",
"customer" => $stripe_customer_id,
"description" => $_SESSION['stripe']['orderdsc'],
)
);
$formatted_amount = $amount / 100;
$formatted_amount = number_format ($formatted_amount, 2);
$result = array(
'success' => TRUE,
'message' => "Credit card payment of $$formatted_amount processed successfully.",
'uid' => $user->uid,
'trans_id' => $charge->__get('id'),
);
uc_order_comment_save($order_id, $user->uid, $result['message'], 'admin');
uc_order_comment_save($order_id, $user->uid, $result['message'], 'order', 'completed', false);
return $result;
}
catch (Exception $e) {
$result = array(
'success' => FALSE,
'comment' => $e->getCode(),
'message' => t("Stripe Charge Failed for order !order: !message", array("!order" => $order_id, "!message" => $e->getMessage())),
'uid' => $user->uid,
'order_id' => $order_id,
);
uc_order_comment_save($order_id, $user->uid, $result['message'], 'admin');
watchdog('uc_stripe_js', $result['message']);
return $result;
}
//--End charging the customer via stripe------------------------------------------------------------------------|
//-------------------------------------------------------------------------------------------|
// Default / Fallback procedure to fail if the above conditions aren't met
//-------------------------------------------------------------------------------------------|
$result = array(
'success' => FALSE,
'comment' => "Stripe Gateway Error",
'message' => "Stripe Gateway Error",
'uid' => $user->uid,
'order_id' => $order_id,
);
uc_order_comment_save($order_id, $user->uid, $result['message'], 'admin');
watchdog('uc_stripe_js', $result['message']);
return $result;
//-------------------------------------------------------------------------------------------|
// End default / fallback procedure if the faux number wasn't passed
//-------------------------------------------------------------------------------------------|
}
function _uc_stripe_js_load_api() {
if ($path = libraries_get_path('stripe')) {
// Load Stripe Library.
include_once $path . '/lib/Stripe.php';
}
else {
watchdog('uc_stripe_js', 'Stripe Library not found. Please download into sites/all/libraries/stripe', array(), WATCHDOG_WARNING);
return FALSE;
}
$apikey = variable_get('uc_stripe_js_testmode', TRUE) ? variable_get('uc_stripe_js_api_key_test_secret', '') : variable_get('uc_stripe_js_api_key_live_secret', '');
if ($apikey == '') {
watchdog('uc_stripe_js', 'No Stripe API key is set. Payment cannot go through until set.', array(), WATCHDOG_WARNING);
return FALSE;
}
try {
Stripe::setApiKey($apikey);
}
catch (Exception $e) {
watchdog('uc_stripe_js', 'Error setting the Stripe API Key. Payments will not be processed: %error', array('%error' => $e->getMessage()));
}
return TRUE;
}
//-------------------------------------------------------------------------------------------|
// Retrieve a user's stripe_customer_id
// @param int $uid: the user to check an ID for
//-------------------------------------------------------------------------------------------|
function _uc_stripe_js_get_customer_id($uid){
$account = user_load(array('uid' => $uid));
$userdata = unserialize($account->data);
if(empty($userdata['uc_stripe_js_customer_id'])){return false;}
$stripe_customer_id = $userdata['uc_stripe_js_customer_id'];
return $stripe_customer_id;
}
/**
* Additional submit handler for uc_cart_checkout_review_form().
*
* @see uc_cart_checkout_review_form()
*/
function uc_stripe_js_submit_form_submit($form, &$form_state) {
watchdog('uc_stripe_js', 'In uc_stripe_js_submit_form_submit', NULL, WATCHDOG_DEBUG);
$order = uc_order_load($_SESSION['cart_order']);
$form_state['redirect'] = 'cart/checkout/complete';
}
/**
* Implements hook_order().
*/
function uc_stripe_js_order($op, $arg1, $arg2) {
switch ($op) {
case 'submit':
if ($arg1->payment_method == 'stripe_js') {
// Attempt to process the CC payment.
$pass = uc_payment_process('stripe_js', $arg1->order_id, $arg1->order_total, $data, FALSE, NULL, FALSE);
// If the payment failed, store the data back in the session and
// halt the checkout process.
if (!$pass) {
$message = t('We were unable to process your credit card payment. Please verify your details and try again. If the problem persists, <a href="/contact/order-inquiry">contact us</a> to complete your order.');
return array(array('pass' => FALSE, 'message' => $message));
}
}
break;
}
}
function uc_stripe_js_uc_checkout_complete($order, $account){
//Pull the stripe customer ID from the session.
$stripe_customer_id = $_SESSION['stripe']['customer_id'];
$loaded_user = user_load(array('uid' => $account->uid));
user_save($loaded_user, array("uc_stripe_js_customer_id" => $stripe_customer_id));
}
//-------------------------------------------------------------------------------------------|
// Custom submit function to store the stripe token
//
// Since we don't have a user account at this step, we're going to store the token
// in the session. We'll grab the token in the charge callback and use it to run cards
//-------------------------------------------------------------------------------------------|
function uc_stripe_js_checkout_form_customsubmit($form, &$form_state){
$_SESSION['stripe']['token'] = $form_state['clicked_button']['#post']['stripeToken'];
$_SESSION['stripe']['orderdsc'] = $form_state['clicked_button']['#post']['order_description'];
}
?>