-
Notifications
You must be signed in to change notification settings - Fork 0
/
commerce_paypal_rb.module
1719 lines (1498 loc) · 65.9 KB
/
commerce_paypal_rb.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
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* @file
* Implements PayPal Express Checkout Recurring Billing in Drupal Commerce checkout.
*/
/**
* Implements hook_menu().
*/
function commerce_paypal_rb_menu() {
$items = array();
// Add a menu item for capturing authorizations.
$items['admin/commerce/orders/%commerce_order/payment/%commerce_payment_transaction/paypal-rb-capture'] = array(
'title' => 'Capture',
'page callback' => 'drupal_get_form',
'page arguments' => array('commerce_paypal_rb_capture_form', 3, 5),
'access callback' => 'commerce_paypal_rb_capture_void_access',
'access arguments' => array(3, 5),
'type' => MENU_DEFAULT_LOCAL_TASK,
'context' => MENU_CONTEXT_INLINE,
'weight' => 2,
'file' => 'includes/commerce_paypal_rb.admin.inc',
);
// Add a menu item for voiding authorizations.
$items['admin/commerce/orders/%commerce_order/payment/%commerce_payment_transaction/paypal-rb-void'] = array(
'title' => 'Void',
'page callback' => 'drupal_get_form',
'page arguments' => array('commerce_paypal_rb_void_form', 3, 5),
'access callback' => 'commerce_paypal_rb_capture_void_access',
'access arguments' => array(3, 5),
'type' => MENU_DEFAULT_LOCAL_TASK,
'context' => MENU_CONTEXT_INLINE,
'weight' => 4,
'file' => 'includes/commerce_paypal_rb.admin.inc',
);
// Add a menu item for refunding settled transactions.
$items['admin/commerce/orders/%commerce_order/payment/%commerce_payment_transaction/paypal-rb-refund'] = array(
'title' => 'Refund',
'page callback' => 'drupal_get_form',
'page arguments' => array('commerce_paypal_rb_refund_form', 3, 5),
'access callback' => 'commerce_paypal_rb_refund_access',
'access arguments' => array(3, 5),
'type' => MENU_DEFAULT_LOCAL_TASK,
'context' => MENU_CONTEXT_INLINE,
'weight' => 4,
'file' => 'includes/commerce_paypal_rb.admin.inc',
);
return $items;
}
/**
* Determines access to the prior authorization capture form or void form for
* Paypal EC credit card transactions.
*
* @param $order
* The order the transaction is on.
* @param $transaction
* The payment transaction object to be captured.
*
* @return
* TRUE or FALSE indicating access.
*/
function commerce_paypal_rb_capture_void_access($order, $transaction) {
// Return FALSE if the transaction isn't for Paypal EC or isn't awaiting capture.
if ($transaction->payment_method != 'paypal_ec' || $transaction->remote_status != 'Pending') {
return FALSE;
}
// Return FALSE if the transaction is not pending.
if ($transaction->status != COMMERCE_PAYMENT_STATUS_PENDING) {
return FALSE;
}
// Return FALSE if the transaction is actually a pending echeck.
if (!empty($transaction->data['commerce_paypal_rb']['paymenttype']) &&
$transaction->data['commerce_paypal_rb']['paymenttype'] == 'echeck') {
return FALSE;
}
// Return FALSE if it is more than 29 days past the original authorization.
if (REQUEST_TIME - $transaction->created > 86400 * 29) {
return FALSE;
}
// Allow access if the user can update payments on this transaction.
return commerce_payment_transaction_access('update', $transaction);
}
/**
* Determines access to the refund form for Paypal EC credit card transactions.
*
* @param $order
* The order the transaction is on.
* @param $transaction
* The payment transaction object to be captured.
*
* @return
* TRUE or FALSE indicating access.
*/
function commerce_paypal_rb_refund_access($order, $transaction) {
// Return FALSE if the transaction isn't Completed.
if ($transaction->payment_method != 'paypal_ec' || $transaction->remote_status != 'Completed') {
return FALSE;
}
// Return FALSE if the transaction was not a success.
if ($transaction->status != COMMERCE_PAYMENT_STATUS_SUCCESS) {
return FALSE;
}
// Return FALSE if it is more than 60 days since the original transaction.
if (REQUEST_TIME - $transaction->created > 86400 * 60) {
return FALSE;
}
// Allow access if the user can update payments on this transaction.
return commerce_payment_transaction_access('update', $transaction);
}
/**
* Implements hook_commerce_checkout_page_info().
*/
function commerce_paypal_rb_commerce_checkout_page_info() {
$checkout_pages = array();
$checkout_pages['paypal_rb'] = array(
'title' => t('Confirm order'),
'help' => t('Confirm your order information and use the button at the bottom of the page to finalize your payment.'),
'status_cart' => FALSE,
'locked' => TRUE,
'buttons' => FALSE,
'weight' => 30,
);
return $checkout_pages;
}
/**
* Implements hook_commerce_checkout_pane_info().
*/
function commerce_paypal_rb_commerce_checkout_pane_info() {
$checkout_panes = array();
$checkout_panes['paypal_ec_review'] = array(
'title' => t('Review and confirm your order'),
'name' => t('Express Checkout review and confirm (only to be used on the confirm order page)'),
'file' => 'includes/commerce_paypal_rb.checkout_pane.inc',
'base' => 'commerce_paypal_rb_review_pane',
'page' => 'paypal_ec',
'fieldset' => FALSE,
);
return $checkout_panes;
}
/**
* Implements hook_commerce_checkout_router().
*/
function commerce_paypal_rb_commerce_checkout_router($order, $checkout_page) {
// If the current page is the Express Checkout page but the current order did
// not use the Express Checkout flow...
if ($checkout_page['page_id'] == 'paypal_ec' &&
(empty($order->data['commerce_paypal_rb']['flow']) || $order->data['commerce_paypal_rb']['flow'] != 'ec')) {
// Update the order status to the next checkout page.
$next_page = $checkout_page['next_page'];
$order = commerce_order_status_update($order, 'checkout_' . $next_page, FALSE, FALSE);
// Inform modules of checkout completion if the next page is Completed.
if ($next_page == 'complete') {
commerce_checkout_complete($order);
}
// Redirect to the URL for the new checkout page.
$target_uri = commerce_checkout_order_uri($order);
return drupal_goto($target_uri);
}
}
/**
* Implements hook_commerce_payment_method_info().
*/
function commerce_paypal_rb_commerce_payment_method_info() {
$payment_methods = array();
$payment_methods['paypal_rb'] = array(
'base' => 'commerce_paypal_rb',
'buttonsource' => 'CommerceGuys_Cart_EC',
'title' => t('PayPal Recurring Billing'),
'short_title' => t('PayPal EC'),
'description' => t('PayPal Recurring Billing'),
'terminal' => FALSE,
'offsite' => TRUE,
'offsite_autoredirect' => TRUE,
);
return $payment_methods;
}
/**
* Implements hook_page_alter().
*/
function commerce_paypal_rb_page_alter(&$page) {
// Add a registration link to the PayPal Express Checkout payment method rules
// on the payment methods admin page.
if (!empty($page['content']['system_main']['#page_callback']) &&
$page['content']['system_main']['#page_callback'] == 'commerce_payment_ui_admin_page') {
// Ensure we loop over both enabled and disabled rules.
foreach (array('enabled', 'disabled') as $key) {
foreach ($page['content']['system_main'][$key]['rules']['#rows'] as $row_key => &$row) {
if (strpos($row[0]['data']['description']['settings']['machine_name']['#markup'], 'commerce_payment_paypal_ec') > 0) {
$row[0]['data']['#suffix'] = '<div class="service-description">' . commerce_paypal_rb_service_description() . '</div></div>';
}
}
}
}
}
/**
* Returns a service description and registration link for the specified method.
*/
function commerce_paypal_rb_service_description() {
return t('Allow customers to pay via PayPal and optionally credit card or debit card on a securely hosted checkout form. This payment method requires a PayPal Business account. <a href="!url">Sign up here</a> and edit this rule to start accepting payments.', array('!url' => 'https://www.paypal.com/webapps/mpp/referral/paypal-express-checkout?partner_id=VZ6B9QLQ8LZEE'));
}
/**
* Returns the default settings for the PayPal EC payment method.
*/
function commerce_paypal_rb_default_settings() {
$default_currency = commerce_default_currency();
$default_settings = array(
'api_username' => '',
'api_password' => '',
'api_signature' => '',
'server' => 'sandbox',
'currency_code' => in_array($default_currency, array_keys(commerce_paypal_currencies('paypal_ec'))) ? $default_currency : 'USD',
'allow_supported_currencies' => FALSE,
'txn_type' => COMMERCE_CREDIT_AUTH_CAPTURE,
'ec_mode' => 'Mark',
'shipping_prompt' => 1,
'log' => array('request' => 0, 'response' => 0),
'ipn_logging' => 'notification',
'receiver_emails' => '',
'reference_transactions' => FALSE,
'ba_desc' => '',
'show_payment_instructions' => FALSE,
'update_billing_profiles' => TRUE,
);
if (module_exists('commerce_shipping')) {
$default_settings['update_shipping_profiles'] = TRUE;
}
return $default_settings;
}
/**
* Payment method callback: settings form.
*/
function commerce_paypal_rb_settings_form($settings = array()) {
$form = array();
// Merge default settings into the stored settings array.
$settings = (array) $settings + commerce_paypal_rb_default_settings();
$form['service_description'] = array(
'#markup' => '<div>' . commerce_paypal_rb_service_description() . ' '
. t('Refer to the <a href="!url" target="_blank">module documentation</a> to find your API credentials and ensure your payment method and account settings are configured properly.', array('!url' => 'http://drupal.org/node/1901466')) . '</div>',
);
$form['api_username'] = array(
'#type' => 'textfield',
'#title' => t('API username'),
'#default_value' => $settings['api_username'],
);
$form['api_password'] = array(
'#type' => 'textfield',
'#title' => t('API password'),
'#default_value' => $settings['api_password'],
);
$form['api_signature'] = array(
'#type' => 'textfield',
'#title' => t('Signature'),
'#default_value' => $settings['api_signature'],
);
$form['server'] = array(
'#type' => 'radios',
'#title' => t('PayPal server'),
'#options' => array(
'sandbox' => ('Sandbox - use for testing, requires a PayPal Sandbox account'),
'live' => ('Live - use for processing real transactions'),
),
'#default_value' => $settings['server'],
);
$form['currency_code'] = array(
'#type' => 'select',
'#title' => t('Default currency'),
'#description' => t('Transactions in other currencies will be converted to this currency, so multi-currency sites must be configured to use appropriate conversion rates.'),
'#options' => commerce_paypal_currencies('paypal_ec'),
'#default_value' => $settings['currency_code'],
);
$form['allow_supported_currencies'] = array(
'#type' => 'checkbox',
'#title' => t('Allow transactions to use any currency in the options list above.'),
'#description' => t('Transactions in unsupported currencies will still be converted into the default currency.'),
'#default_value' => $settings['allow_supported_currencies'],
);
$form['txn_type'] = array(
'#type' => 'radios',
'#title' => t('Default transaction type'),
'#description' => t('The default will be used to process transactions during checkout.'),
'#options' => array(
COMMERCE_CREDIT_AUTH_CAPTURE => t("Sale (direct debit from the customer's PayPal account)"),
COMMERCE_CREDIT_AUTH_ONLY => t('Authorization only (requires manual or automated capture after checkout)'),
),
'#default_value' => $settings['txn_type'],
);
$form['ec_mode'] = array(
'#type' => 'radios',
'#title' => t('Express Checkout mode'),
'#description' => t('Express Checkout Account Optional (ECAO) where PayPal accounts are not required for payment may not be available in all markets.'),
'#options' => array(
'Mark' => t('Require a PayPal account (this is the standard configuration).'),
'SoleLogin' => t('Allow PayPal AND credit card payments, defaulting to the PayPal form.'),
'SoleBilling' => t('Allow PayPal AND credit card payments, defaulting to the credit card form.'),
),
'#default_value' => $settings['ec_mode'],
);
$form['shipping_prompt'] = array(
'#type' => 'radios',
'#title' => t('Shipping address collection'),
'#description' => t('Express Checkout will only request a shipping address if the Shipping module is enabled to store the address in the order.'),
'#options' => array(
'0' => t('Do not ask for a shipping address at PayPal.'),
),
'#default_value' => '0',
);
if (module_exists('commerce_shipping')) {
$form['shipping_prompt']['#options'] += array(
'1' => t('Ask for a shipping address at PayPal if the order does not have one yet.'),
'2' => t('Ask for a shipping address at PayPal even if the order already has one.'),
);
$form['shipping_prompt']['#default_value'] = $settings['shipping_prompt'];
}
$form['log'] = array(
'#type' => 'checkboxes',
'#title' => t('Log the following messages for debugging'),
'#options' => array(
'request' => t('API request messages'),
'response' => t('API response messages'),
),
'#default_value' => $settings['log'],
);
$form['ipn_logging'] = array(
'#type' => 'radios',
'#title' => t('IPN logging'),
'#options' => array(
'notification' => t('Log notifications during IPN validation and processing.'),
'full_ipn' => t('Log notifications with the full IPN during validation and processing (used for debugging).'),
),
'#default_value' => $settings['ipn_logging'],
);
$form['receiver_emails'] = array(
'#type' => 'textfield',
'#title' => t('PayPal receiver e-mail addresses'),
'#description' => t('Enter the primary e-mail address for your PayPal account where you receive Express Checkout payments or a comma separated list of valid e-mail addresses.') . '<br />' . t('IPNs that originate from payments made to a PayPal account whose e-mail address is not in this list will not be processed.'),
'#default_value' => $settings['receiver_emails'],
);
$form['reference_transactions'] = array(
'#type' => 'checkbox',
'#title' => t('Enable reference transactions for payments captured through Express Checkout.'),
'#description' => t('Contact PayPal if you are unsure if this option is available to you.'),
'#default_value' => $settings['reference_transactions'],
);
$form['ba_desc'] = array(
'#type' => 'textfield',
'#title' => t('Express Checkout billing agreement description'),
'#description' => t('If you have a PayPal account that supports reference transactions and need them, you must specify a billing agreement description.'),
'#default_value' => $settings['ba_desc'],
);
$form['show_payment_instructions'] = array(
'#type' => 'checkbox',
'#title' => t('Show a message on the checkout form when PayPal EC is selected telling the customer to "Continue with checkout to complete payment via PayPal."'),
'#default_value' => $settings['show_payment_instructions'],
);
$form['update_billing_profiles'] = array(
'#type' => 'checkbox',
'#title' => t('Update billing customer profiles with address information the customer enters at PayPal.'),
'#default_value' => $settings['update_billing_profiles'],
);
if (module_exists('commerce_shipping')) {
$form['update_shipping_profiles'] = array(
'#type' => 'checkbox',
'#title' => t('Update shipping customer profiles with address information the customer enters at PayPal.'),
'#default_value' => $settings['update_shipping_profiles'],
);
}
return $form;
}
/**
* Implements hook_form_alter().
*/
function commerce_paypal_rb_form_alter(&$form, &$form_state, $form_id) {
if (!is_string($form_id)) {
return;
}
// If we're altering a shopping cart form and PayPal EC is enabled...
if (strpos($form_id, 'views_form_commerce_cart_form_') === 0 && commerce_paypal_rb_enabled()) {
// If the cart form View shows line items...
if (!empty($form_state['build_info']['args'][0]->result)) {
$order = $form_state['order'];
// And Express Checkout is also available as a payment option in checkout...
if (commerce_paypal_rb_enabled($order)) {
// Add the Express Checkout form as a suffix to the cart form.
$payment_method = commerce_payment_method_instance_load('paypal_ec|commerce_payment_paypal_ec');
$ec_form = drupal_get_form('commerce_paypal_rb_order_form', $payment_method, $order);
$form['#suffix'] .= drupal_render($ec_form);
}
}
}
// If we're altering a checkout form that has the PayPal EC radio button...
if (strpos($form_id, 'commerce_checkout_form_') === 0 && !empty($form['commerce_payment']['payment_method'])) {
$paypal_ec = FALSE;
foreach ($form['commerce_payment']['payment_method']['#options'] as $key => &$value) {
list($method_id, $rule_name) = explode('|', $key);
// If we find PayPal EC, include its CSS on the form and exit the loop.
if ($method_id == 'paypal_ec') {
$paypal_ec = TRUE;
$value = theme('paypal_ec_mark_image');
}
}
// If we did find PayPal EC, include its CSS now.
if ($paypal_ec) {
$form['commerce_payment']['payment_method']['#attached']['css'][] = drupal_get_path('module', 'commerce_paypal_rb') . '/theme/commerce_paypal_rb.theme.css';
}
}
}
/**
* Displays an Express Checkout button as a form that redirects to PayPal.
*/
function commerce_paypal_rb_order_form($form, &$form_state, $payment_method, $order) {
$form_state['payment_method'] = $payment_method;
$form_state['order'] = $order;
$form['#attributes'] = array(
'class' => array('paypal-ec-order-form'),
);
// @todo See if we can embed this using HTTP to avoid potential browser
// warnings if HTTPS is not enabled on the site.
$form['paypal_ec'] = array(
'#type' => 'image_button',
'#value' => t('Check out with PayPal'),
'#src' => commerce_paypal_rb_button_url(),
'#attached' => array(
'css' => array(
drupal_get_path('module', 'commerce_paypal_rb') . '/theme/commerce_paypal_rb.theme.css',
),
),
);
return $form;
}
/**
* Validate handler: ensures PayPal Express Checkout has been configured.
*/
function commerce_paypal_rb_order_form_validate($form, &$form_state) {
// Return an error if the enabling action's settings haven't been configured.
foreach (array('api_username', 'api_password', 'api_signature') as $key) {
if (empty($form_state['payment_method']['settings'][$key])) {
form_set_error('', t('PayPal Express Checkout is not configured for use. Please contact an administrator to resolve this issue.'));
}
}
}
/**
* Submit handler: redirect to PayPal Express Checkout.
*/
function commerce_paypal_rb_order_form_submit($form, &$form_state) {
$flow = 'ec';
// Update the order to reference the PayPal Express Checkout payment method.
$payment_method = $form_state['payment_method'];
$order = $form_state['order'];
$order->data['payment_method'] = $payment_method['instance_id'];
// Generate a payment redirect key.
$order->data['payment_redirect_key'] = drupal_hash_base64(time());
// Request a token from Express Checkout.
$token = commerce_paypal_rb_set_express_checkout($payment_method, $order, $flow);
// If we got one back...
if (!empty($token)) {
// Set the Express Checkout data array.
$order->data['commerce_paypal_rb'] = array(
'flow' => 'ec',
'token' => $token,
'payerid' => FALSE,
);
// Set the redirect to PayPal.
$form_state['redirect'] = commerce_paypal_rb_checkout_url($payment_method['settings']['server'], $order->data['commerce_paypal_rb']['token']);
// Update the order status to the payment redirect page.
commerce_order_status_update($order, 'checkout_payment', FALSE, NULL, t('Customer clicked the Express Checkout button on the cart page.'));
// Save the changes to the order data array.
commerce_order_save($order);
}
else {
// Otherwise show an error message and remain on the cart page.
drupal_set_message(t('Redirect to PayPal Express Checkout failed. Please try again or contact an administrator to resolve the issue.'), 'error');
$form_state['redirect'] = 'cart';
}
}
/**
* Payment method callback: adds a message to the submission form if enabled in
* the payment method settings.
*/
function commerce_paypal_rb_submit_form($payment_method, $pane_values, $checkout_pane, $order) {
$form = array();
if (!empty($payment_method['settings']['show_payment_instructions'])) {
$form['paypal_ec_information'] = array(
'#markup' => '<span class="commerce-paypal-ec-info">' . t('(Continue with checkout to complete payment via PayPal.)') . '</span>',
);
}
return $form;
}
/**
* Payment method callback: submit form validation.
*/
function commerce_paypal_rb_submit_form_validate($payment_method, $pane_form, $pane_values, $order, $form_parents = array()) {
// Return an error if the enabling action's settings haven't been configured.
foreach (array('api_username', 'api_password', 'api_signature') as $key) {
if (empty($payment_method['settings'][$key])) {
drupal_set_message(t('PayPal Express Checkout is not configured for use. Please contact an administrator to resolve this issue.'), 'error');
return FALSE;
}
}
return TRUE;
}
/**
* Payment method callback: submit form submission.
*/
function commerce_paypal_rb_submit_form_submit($payment_method, $pane_form, $pane_values, $order, $charge) {
// Update the order to reference the PayPal Express Checkout payment method.
$order->data['payment_method'] = $payment_method['instance_id'];
// Generate a payment redirect key.
$order->data['payment_redirect_key'] = drupal_hash_base64(time());
// Request a token from Express Checkout.
$token = commerce_paypal_rb_set_express_checkout($payment_method, $order, 'mark');
// If we got one back...
if (!empty($token)) {
// Set the Express Checkout data array and proceed to the redirect page.
$order->data['commerce_paypal_rb'] = array(
'flow' => 'mark',
'token' => $token,
'payerid' => FALSE,
);
return TRUE;
}
else {
// Otherwise show an error message and remain on the current page.
drupal_set_message(t('Communication with PayPal Express Checkout failed. Please try again or contact an administrator to resolve the issue.'), 'error');
return FALSE;
}
}
function commerce_paypal_rb_set_express_checkout($payment_method, $order, $flow) {
// Extract the order total value array.
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
$order_total = $order_wrapper->commerce_order_total->value();
// Determine the currency code to use to actually process the transaction,
// which will either be the default currency code or the currency code of the
// order if it's supported by PayPal if that option is enabled.
$currency_code = $payment_method['settings']['currency_code'];
if (!empty($payment_method['settings']['allow_supported_currencies']) && in_array($order_total['currency_code'], array_keys(commerce_paypal_currencies('paypal_ec')))) {
$currency_code = $order_total['currency_code'];
}
// Build a name-value pair array for this transaction.
$nvp = array(
'METHOD' => 'SetExpressCheckout',
// Default the Express Checkout landing page to the Mark solution.
'SOLUTIONTYPE' => 'Mark',
'LANDINGPAGE' => 'Login',
// Disable entering notes in PayPal, as we don't have any way to accommodate
// them right now.
'ALLOWNOTE' => '0',
//'PAYMENTREQUEST_0_PAYMENTACTION' => commerce_paypal_payment_action($payment_method['settings']['txn_type']),
'PAYMENTREQUEST_0_AMT' => 0,//commerce_paypal_price_amount($order_total['amount'], $order_total['currency_code']),
// Set the return and cancel URLs.
'RETURNURL' => url('checkout/' . $order->order_id . '/payment/return/' . $order->data['payment_redirect_key'], array('absolute' => TRUE)),
'CANCELURL' => url('checkout/' . $order->order_id . '/payment/back/' . $order->data['payment_redirect_key'], array('absolute' => TRUE)),
);
$nvp['BILLINGTYPE'] = 'RecurringPayments';
$nvp['BILLINGAGREEMENTDESCRIPTION'] = commerce_paypal_rb_build_subscription_desc($order);
// If reference transactions are enabled and a billing agreement is supplied...
/* if (!empty($payment_method['settings']['reference_transactions']) &&
!empty($payment_method['settings']['ba_desc'])) {*/
$nvp['L_BILLINGTYPE0'] = 'RecurringPayments';
$nvp['L_BILLINGAGREEMENTDESCRIPTION0'] = $payment_method['settings']['ba_desc'];
$nvp['L_DESC0'] = commerce_paypal_rb_build_subscription_desc($order);
//}
// Add itemized information to the API request.
//$nvp += commerce_paypal_rb_itemize_order($order, $currency_code);
// If Express Checkout Account Optional is enabled...
if ($payment_method['settings']['ec_mode'] != 'Mark') {
// Update the solution type and landing page parameters accordingly.
$nvp['SOLUTIONTYPE'] = 'Sole';
if ($payment_method['settings']['ec_mode'] == 'SoleBilling') {
$nvp['LANDINGPAGE'] = 'Billing';
}
}
// Otherwise disable shipping options entirely.
$nvp['NOSHIPPING'] = '1';
// Submit the SetExpressCheckout API request to PayPal.
$response = commerce_paypal_api_request($payment_method, $nvp, $order);
// If the request is successful, return the token.
if (in_array($response['ACK'], array('SuccessWithWarning', 'Success'))) {
return $response['TOKEN'];
}
// Otherwise indicate failure by returning FALSE.
return FALSE;
}
/**
* Payment method callback: redirect form.
*/
function commerce_paypal_rb_redirect_form($form, &$form_state, $order, $payment_method) {
// If we didn't get a valid redirect token...
if (empty($order->data['commerce_paypal_rb']['token'])) {
// Clear the payment related information from the data array.
unset($order->data['payment_method']);
unset($order->data['commerce_paypal_rb']);
// Show an error message and go back a page.
drupal_set_message(t('Redirect to PayPal Express Checkout failed. Please try again or contact an administrator to resolve the issue.'), 'error');
commerce_payment_redirect_pane_previous_page($order, t('Redirect to PayPal Express Checkout failed.'));
}
elseif (!in_array(arg(3), array('back', 'return'))) {
// Otherwise go ahead and redirect to PayPal.
drupal_goto(commerce_paypal_rb_checkout_url($payment_method['settings']['server'], $order->data['commerce_paypal_rb']['token']));
}
}
/**
* Payment method callback: redirect form back callback.
*/
function commerce_paypal_rb_redirect_form_back($order, $payment_method) {
// Display a message indicating the customer initiatied cancellation.
drupal_set_message(t('You have canceled checkout at PayPal but may resume the checkout process here when you are ready.'));
// Remove the payment information from the order data array.
$flow = $order->data['commerce_paypal_rb']['flow'];
unset($order->data['commerce_paypal_rb']);
unset($order->data['payment_method']);
// If the customer initially redirected to PayPal from the cart form...
if ($flow == 'ec') {
// Send them back to the shopping cart page instead of the previous page in
// the checkout process.
commerce_order_status_update($order, 'cart', FALSE, NULL, t('Customer canceled Express Checkout at PayPal.'));
drupal_goto('cart');
}
}
/**
* Payment method callback: redirect form return validation.
*/
function commerce_paypal_rb_redirect_form_validate($order, $payment_method) {
$payment_method['settings'] += commerce_paypal_rb_default_settings();
if (!empty($payment_method['settings']['ipn_logging']) &&
$payment_method['settings']['ipn_logging'] == 'full_ipn') {
watchdog('commerce_paypal_rb', 'Customer returned from PayPal with the following POST data:!ipn_data', array('!ipn_data' => '<pre>' . check_plain(print_r($_POST, TRUE)) . '</pre>'), WATCHDOG_NOTICE);
}
// This may be an unnecessary step, but if for some reason the user does end
// up returning at the success URL with a Failed payment, go back.
if (!empty($_POST['payment_status']) && $_POST['payment_status'] == 'Failed') {
return FALSE;
}
// Don't attempt to verify the Express Checkout details without a valid token.
if (empty($order->data['commerce_paypal_rb']['token'])) {
return FALSE;
}
// Build a name-value pair array to obtain buyer information from PayPal.
$nvp = array(
'METHOD' => 'GetExpressCheckoutDetails',
'TOKEN' => $order->data['commerce_paypal_rb']['token'],
);
// Submit the API request to PayPal.
$response = commerce_paypal_api_request($payment_method, $nvp, $order);
// If the request failed, exit now with a failure message.
if ($response['ACK'] == 'Failure') {
return FALSE;
}
// If payment is ok, create payment profile
// $order->data['commerce_paypal_rb']['profileid'] = commerce_paypal_rb_create_profile($payment_method, $order);
/*
if(!$order->data['commerce_paypal_rb']['profileid'])
return false;*/
// Set the Payer ID used to finalize payment.
$order->data['commerce_paypal_rb']['payerid'] = $response['PAYERID'];
// If the user is anonymous, add their PayPal e-mail to the order.
if (empty($order->mail)) {
$order->mail = $response['EMAIL'];
}
// Create a billing information profile for the order with the available info.
if (!empty($payment_method['settings']['update_billing_profiles'])) {
commerce_paypal_rb_customer_profile($order, 'billing', $response, 'PAYMENTREQUEST_0_');
}
// If the shipping module exists on the site, create a shipping information
// profile for the order with the available info.
if (module_exists('commerce_shipping') && !empty($payment_method['settings']['update_shipping_profiles'])) {
commerce_paypal_rb_customer_profile($order, 'shipping', $response, 'PAYMENTREQUEST_0_');
}
// Recalculate the price of products on the order in case taxes have
// changed or prices have otherwise been affected.
if ($order->data['commerce_paypal_rb']['flow'] == 'ec') {
commerce_cart_order_refresh($order);
}
// Save the changes to the order.
commerce_order_save($order);
// If the customer completed payment using the Mark flow, then we should
// attempt to process payment now and go back if it fails.
if ($order->data['commerce_paypal_rb']['flow'] == 'mark') {
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
$charge = $order_wrapper->commerce_order_total->value();
// Attempt to process the payment.
if (!commerce_paypal_rb_do_payment($payment_method, $order, $charge)) {
return FALSE;
}
}
}
function commerce_paypal_rb_create_profile($payment_method, $order) {
// Extract the order total value array.
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
$order_total = $order_wrapper->commerce_order_total->value();
$currency_code = $payment_method['settings']['currency_code'];
if (!empty($payment_method['settings']['allow_supported_currencies']) && in_array($order_total['currency_code'], array_keys(commerce_paypal_currencies('paypal_ec')))) {
$currency_code = $order_total['currency_code'];
}
$nvp = array(
'METHOD' => 'CreateRecurringPaymentsProfile',
'TOKEN' => $order->data['commerce_paypal_rb']['token'],
'PROFILESTARTDATE' => strtotime ( '+1 month' , strtotime ( date('c') ) ) ,
'PROFILEREFERENCE' => $order->order_number,
'DESC' => commerce_paypal_rb_build_subscription_desc($order),
'MAXFAILEDPAYMENTS' => '1',
'AUTOBILLAMT' => 'AddToNextBilling',
'BILLINGPERIOD' => 'Month',
'BILLINGFREQUENCY' => '1',
'TOTALBILLINGCYCLES' => '10',
'AMT' => commerce_paypal_price_amount($order_total['amount'], $order_total['currency_code']),
'CURRENCYCODE' => $currency_code,
'TAXAMT' => '0'
);
// Submit the API request to PayPal.
$response = commerce_paypal_api_request($payment_method, $nvp, $order);
// If the request is successful, return the token.
if (in_array($response['ACK'], array('SuccessWithWarning', 'Success'))) {
return $response['PROFILEID'];
}
// Otherwise indicate failure by returning FALSE.
return FALSE;
}
function commerce_paypal_rb_build_subscription_desc($order){
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
$desc = array();
foreach($order_wrapper->commerce_line_items->getIterator() as $item){
if(!empty($item->commerce_product)){
$total = $item->commerce_unit_price->value();
$desc[] = $item->commerce_product->title->value() . ' ' . commerce_currency_format($total['amount'], $total['currency_code']).'/Mes';
}
}
if(!empty($desc)){
return t('Subscription to : @items', array('@items' => implode($desc, ', ')));
}
return false;
}
/**
* Payment method callback: redirect form return submission.
*/
function commerce_paypal_rb_redirect_form_submit($order, $payment_method) {
// Because we need to be able to halt checkout completion if payment fails for
// some reason, instead of getting and processing Express Checkout payment
// details in the submission step, we do this in the validate step above.
}
/**
* Payment method callback: validate an IPN based on receiver e-mail address,
* price, and other parameters as possible.
*/
function commerce_paypal_rb_paypal_ipn_validate($order, $payment_method, $ipn) {
// Prepare a trimmed list of receiver e-mail addresses.
if (!empty($payment_method['settings']['receiver_emails'])) {
$receiver_emails = explode(',', $payment_method['settings']['receiver_emails']);
}
else {
$receiver_emails = array();
}
foreach ($receiver_emails as $key => &$email) {
$email = trim(strtolower($email));
}
// Return FALSE if the receiver e-mail does not match the one specified by
// the payment method instance.
if (!empty($ipn['receiver_email']) && !in_array(trim(strtolower($ipn['receiver_email'])), $receiver_emails)) {
commerce_payment_redirect_pane_previous_page($order);
watchdog('commerce_paypal_rb', 'IPN rejected: invalid receiver e-mail specified (@receiver_email); must match a receiver e-mail address configured in the payment method settings.', array('@receiver_email' => $ipn['receiver_email']), WATCHDOG_NOTICE);
return FALSE;
}
// Prepare the IPN data for inclusion in the watchdog message if enabled.
$ipn_data = '';
if (!empty($payment_method['settings']['ipn_logging']) &&
$payment_method['settings']['ipn_logging'] == 'full_ipn') {
$ipn_data = '<pre>' . check_plain(print_r($ipn, TRUE)) . '</pre>';
}
// Log a message including the PayPal transaction ID if available.
if (!empty($ipn['txn_id'])) {
watchdog('commerce_paypal_rb', 'IPN validated for Order @order_number with ID @txn_id.!ipn_data', array('@order_number' => $order->order_number, '@txn_id' => $ipn['txn_id'], '!ipn_data' => $ipn_data), WATCHDOG_NOTICE);
}
else {
watchdog('commerce_paypal_rb', 'IPN validated for Order @order_number.!ipn_data', array('@order_number' => $order->order_number, '!ipn_data' => $ipn_data), WATCHDOG_NOTICE);
}
}
/**
* Payment method callback: process an IPN once it's been validated.
*/
function commerce_paypal_rb_paypal_ipn_process($order, $payment_method, &$ipn) {
// Do not perform any processing on EC transactions here that do not have
// transaction IDs, indicating they are non-payment IPNs such as those used
// for subscription signup requests.
if (empty($ipn['txn_id'])) {
return FALSE;
}
// Exit when we don't get a payment status we recognize.
if (!in_array($ipn['payment_status'], array('Failed', 'Voided', 'Pending', 'Completed', 'Refunded'))) {
commerce_payment_redirect_pane_previous_page($order);
return FALSE;
}
// If this is a prior authorization capture IPN...
if (in_array($ipn['payment_status'], array('Voided', 'Completed')) && !empty($ipn['auth_id'])) {
// Ensure we can load the existing corresponding transaction.
$transaction = commerce_paypal_payment_transaction_load($ipn['auth_id']);
// If not, bail now because authorization transactions should be created by
// the Express Checkout API request itself.
if (!$transaction) {
watchdog('commerce_paypal_rb', 'IPN for Order @order_number ignored: authorization transaction already created.', array('@order_number' => $order->order_number), WATCHDOG_NOTICE);
return FALSE;
}
}
elseif (in_array($ipn['payment_status'], array('Failed', 'Refunded'))) {
// Ensure there isn't already an existing corresponding transaction.
$transaction = commerce_paypal_payment_transaction_load($ipn['txn_id']);
// If so, bail now because the refund transaction was created by the Express
// Checkout API request itself.
if ($transaction) {
watchdog('commerce_paypal_rb', 'IPN for Order @order_number ignored: refund transaction already created.', array('@order_number' => $order->order_number), WATCHDOG_NOTICE);
return FALSE;
}
// Otherwise if this is a failed bank payment or refund, create a new
// payment transaction to log it to the order.
$transaction = commerce_payment_transaction_new('paypal_ec', $order->order_id);
$transaction->instance_id = $payment_method['instance_id'];
}
else {
// In other circumstances, exit the processing, because we handle those
// cases directly during API response processing.
watchdog('commerce_paypal_rb', 'IPN for Order @order_number ignored: this operation was accommodated in the direct API response.', array('@order_number' => $order->order_number), WATCHDOG_NOTICE);
return FALSE;
}
$transaction->remote_id = $ipn['txn_id'];
$transaction->amount = commerce_currency_decimal_to_amount($ipn['mc_gross'], $ipn['mc_currency']);
$transaction->currency_code = $ipn['mc_currency'];
$transaction->payload[REQUEST_TIME . '-ipn'] = $ipn;
if (!empty($transaction->message)) {
$transaction->message .= '<br />';
}
// Set the transaction's statuses based on the IPN's payment_status.
$transaction->remote_status = $ipn['payment_status'];
// If we didn't get an approval response code...
switch ($ipn['payment_status']) {
case 'Failed':
$transaction->status = COMMERCE_PAYMENT_STATUS_FAILURE;
$transaction->message .= t("The payment has failed. This happens only if the payment was made from your customer’s bank account.");
break;
case 'Voided':
$transaction->status = COMMERCE_PAYMENT_STATUS_FAILURE;
$transaction->message .= t('The authorization was voided.');
break;
case 'Pending':
$transaction->status = COMMERCE_PAYMENT_STATUS_PENDING;
$transaction->message .= commerce_paypal_ipn_pending_reason($ipn['pending_reason']);
break;
case 'Completed':
$transaction->status = COMMERCE_PAYMENT_STATUS_SUCCESS;
$transaction->message .= t('The payment has completed.');
break;
case 'Refunded':
$transaction->status = COMMERCE_PAYMENT_STATUS_SUCCESS;
$transaction->message .= t('Refund for transaction @txn_id', array('@txn_id' => $ipn['parent_txn_id']));
break;