/
PaypalExpress.pm
2143 lines (1841 loc) · 108 KB
/
PaypalExpress.pm
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
# Vend::Payment::PaypalExpress - Interchange Paypal Express Payments module
#
# Copyright (C) 2015 Zolotek Resources Ltd
# All Rights Reserved.
#
# Author: Lyn St George <lyn@zolotek.net>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public
# License along with this program; if not, write to the Free
# Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307 USA.
#
package Vend::Payment::PaypalExpress;
=head1 NAME
Vend::Payment::PaypalExpress - Interchange Paypal Express Payments Module
=head1 PREREQUISITES
SOAP::Lite
XML::Parser
MIME::Base64
URI
libwww-perl
Crypt::SSLeay
IO::Socket::SSL (version 0.97 until 0.99x is fixed for the "illegal seek" error, or a later one that works)
Date::Calc - new for v1.1.0
Test for current installations with: perl -MSOAP::Lite -e 'print "It works\n"'
=head1 DESCRIPTION
The Vend::Payment::PaypalExpress module implements the paypalexpress() routine
for use with Interchange.
#=========================
=head1 SYNOPSIS
Quick start:
Place this module in <ic_root>/lib/Vend/Payment, and call it in <ic_root>/interchange.cfg with
Require module Vend::Payment::PaypalExpress. Ensure that your perl installation contains the modules
listed above and their pre-requisites.
Logon to your Paypal Business (not Personal) account and go to 'Profile' -> 'API access' ->
'Request API Credentials' -> 'Signature'. This will generate a user id, password and signature.
Add to catalog.cfg all marked 'required', optionally the others:
Route paypalexpress id xxx (required_
Route paypalexpress password xxx (required)
Optionally for this updated version, you may prefix the three credentials above some unique
identifier, eg 'gbp', 'usd', 'sandbox' and the module will switch between them on the fly.
Useful if you have different Paypal a/cs in different currencies and want to choose the
a/c used based on the currency chosen by the customer.
Route paypalexpress signature xxx (required: use the 3-token system, not the certificate system at Paypal)
Route paypalexpress returnurl your_full_URL/paypalgetrequest (required)
Route paypalexpress cancelurl your_full_URL/your_cancellation_page (required)
Route paypalexpress host api-3t.sandbox.paypal.com (for testing)
Route paypalexpress host api-3t.paypal.com (required: live host, one of this or the above but not both)
Route paypalexpress currency EUR|GBP|USD|CAD|AUD (optional, defaults to USD)
Route paypalexpress pagestyle (optional, set up at Paypal)
Route paypalexpress paymentaction Sale (optional, defaults to 'Sale')
Route paypalexpress headerimg 'secure URL' (optional, though must be served from a secure URL if used)
Optionally, you may set the return URL in the page as
<input type=hidden name=returnurl value=your_url>,
and similarly the cancelurl may be set in the page.
To have Paypal co-operate with your normal payment service provider, eg Authorizenet, do the following:
Leave the MV_PAYMENT_MODE variable in catalog.cfg and products/variable.txt set to your normal payment processor.
Add to etc/profiles.order:
__NAME__ paypalexpress
__COMMON_ORDER_PROFILE__
&fatal = yes
email=required
email=email
&set=mv_payment PaypalExpress
&set=psp Paypal
&set=mv_payment_route paypalexpress
&final = yes
&setcheck = payment_method paypalexpress
__END__
or, if you want to use Paypal as a 'Buy now' button without taking any customer details, then omit the
__COMMON_ORDER_PROFILE__ and the two 'email=...' lines above.
Within the 'credit_card' section of etc/profiles.order leave "MV_PAYMENT_MODE" as set,
and add
&set=psp __MV_PAYMENT_PSP__
&set=mv_payment_route authorizenet
(or your preferred gateway instead of authorizenet) as the last entries in the section.
NB: if you are taking offline payments then do not set mv_payment_route here, but instead set in the body
of the 'Buy now' button "mv_payment_route=offlinepayment
mv_order_profile=credit_card"
and install the OfflinePayment.pm module so as to have a named alternative payment route in catalog.cfg.
and then add
Variable MV_PAYMENT_PSP "foo"
to catalog.cfg, where "foo" is the name of your gateway or acquirer, formatted as you want it to appear
on the receipt. Eg, "Bank of America" (rather than boa), "AuthorizeNet" (rather than authorizenet).
In etc/log_transction, immediately after the
[elsif variable MV_PAYMENT_MODE]
[calc]
insert this line:
undef $Session->{payment_result}{MStatus};
and leave
[elsif variable MV_PAYMENT_MODE]
as set (contrary to previous revisions of this document) but within the same section change the following
two instances of [var MV_PAYMENT_MODE] to [value mv_payment_route]. In particular, the setting inside the
[charge route="..] line will specify which payment processor is used for each particular case, and you
need to further modify this line so that it ends up like this:
[tmp name="charge_succeed"][charge route="[value mv_payment_route]" pprequest="dorequest" amount="[scratch tmp_remaining]" order_id="[value mv_transaction_id]"][/tmp]
If the value of 'mv_payment_route' is set to 'paypalexpress', then this is the one that is run. It is only
called via log_transaction after the customer has returned from Paypal and clicks the 'final' pay button,
hence this is where the final 'pprequest=dorequest' value is sent.
Add into the end of the "[import table=transactions type=LINE continue=NOTES no-commit=1]" section
of etc/log_transaction:
psp: [value psp]
pptransactionid: [calc]$Session->{payment_result}{TransactionID}[/calc]
pprefundtransactionid: [calc]$Session->{payment_result}{RefundTransactionID}[/calc]
ppcorrelationid: [calc]$Session->{payment_result}{CorrelationID};[/calc]
pppayerstatus: [value payerstatus]
ppaddressstatus: [value address_status]
and add these 6 new columns into your transactions table as type varchar(256).
You will have records of which transactions went through which payment service providers, as well
as Paypal's returned IDs. The CorrelationID is the one you need in any dispute with them. The payerstatus
and addressstatus results may be useful in the order fulfillment process.
Add these lines into the body of the 'submit' button that sends the customer to Paypal.
[run-profile name=paypalexpress]
[if type=explicit compare="[error all=1 show_var=1 keep=1]"]
mv_nextpage=ord/checkout
[/if]
[charge route="paypalexpress" pprequest="setrequest"]
mv_todo=return
Create a page 'ord/paypalgetrequest.html', and make it the target of the returnURL from Paypal:
[charge route="paypalexpress" pprequest="getrequest"]
[bounce href="[area ord/paypalcheckout]"]
Create a page 'paypalcheckout.html' in the pages/ord folder. This should display just the basket and address
or whatever you choose for the final pages, plus an IC button with:
mv_order_profile=paypalexpress
mv_todo=submit
in the body part as the submit button to finalise the order. 'dorequest' is set in log_transaction.
You may then use PaypalExpress for any transaction where the 'mv_order_profile' is set to paypalexpress
but still use the "credit_card" 'mv_order_profile' for other transactions, eg for Authorizenet. Of
course, if PaypalExpress is to be your only payment method, then simply add:
Variable MV_PAYMENT_MODE paypalexpress
to catalog.cfg just before the paypalexpress Route entries, and this route will be the default.
Note that because Paypal do not recognise UK as a country, only GB, you need to set up shipping in
your country.txt for GB as well as UK. Note also that Paypal do not return the customer's telephone
number by default, so you may need to adjust your order profiles to compensate.
Also note that Paypal requires the user to have cookies enabled, and if they're not will return an error page with no
indication of the real problem. You may want to warn users of this.
The flow is: the first button for Paypal sends a request to Paypal to initialise the transaction and gets a token
back in return. If Paypal fails to send back a token, then the module refreshes that page with an error message
suggesting that the customer should use your normal payment service provider and shows the cards that you accept.
Once the token is read, then your customer is taken to Paypal to login and choose his payment method. Once that is
done, he returns to us and hits the 'paypalgetrequest' page. This gets his full address as held by Paypal, bounces to
the final 'paypalcheckout' page and populates the form with his address details. If you have both shipping
and billing forms on that page, the shipping address will be populated by default but you may force
the billing form to be populated instead by sending
<input type=hidden name=pp_use_billing_address value=1>
at the initial stage. Then the customer clicks the final 'pay now' button and the transaction is done.
Options that may be set either in the route or in the page:
* reqconfirmshipping - this specifies that a Paypal customer must have his address 'confirmed'
* addressoverride - this specifies that you will ship only to the address IC has on file (including
the name and email); your customer needs to login to IC first before going to Paypal
* use_billing_override - sends billing address instead of shipping to PayPal (use with addressoverride)
* other options are also settable.
Testing: while the obvious test choice is to use their sandbox, I've always found it a bit of a dog's breakfast
and never trusted it. Much better to test on the live site, and just recyle money between your personal and
business accounts at minimal cost to yourself, but with the confidence of knowing that test results are correct.
Recurring Payments:
you need a number of new fields in the products table for the parameters required by
Paypal, viz:
rpdeposit: gross amount for a deposit
rpdepositfailedaction: ContinueOnFailure - Paypal will added failed amount to outstanding balance
CancelOnFailure (or empty) - Paypal sets status to Pending till inital payment completes, then
sends IPN to notify of either the status becoming Active or the payment failing
rptrialamount: nett amount
rptrialtaxamount:
rptrialshippingamount:
rptrialperiod: one of Day, Week, SemiMonth, Month.
rptrialfrequency: integer, number of periods between payments, eg "every 2 weeks"
rptrialtotalcycles: total number of trial payments before regular payments start
rpamount: nett amount for regular payments
rptaxamount:
rpshippingamount:
rpperiod: one of Day, Week, SemiMonth, Month
rpfrequency: integer, number of periods between payments, eg "every 2 weeks"
NB:/ multiple of period * frequency cannot be greater than one year as maximum interval between payments
rptotalcycles: total number of regular payments - can be empty
rpstartdate: leave empty to use current date. An absolute date must be in the 2011-02-25T00:00:00Z
format. An interval from the current date should use "2 weeks", "5 days" as the format, where
the period can be any given above except SemiMonth (this is always billed on the 1st and
15th of the month)
rpmaxfailedpayments: number of failures before the agreement is automatically cancelled
rpautobillarrears: NoAutoBill, AddToNextBilling - Paypal automatically takes requested action
Displaying the recurring payment amounts taken at order time is quite straightforward - if you want
to do that then put the total to be taken into the price field, nett of tax or shipping.
You could then modify the receipt page and receipt emails with a new field something like:
[if-item-field rpperiod]
[tmp][item-calc]$rpno++[/item-calc][/tmp]
Ref: [value mv_order_number]-sub[item-calc]$rpno[/item-calc]
<br>ID: [data table=transactions col=order_id key='[value mv_order_number]-sub[item-calc]$rpno[/item-calc]']
<br>Status: [data table=transactions col=status key='[value mv_order_number]-sub[item-calc]$rpno[/item-calc]']
[/if-item-field]
Where:
ID = rpprofileid (the primary identifier on the customer's Paypal account page),
Ref = rpprofilereference (your order number, appended with '-subn' where n is a number from 1 to 10),
Status = rpprofilestatus (Pending or Active, but Cancelled and Suspended are also valid)
If you want to log the key values for each recurring profile, then add these fields to the orderline table:
rpperiod varchar(32)
rpfrequency varchar(32)
rpprofileid varchar(64)
rpprofilereference varchar(64)
rpprofilestatus varchar(32)
rpgrossamount varchar(32)
rpcorrelationid varchar(64)
and at the beginning of the orderline section of log_transaction, around line 462, add
[calc] $rpno = 0; [/calc]
just before "[item-list] Added [item-code] to orderline:"
and then between "[item-list]" and "[import table=orderline ...]" add:
[if-item-field rpperiod]
[item-calc]$rpno++[/item-calc]
[seti rpprofileid][data table=transactions col=order_id key='[value mv_order_number]-sub[item-calc]$rpno[/item-calc]'][/seti]
[charge route="[value mv_payment_route]" pprequest="getrpdetails" rpprofileid="[scratchd rpprofileid]"]
[/if-item-field]
and then between [import ..] and [/import]
add:
rpprofileid: [scratchd rpprofileid]
rpprofilereference: [scratchd rpprofilereference]
rpprofilestatus: [scratchd rpprofilestatus]
rpgrossamount: [scratchd rpgrossamount]
rpperiod: [scratchd rpperiod]
rpfrequency: [scratchd rpfrequency]
rpcorrelationid: [scratchd rpcorrelationid]
Calling 'getrpdetails' as above returns everything Paypal holds about that transaction and makes it available
in scratch space:
rpcorrelationid
rpprofilereference
rpprofileid
rpdescription
rpprofilestatus
rpsubscribername
rpstartdate (formatted for [convert-date])
rptaxamount
rpshippingamount
rpamount
rpgrossamount (including tax and shipping, amount for each regular payment)
rpfrequency
rpperiod
rptotalycles (total committed to)
rpnextbillingdate (formatted for [convert-date])
rpcyclesmade (number of payments made)
rpcyclesfailed (number of payaments failed)
rpcyclesremaining (number of payments left to go)
rparrears (amount oustanding)
rpmaxfailedpayments (number of failed payments allowed by merchant)
rptrialamount
rptrialtaxamount
rptrialshippingamount
rptrialfrequency
rptrialperiod
rptrialtotalcycles
rptrialgrossamount
rpfinalpaymentduedate
rpregularamountpaid (amount paid to date)
rptrialamountpaid
ItemDetails now passed and displayed in the 'new style' Paypal checkout. Discounts/coupons
are not passed, as there is too much scope for error with currency conversions etc which
would cause Paypal to reject the transaction, but instead a note to the buyer will be displayed if
the value of pp_discount_note is passed as true.
The order number is now set prior to going to Paypal, as they need a Profile Reference
and the most sensible way to handle this is to set the order number and append a unique
reference for each recurring agreement set up. This also means that the customer's Paypal
account page will show the IC order number as well as Paypal's ProfileID for simpler correlation.
You may setup a recurring billing agreement and profile with or without an accompanying
purchase or possibly without any initial payment - if without then the amount sent is zero.
# ### FIXME
To allow Interchange to log a zero amount,
change log_transaction to:
[unless scratch allowzeropayment]
[if scratch tmp_remaining == 0]
Fully paid by payment cert.
[/if]
[/unless]
around line 80, and around line 221
[if scratchd ordernumberalreadyset]
Order number already set by PaypalExpress
[else]
Set order number in values: [value
.....
$Session->{mv_order_number} = $Values->{mv_order_number};
[/calc]
[/else]
[/if]
to stop IC setting the order number again
There are also a number of functions which could be handled by an admin panel or virtual
terminal.
Manage Recurring Payments:
this will cancel, suspend or reactive a profile. It expects to find the customer's
ProfileID in the orderline table as rpprofileid, and will return a new correlationid.
Send managerp_cancel, managerp_suspend, or managerp_reactivate from your virtual
terminal as a 'pprequest' along with the customer's profileID as an IC 'value'.
Modify Recurring Payments;
this allows you to add cycles to the payment profile, change addresses, change amount
to be paid. You cannot increase the amount by more than 20% pa.
Masspay:
this works for a list of up to 250 recipients, but this function is apparently being phased
out - certainly in the UK they will not enable masspay any more. Note that the currency
sent must be the same as the currency the sending account is in, and you only get one
ID returned for the entire masspayment. The module expects a list as [value vtmessage],
consisting of four comma-separated and quoted fields per record, one record per line:
"email address (or paypal ID)","amount (without currency symbols)","unique ID","notes"
The notes field may be empty but must be quoted. You may also send a subject for the email
that Paypal sends to each recipient, as [value email_subject], defaulting to 'Paypal payment'
if not set. All recipients must be either email addresses or paypal IDs, not a mixture of both.
All payments must be in the same currency for each list sent, and the currency set is the same
as taken by the main routines; see above.
Other functions added, as Route parameters or IC or HTML values
allowed_payment_method: Default = any; AnyFundingSource = any chosen by buyer irrespective of profile;
InstantOnly = only instant payments; InstantFundingSource = only instant methods, blocks
echeck, meft, elevecheck
soft_descriptor: shown on customer's card receipt as transaction description
brand_name: overrides business name shown to customer
gift_message_enable: 0 or 1
gift_receipt_enable: 0 or 1
gift_receipt_enable: 0 or 1
gift_wrap_name: string
buyer_email_optin: 0 or 1
survey_enable: 0 or 1
allow_push_funding: 0 or 1
allow_note: 0 or 1
service_phone: displayed to customer at PaypalExpress
notify_url: for IPN callbacks
=head1 Bugs
Including total_type causes all child elements of the initial Set request to be ignored, thereby
removing recurring payment BillingAgreeements and all payment detail items from view, which
in turn means there is no order total and so the request is rejected.
Including brand_name does the same as above but only when a BillingAgreeement is included in the
request - hence the module excludes this setting when a BillingAgreeement is included, but sets
it otherwise.
SOAP::Lite v0.715 may crash with an error on ln1993 of Lite.pm - backlevelling the version will make
this error go away.
=head1 Changelog
version 1.1.6 November 2015
- more minor bug fixes
version 1.1.5 February 2015
- bug fix in XML entities handling
version 1.1.4 January 2015
- further stricter handling of XML entities
version 1.1.3 September 2014
- update to allow LandingPage to be set to either Login or Billing
- stricter handling of XML entities to suit Paypal's stricter handling
version 1.1.2 March 2013
- bugfix for rounding errors when sending basket in the 'dorequest'
- set $Config->{PriceField} to $::Scratch->{PriceField} if defined
version 1.1.1 November 2012
- incorporated Racke's updates
- stripped locale tags from data displayed in the basket at Paypal
- truncated description field displayed in itemised basket at paypal
version 1.1.0 October 2011
- major update:
- enabled 'item details' in initial request, so the new-style Paypal checkout page shows
an itemised basket
- updated masspay to handle multiple recipients properly
- added refunds, either full or partial
- added 'getbalance', to get the balance of the calling account or any other account for
which the credentials are known. If account is multi-currency, then all balances and currencies
are displayed in a scratch value.
- added 'sendcredit', which sends funds to a specified credit card. You need to know the full
billing address and cv2 number, and need to get Paypal to enable this function on your account
- added repeat payments, ie recurring billing. Up to the Paypal limit of 10 billing agreements
may be set up in one request. Billing agreements may be set up with optional trial periods and
deposits, and may be setup with or without an accompanying standard purchase.
- added function to manage repeat payments, ie suspend, reactivate, or cancel
- added function to modify repeat payments, ie to alter the billing/shipping address or name,
to alter the amount or period etc
- added function to get details of a repeat payments billing agreement, and display the results
in scratch space including date of next payment, amount paid to date, etc
- added function to bill any outstanding arrears in a billing agreement
- requires Date::Calc now
version 1.0.8 July 2010
- fixed bug in handling of multiple PP error messages
version 1.0.7 December 2009
- another variation in Canadian Province names has just come to light, whereby they sometimes send
the 2 letter code with periods, eg B.C. as well as BC. Thanks to Steve Graham for finding this
- patch to allow use of the [assign] tag in shipping
- patch to allow 'use_billing_override' to send billing addresses
- patch to display Long rather than Short PP error message to customers
Thanks to Josh Lavin for these last three
version 1.0.6 September 2009
- added 'use strict' and fixed odd errors (and removed giropay vestiges that belong in next version)
- made itemdetails loop through basket properly
- added Fraud Management Filters return messages to optional charge parameters
version 1.0.5, June 2009
- fixed bug with Canadian provinces: PP were sending shortened versions of 2 province names, and also
sometimes sending the 2 letter code (possibly from older a/cs) rather than the full name. Thanks to
Steve Graham for finding this.
version 1.0.4, May 2009
- re-wrote documentation, including revised and simplified method of co-operating with other payment
systems in log_transaction.
version 1.0.3, 1.02.2009
- fixed bug in handling of thousands separator
version 1.0.2, 22.01.2009
- conversion of Canadian province names to 2 letter variant is now the default
- fixed bug with conversion of Canadian province names to 2 letter variant
- changed method of reading value of pprequest
- added failsafe logging to orders/paypal/ in case of order route failure
- fixed bug whereby PP returns billing name in a shipping address
- added note to docs re PP requiring cookie
- altered internal redirection code to better handle absence of cookies (thanks to Peter Ajamian for heads-up)
- altered docs to reflect the new sandbox (thanks to Josh Lavin for the heads-up on that)
- TODO: as the new API now includes a SOAP integration of recurring/subscription billing, need
to convert existing name=value pair IPN module and integrate into this module. Will add
masspay, refund and other functions at the same time.
version 1.0.1, 24.05.2008
- added error message to IC session for when Paypal returns error message instead of token.
- added option to convert Canadian state/province names to an uppercased 2 letter variant, so
as to agree with Interchange's de facto requirement for this.
=back
=head1 AUTHORS
Lyn St George <info@zolotek.net>
=cut
BEGIN {
eval {
package Vend::Payment;
require SOAP::Lite or die __PACKAGE__ . " requires SOAP::Lite";
# without this next it defaults to Net::SSL which may crash
require IO::Socket::SSL or die __PACKAGE__ . " requires IO::Socket::SSL";
require Net::SSLeay;
require LWP::UserAgent;
require HTTP::Request;
require Date::Calc or die __PACKAGE__ . " requires Date::Calc";
use Date::Calc qw(Add_Delta_YMD Today Today_and_Now);
use POSIX 'strftime';
};
$Vend::Payment::Have_Net_SSLeay = 1 unless $@;
if ($@) {
$msg = __PACKAGE__ . ' requires SOAP::Lite, IO::Socket::SSL and Date::Calc ' . $@;
::logGlobal ($msg);
die $msg;
}
::logGlobal("%s v1.1.6e 20151002 payment module loaded",__PACKAGE__)
unless $Vend::Quiet or ! $Global::VendRoot;
}
package Vend::Payment;
#use SOAP::Lite +trace; # ### debugging only ###
use strict;
my (%result, $header, $service, $version, $xmlns, $currency);
sub paypalexpress {
my ($token, $request, $method, $response, $in, $opt, $actual, $basket, $itemCode, $tax, $invoiceID);
my ($item, $itm, $basket, $setrpbillagreement, $rpprofile, $db, $dbh, $sth, $noteText);
foreach my $x (@_) {
$in = {
pprequest => $x->{'pprequest'},
}
}
#::logDebug("PP".__LINE__.": sandbox=$::Values->{ppsandbox} ". charge_param('sandbox'). "req=".charge_param('pprequest'));
my $pprequest = charge_param('pprequest') || $::Values->{'pprequest'} || $in->{'pprequest'} || 'setrequest'; # 'setrequest' must be the default for standard Paypal.
my $sandbox = charge_param('sandbox') || $::Values->{'sandbox'} || $::Values->{'ppsandbox'} || ''; # 1 or true to use for testing
$sandbox = '' unless $sandbox =~ /sandbox|1/;
$sandbox = "sandbox." if $sandbox =~ /sandbox|1/;
$::Values->{'ppsandbox'} = $::Values->{'sandbox'} = '';
$::Scratch->{'mstatus'} = '';
#::logDebug("PP".__LINE__.": sandbox=$sandbox passwd=".charge_param('password')." sig=".charge_param('signature'));
$currency = $::Values->{'iso_currency_code'} || $::Values->{'currency_code'} || $::Scratch->{'iso_currency_code'} ||
$Vend::Cfg->{'Locale'}{'iso_currency_code'} || charge_param('currency') || $::Variable->{MV_PAYMENT_CURRENCY} || 'USD';
$::Scratch->{'iso_currency_code'} ||= $currency;
# Credentials, prefixed with lower-cased account name if using 'getbalance' for more than one account
my $account = lc($pprequest) if $pprequest =~ /getbalance_/ || '';
$account =~ s/getbalance_//;
$account .= '_' if length $account;
$sandbox = "sandbox." if $account =~ /sandbox/;
my ($username, $password, $signature);
if (length $sandbox && charge_param('sandbox_id')) {
$username = charge_param('sandbox_id');
$password = charge_param('sandbox_password');
$signature = charge_param('sandbox_signature');
}
else {
$username = charge_param($account . 'id');
$password = charge_param($account . 'password');
$signature = charge_param($account . 'signature');
}
unless ($username && $password && $signature) {
return (
MStatus => 'failure-hard',
MErrMsg => errmsg('Bad credentials'),
);
}
my $ppcheckreturn = $::Values->{'ppcheckreturn'} || 'ord/checkout';
my $checkouturl = $::Tag->area({ href => "$ppcheckreturn" });
#::logDebug("PP".__LINE__.": req=$pprequest; sandbox=$sandbox;");
#::logDebug("PP".__LINE__.": pf=" . $Vend::Cfg->{'PriceField'} . " $::Scratch->{'PriceField'}; amt=" . Vend::Interpolate::total_cost() . "-" . charge_param('amount') ."-". $::Values->{'amount'});
$Vend::Cfg->{'PriceField'} = delete $::Scratch->{'PriceField'} if defined $::Scratch->{'PriceField'};
#::logDebug("PP".__LINE__.": pf=" . $Vend::Cfg->{'PriceField'} . " $::Scratch->{'PriceField'}; amt=" . Vend::Interpolate::total_cost() . "-" . charge_param('amount') ."-". $::Values->{'amount'});
# my $amount = charge_param('amount') || Vend::Interpolate::total_cost() || $::Values->{amount}; # required
my $amount = charge_param('amount') || Vend::Interpolate::total_cost() || $::Values->{'amount'}; # required
$amount =~ s/^\D*//g;
$amount =~ s/\s*//g;
$amount =~ s/,//g;
# for a SET request
my $host = charge_param('host') || 'api-3t.paypal.com'; # testing 3-token system is 'api-3t.sandbox.paypal.com'.
$host = 'api-3t.sandbox.paypal.com' if length $sandbox;
my $ipnhost = 'www.paypal.com';
$ipnhost = 'www.sandbox.paypal.com' if length $sandbox;
my $setordernumber = charge_param('setordernumber') || '1'; # unset to revert to using a temp order number until order settled
$invoiceID = $::Values->{'inv_no'} || $::Values->{'mv_transaction_id'} || $::Values->{'order_number'} || '' unless $setordernumber; # optional
my $ordercounter = charge_param('order_counter') || 'etc/order.number';
my $returnURL = charge_param('returnurl') or die "No return URL found\n"; # required
my $cancelURL = charge_param('cancelurl') or die "No cancel URL found\n"; # required
my $notifyURL = charge_param('notifyurl') || ''; # for IPN
my $maxAmount = $::Values->{'maxamount'} || $amount * '2'; # optional
$maxAmount = sprintf '%.2f', $maxAmount;
my $orderDescription = '';
my $address = '';
my $reqConfirmShipping = $::Values->{'reqconfirmshipping'} || charge_param('reqconfirmshipping') || ''; # you require that the customer's address must be "confirmed"
my $returnFMFdetails = $::Values->{'returnfmfdetails'} || charge_param('returnfmfdetails') || '0'; # set '1' to return FraudManagementFilter details
my $noShipping = $::Values->{'noshipping'} || charge_param('noshipping') || ''; # no shipping displayed on Paypal pages
my $addressOverride = $::Values->{'addressoverride'} || charge_param('addressoverride') || ''; # if '1', Paypal displays address given in SET request, not the one on Paypal's file
# new style checkout 'co-branding' options
my $localeCode = $::Values->{'localecode'} || $::Session->{'mv_locale'} || charge_param('localecode') || 'US';
my $pageStyle = $::Values->{'pagestyle'} || charge_param('pagestyle') || ''; # set in Paypal account
my $headerImg = $::Values->{'headerimg'} || charge_param('headerimg') || ''; # max 750x90, classic checkout, left-aligned, from your secure site
my $logoImg = $::Values->{'logoimg'} || charge_param('logoimg') || ''; # max 190x60, 'new style checkout', centred in 'cart area', from your secure site
my $cartBorderColor = $::Values->{'cartbordercolor'} || charge_param('cartbordercolor'); # hex code, without '#'
my $headerBorderColor = $::Values->{'headerbordercolor'} || charge_param('headerbordercolor') || '';
my $headerBackColor = $::Values->{'headerbackcolor'} || charge_param('headerbackcolor') || '';
my $payflowColor = $::Values->{'payflowcolor'} || charge_param('payflowcolor') || '';
my $paymentAction = $::Values->{'paymentaction'} || charge_param('paymentaction') || 'Sale'; # others: 'Order', 'Authorization'
my $buyerEmail = $::Values->{'buyeremail'} || '';
my $custom = $::Scratch->{'mv_currency'} || $::Scratch->{'mv_locale'};
$custom ||= 'en_' . lc(substr($currency,0,1));
# these next taken from IC after customer has logged in, and used in '$addressOverride'
my $usebill = $::Values->{'use_billing_override'} || charge_param('use_billing_override');
my $name = $usebill ? "$::Values->{'b_fname'} $::Values->{'b_lname'}" || '' : "$::Values->{'fname'} $::Values->{'lname'}" || '';
my $address1 = $usebill ? $::Values->{'b_address1'} : $::Values->{'address1'};
my $address2 = $usebill ? $::Values->{'b_address2'} : $::Values->{'address2'};
my $city = $usebill ? $::Values->{'b_city'} : $::Values->{'city'};
my $state = $usebill ? $::Values->{'b_state'} : $::Values->{'state'};
my $zip = $usebill ? $::Values->{'b_zip'} : $::Values->{'zip'};
my $country = $usebill ? $::Values->{'b_country'} : $::Values->{'country'};
$country = 'GB' if ($country eq 'UK'); # plonkers reject UK
my $phone = $::Values->{'phone_day'} || $::Values->{'phone_night'};
#::logDebug("PP".__LINE__.": usebill=$usebill, name=$name, address1=$address1, city=$city");
# for a Do request, and Set with item details
my $dsmode = $::Variable->{'DSMODE'}; # for any custom shipping tags
my $itemTotal = $::Values->{'itemtotal'} || Vend::Interpolate::subtotal() || $::Session->{'ppitemTotal'} || '';
$itemTotal = sprintf '%.2f', $itemTotal;
my $shipTotal = $::Values->{'shiptotal'} || Vend::Interpolate::tag_shipping() || $::Session->{'ppshipTotal'} || '' unless $::Variable->{'DSMODE'};
$shipTotal = $::Tag->$dsmode() if $::Variable->{'DSMODE'};
$shipTotal = sprintf '%.2f', $shipTotal;
my $taxTotal = $::Values->{'taxtotal'} || Vend::Interpolate::salestax() || $::Session->{'pptaxTotal'} || '';
$taxTotal = sprintf '%.2f', $taxTotal;
my $handlingTotal = $::Values->{'handlingtotal'} || Vend::Ship::tag_handling() || $::Session->{'pphandlingTotal'} || '';
$handlingTotal = sprintf '%.2f', $handlingTotal;
my $buttonSource = $::Values->{'buttonsource'} || charge_param('buttonsource') || ''; # for third party source
my $paymentDetailsItem = $::Values->{'paymentdetailsitem'} || charge_param('paymentdetailsitem') || ''; # set '1' to include item details
my $transactionID = $::Values->{'transactionid'} || ''; # returned upon success, but not for recurring billing, only the correlationid
my $correlationID = $::Values->{'correlationid'} || ''; # use for any dispute with Paypal
my $refundtransactionID = $::Values->{'refundtransactionid'} || ''; # log for reference
my $quantity = $::Tag->nitems() || '1';
my $itemised_basket_off = delete $::Values->{'itemised_basket_off'} || charge_param('itemised_basket_off');
# if $paymentDetailsItem is set, then need to pass an item amount to keep Paypal happy
my $itemAmount = $amount / $quantity;
$itemAmount = sprintf '%.2f', $itemAmount;
$amount = sprintf '%.2f', $amount;
my $receiverType = $::Values->{'receiverType'} || charge_param('receivertype') || 'EmailAddress'; # used in MassPay
$version = '122.0'; # '97.0', '74.0';
my $order_id = gen_order_id($opt);
#::logDebug("PP".__LINE__.": oid=$order_id; amount=$amount, itemamount=$itemAmount; tax=$taxTotal, ship=$shipTotal, hdl=$handlingTotal");
# new fields for v 1.1.0 and API v 74
my $softDescriptor = $::Values->{'soft_descriptor'} || charge_param('soft_descriptor'); # appears on customer's card statement
my $sellerDetails = $::Values->{'seller_details'} || charge_param('seller_details'); # will appear in eBay emails
my $allowNote = $::Values->{'allow_note'} || charge_param('allow_note'); # allow customer to enter note at Paypal
my $brandName = $::Values->{'brand_name'} || charge_param('brand_name'); # max 127 chars, over-rides the business name at Paypal
my $servicePhone = $::Values->{'service_phone'} || charge_param('service_phone'); # displayed to customer
my $giftMessageEnable = $::Values->{'gift_message_enable'} || charge_param('gift_message_enable'); # 0 or 1
my $giftReceiptEnable = $::Values->{'gift_receipt_enable'} || charge_param('gift_receipt_enable'); # 0 or 1
my $giftWrapEnable = $::Values->{'gift_wrap_enable'} || charge_param('gift_wrap_enable'); # 0 or 1
my $giftWrapName = $::Values->{'gift_wrap_name'};
my $giftWrapAmount = $::Values->{'gift_wrap_amount'};
my $buyerEmailOptin = $::Values->{'buyer_email_optin'} || charge_param('buyer_email_optin'); # 0 or 1
my $surveyEnable = $::Values->{'survey_enable'} || charge_param('survey_enable'); # 0 or 1
my $surveyQuestion = $::Values->{'survey_question'} || charge_param('survey_question');
my $surveyChoice = $::Values->{'survey_choice'} || charge_param('survey_choice');
my $allowPushFunding = $::Values->{'allow_push_funding'} || charge_param('allow_push_funding'); # 0 or `
my $allowedPayMethod = $::Values->{'allowed_payment_method'} || charge_param('allowed_payment_method'); #
my $landingPage = $::Values->{'landing_page'} || charge_param('landing_page');
my $solutionType = $::Values->{'solution_type'} || charge_param('solution_type');
my $totalType = $::Values->{'total_type'} || charge_param('total_type') || 'EstimatedTotal'; # or 'Total' if is known accurately
my $errordisplayoff = charge_param('errordisplayoff') || '';
# for Giropay
my $giropaySuccessURL = $::Values->{'giropay_success_url'} || charge_param('giropay_success_url');
my $giropayCancelURL = $::Values->{'giropay_cancel_url'} || charge_param('giropay_cancel_url');
my $BanktxnPendingURL = $::Values->{'bnktxn_pending_url'} || charge_param('bnktxn_pending_url');
my $giropayaccepted = $::Values->{'giropay_accepted'} || charge_param('giropay_accepted') || '1';
my $giropayurl = "https://www." . $sandbox . "paypal.com/cgi-bin/webscr?cmd=_complete-express-checkout";
#-----------------------------------------------------------------------------------------------
# for operations through the payment terminal, eg 'masspay', 'refund' etc
my $refundType = $::Values->{'refundtype'} || 'Full'; # either 'Full' or 'Partial'
my $memo = $::Values->{'memo'} || '';
my $orderid = $::Values->{'mv_order_id'} || '';
my $emailSubject = $::Values->{'emailsubject'} || ''; # subject line of email
my $receiverEmail = $::Values->{'receiveremail'} || ''; # address of refund recipient
$xmlns = 'urn:ebay:api:PayPalAPI';
$service = SOAP::Lite->proxy("https://$host/2.0/")->uri($xmlns);
# Ignore the paypal typecasting returned
*SOAP::Deserializer::typecast = sub {shift; return shift};
#-------------------------------------------------------------------------------------------------
### Create the Security Header
#
$header = SOAP::Header->name("RequesterCredentials" =>
\SOAP::Header->value(
SOAP::Data->name("Credentials" =>
\SOAP::Data->value(
SOAP::Data->name("Username" => $username )->type("xs:string"),
SOAP::Data->name("Password" => $password )->type("xs:string"),
SOAP::Data->name("Signature" => $signature)->type("xs:string")
)
)
->attr({xmlns=>"urn:ebay:apis:eBLBaseComponents"})
)
)
->attr({xmlns=>$xmlns})->mustUnderstand("1");
#--------------------------------------------------------------------------------------------------
### Create a SET request and method, and read response
#
my ($item,$itm,@pditems,@pdi,$pdi,$pdiamount,$itemtotal,$pdisubtotal,$cntr,$pditotalamount,$rpamount,$itemname,$itemdesc);
if ($pprequest eq 'setrequest') {
if (charge_param('setordernumber') == '1') {
$invoiceID = $::Values->{'inv_no'} || Vend::Interpolate::tag_counter( $ordercounter );
$::Values->{'mv_order_number'} = $::Session->{'mv_order_number'} = $invoiceID;
$::Scratch->{'ordernumberalreadyset'} = '1';
}
# start with required elements, add optional elements if they exist
my @setreq = (
SOAP::Data->name("ReturnURL" => $returnURL)->type(""),
SOAP::Data->name("CancelURL" => $cancelURL)->type(""),
);
push @setreq, SOAP::Data->name("ReqConfirmShipping" => $reqConfirmShipping)->type("xs:string") if $reqConfirmShipping;
push @setreq, SOAP::Data->name("NoShipping" => $noShipping)->type("xs:string") if $noShipping;
push @setreq, SOAP::Data->name("AddressOverride" => $addressOverride)->type("xs:string") if $addressOverride;
push @setreq, SOAP::Data->name("PageStyle" => $pageStyle)->type("xs:string") if $pageStyle;
push @setreq, SOAP::Data->name("BuyerEmail" => $buyerEmail)->type("xs:string") if $buyerEmail;
push @setreq, SOAP::Data->name("cpp-header-image" => $headerImg)->type("xs:string") if $headerImg;
push @setreq, SOAP::Data->name("cpp-logo-image" => $logoImg)->type("xs:string") if $logoImg;
push @setreq, SOAP::Data->name("cpp-header-border-color" => $headerBorderColor)->type("xs:string") if $headerBorderColor;
push @setreq, SOAP::Data->name("cpp-header-back-color" => $headerBackColor)->type("xs:string") if $headerBackColor;
push @setreq, SOAP::Data->name("cpp-payflow-color" => $payflowColor)->type("xs:string") if $payflowColor;
push @setreq, SOAP::Data->name("cpp-cart-border-color" => $cartBorderColor)->type("xs:string") if $cartBorderColor;
push @setreq, SOAP::Data->name("LandingPage" => $landingPage)->type("") if $landingPage;
push @setreq, SOAP::Data->name("SolutionType" => $solutionType)->type("") if $solutionType;
push @setreq, SOAP::Data->name("MaxAmount" => $maxAmount)->attr({"currencyID" => $currency})->type("ebl:BasicAmountType") if $maxAmount;
push @setreq, SOAP::Data->name("CustomerServiceNumber" => $servicePhone)->type("xs:string") if $servicePhone;
push @setreq, SOAP::Data->name("GiftMessageEnable" => $giftMessageEnable)->type("xs:string") if $giftMessageEnable; # 0 or 1
push @setreq, SOAP::Data->name("GiftReceiptEnable" => $giftReceiptEnable)->type("xs:string") if $giftReceiptEnable; # 0 or 1
push @setreq, SOAP::Data->name("GiftWrapEnable" => $giftWrapEnable)->type("xs:string") if $giftWrapEnable; # 0 or 1
push @setreq, SOAP::Data->name("GiftWrapName" => $giftWrapName)->type("xs:string") if $giftWrapName; # 25 chars
push @setreq, SOAP::Data->name("GiftWrapAmount" => $giftWrapAmount)->attr({"currencyID" => $currency})->type("ebl:BasicAmountType") if $giftWrapAmount;
push @setreq, SOAP::Data->name("BuyerEmailOptinEnable" => $buyerEmailOptin)->type("xs:string") if $buyerEmailOptin; # 0 or 1
push @setreq, SOAP::Data->name("SurveyEnable" => $surveyEnable)->type("xs:string") if $surveyEnable; # 0 or 1
push @setreq, SOAP::Data->name("SurveyQuestion" => $surveyQuestion)->type("xs:string") if $surveyQuestion; # max 50 chars
push @setreq, SOAP::Data->name("SurveyChoice" => $surveyChoice)->type("xs:string") if $surveyChoice; # max 15 chars
push @setreq, SOAP::Data->name("LocaleCode" => $localeCode)->type("xs:string") if $localeCode;
push @setreq, SOAP::Data->name("AllowNote" => $allowNote)->type("xs:string") if defined $allowNote; # 0 or 1
# push @setreq, SOAP::Data->name("TotalType" => $totalType)->type("") if $totalType; # ### crashes ... ###
::logDebug("PP".__LINE__.": itemTotal=$itemTotal; taxTotal=$taxTotal");
# now loop through the basket and put every item into iterated PaymentDetailsItem blocks, and
# recurring payments items into iterated BillingAgreeement blocks. Explicit arrays not needed.
foreach $item (@{$::Carts->{'main'}}) {
my $rpamount_field = 'rpamount_' . lc($currency) || 'rpamount';
$itm = {
sku => $item->{'code'},
quantity => $item->{'quantity'},
amount => Vend::Data::item_price($item),
title => Vend::Data::item_field($item, 'title'),
description => Vend::Data::item_field($item, 'description'),
comment => Vend::Data::item_field($item, 'comment'),
rpamount => Vend::Data::item_field($item, 'rpamount'),
rpamount_field => Vend::Data::item_field($item, $rpamount_field),
};
$itm->{'title'} = _pplocfilter( $itm->{'title'} );
$itm->{'comment'} = _pplocfilter( $itm->{'comment'} );
$itm->{'description'} = _pplocfilter( $itm->{'description'} );
$itemname = $itm->{'title'} || $itm->{'description'};
$itemname = _ppxmlfilter( $itemname );
$itemname = substr($itemname,0,126);
$itemdesc = $itm->{'description'} if $itm->{'title'};
$itemdesc = $itm->{'comment'} unless $itm->{'title'};
$itemdesc = _ppxmlfilter( $itemdesc );
$itemdesc = substr($itemdesc,0,126);
$pdiamount = $itm->{'amount'};
$pdiamount = sprintf '%.02f', $pdiamount;
$pdisubtotal = $pdiamount * $itm->{'quantity'};
#::logDebug("PP".__LINE__.": pdi: sku=$itm->{sku}, desc=$itm->{description}, qty=$itm->{quantity}; amt=$itm->{amount}; rpamt=$itm->{rpamount}; fld=$rpamount_field; cur=$currency; payact=$paymentAction");
$rpamount = $itm->{'rpamount_field'} || $itm->{'rpamount'};
if ($rpamount) {
#::logDebug("PP".__LINE__.": cntr=$cntr; rpamount=$rpamount");
$setrpbillagreement = (
SOAP::Data->name("BillingAgreementDetails" =>
\SOAP::Data->value(
SOAP::Data->name("BillingType" => 'RecurringPayments')->type(""),
SOAP::Data->name("BillingAgreementDescription" => $itm->{'description'})->type(""),
)
)->type("ns:BillingAgreementDetailsType"),
);
if ($cntr > '9') {
$::Session->{'errors'}{'Paypal'} = "Paypal will not accept more than ten subscriptions in one order - please remove some and purchase them in
a second order";
return();
};
$cntr++;
$::Scratch->{'allowzeroamount'} = '1'; # use in log_transaction
push @setreq, $setrpbillagreement;
} # if RecPay item in basket loop
#
# Finished with BillingAgreeements, now for PaymentDetailsItem in basket loop
# Separate block for each item: also include those which are RecPay items
#
$pditotalamount += $pdisubtotal; # to overcome rounding errors in currency conversions
::logDebug("PP".__LINE__.":amt=$amount; pditotalamount=$pditotalamount; pdiamount=$pdiamount");
@pdi = SOAP::Data->name("Name" => $itemname)->type("");
push @pdi, SOAP::Data->name("Amount" => $pdiamount)->attr({"currencyID" => $currency})->type("");
push @pdi, SOAP::Data->name("Number" => $itm->{'sku'})->type("");
push @pdi, SOAP::Data->name("Description" => $itemdesc)->type("");
push @pdi, SOAP::Data->name("Quantity" => $itm->{'quantity'})->type("") if $itm->{'quantity'};
push @pdi, SOAP::Data->name("ItemWeight" => $itm->{'weight'})->type("") if $itm->{'weight'};
push @pdi, SOAP::Data->name("ItemWidth" => $itm->{'width'})->type("") if $itm->{'width'};
push @pdi, SOAP::Data->name("ItemLength" => $itm->{'length'})->type("") if $itm->{'length'};
push @pdi, SOAP::Data->name("ItemHeight" => $itm->{'height'})->type("") if $itm->{'height'};
push @pdi, SOAP::Data->name("ItemURL" => $itm->{'murl'})->type("") if $itm->{'url'};
push @pdi, SOAP::Data->name("ItemCategory" => $itm->{'category'})->type("") if $itm->{'category'}; # required as 'Digital' for digital goods, else optional as 'Physical'
$pdi = (
SOAP::Data->name("PaymentDetailsItem" =>
\SOAP::Data->value(
@pdi,
)
)->type("ebl:PaymentDetailsItemType"),
);
push @pditems, $pdi unless length $rpamount;
$cntr++;
} # foreach item in basket
#
# Finished basket loop for each item, now for PaymentDetails
#
::logDebug("PP".__LINE__.": vship=$::Values->{'shiptotal'}; tag=" .Vend::Interpolate::tag_shipping());
# calculate here so as to avoid rounding errors and rejection at Paypal
my $itemtotal = $pditotalamount;
$itemtotal = sprintf '%.2f', $itemtotal;
$::Session->{'ppitemTotal'} = $itemtotal;
my $shiptotal = $::Values->{'shiptotal'} || Vend::Interpolate::tag_shipping() || '' unless $::Variable->{'DSMODE'};
$shiptotal = $::Tag->$dsmode() if $::Variable->{'DSMODE'};
$shiptotal = sprintf '%.2f', $shiptotal;
$::Session->{'ppshipTotal'} = $shiptotal;
my $handlingtotal = $::Values->{'handlingtotal'} || Vend::Ship::tag_handling() || '';
$handlingtotal = sprintf '%.2f', $handlingtotal;
$::Session->{'pphandlingTotal'} = $handlingtotal;
my $taxtotal = $::Values->{'taxtotal'} || Vend::Interpolate::salestax() || '';
$taxtotal = sprintf '%.2f', $taxtotal;
$::Session->{'pptaxTotal'} = $taxtotal;
::logDebug("PP".__LINE__.": tax=$::Values->{taxtotal}; ". Vend::Interpolate::salestax());
$amount = $itemtotal + $shiptotal + $taxtotal + $handlingtotal;
my $shiptoaddress = (
SOAP::Data->name("ShipToAddress" =>
\SOAP::Data->value(
SOAP::Data->name("Name" => $name)->type(""),
SOAP::Data->name("Street1" => $address1)->type(""),
SOAP::Data->name("Street2" => $address2)->type(""),
SOAP::Data->name("CityName" => $city)->type(""),
SOAP::Data->name("StateOrProvince" => $state)->type(""),
SOAP::Data->name("PostalCode" => $zip)->type(""),
SOAP::Data->name("Country" => $country)->type(""),
SOAP::Data->name("Phone" => $phone)->type(""),
)
)
) if length $address1;
my @pd = SOAP::Data->name("OrderTotal" => $amount)->attr({"currencyID" => $currency})->type('');
push @pd, SOAP::Data->name("ItemTotal" => $itemtotal)->attr({"currencyID" => $currency})->type("") if $itemtotal;
push @pd, SOAP::Data->name("TaxTotal" => $taxtotal)->attr({"currencyID" => $currency})->type("") if $taxtotal;
push @pd, SOAP::Data->name("ShippingTotal" => $shiptotal)->attr({"currencyID" => $currency})->type("") if $shiptotal;
push @pd, SOAP::Data->name("HandlingTotal" => $handlingtotal)->attr({"currencyID" => $currency})->type("") if $handlingtotal;
push @pd, SOAP::Data->name("InvoiceID" => $invoiceID)->type("") if length $invoiceID;
push @pd, SOAP::Data->name("NotifyURL" => $notifyURL)->type("") if $notifyURL;
push @pd, SOAP::Data->name("Custom" => $custom)->type("") if $custom;
# push @pd, SOAP::Data->name("TransactionID" => $order_id)->type(""); # ###
push @pd, $shiptoaddress if length $addressOverride;
my $discount = $Vend::Session->{discount} || '';
::logDebug("PP:".__LINE__." discount=$discount " . ::uneval($discount));
#
# discounts are not shown at paypal
#
push @pd, @pditems unless $itemised_basket_off == '1' or length $discount;
#::logDebug("PP".__LINE__.": ppdiscnote=$::Values->{pp_discount_note}; note=$::Values->{pp_note_to_buyer}");
my $note_to_buyer = $::Values->{'pp_discount_note'};
push @pd, SOAP::Data->name("NoteToBuyer" => $note_to_buyer)->type("") if length $note_to_buyer;
$::Values->{'pp_discount_note'} = '';
push @pd, SOAP::Data->name("OrderDescription" => $note_to_buyer)->type("") if $custom;
#
# neither NoteToBuyer nor OrderDescription show at the new-style dumbed-down paypal splash page ...
#
my $paymentDetails = (
SOAP::Data->name("PaymentDetails" =>
\SOAP::Data->value(
@pd,
)
)->type(""),
);
push @setreq, $paymentDetails;
push @setreq, SOAP::Data->name("BrandName" => $brandName)->type("") if $brandName;
my ($bt,$rpdesc,$rpAgreementAmount,$rpStartDate);
# rpStartDate > dateTime
my @maxrpamt;
my @setrpbill;
my $cntr = '0';
#::logDebug("PP".__LINE__.": setreq=".::uneval(@setreq)); # ### NOTE
# Destroy the token here at the start of a new request, rather than after a 'dorequest' has completed,
# as Paypal use it to reject duplicate payments resulting from clicking the final 'pay' button more
# than once.
undef $result{'Token'};
$request = SOAP::Data->name("SetExpressCheckoutRequest" =>
\SOAP::Data->value(
SOAP::Data->name("Version" => $version)->attr({ xmlns => "urn:ebay:apis:eBLBaseComponents" }),
SOAP::Data->name("SetExpressCheckoutRequestDetails" =>
\SOAP::Data->value(@setreq
)
) ->attr({ xmlns => "urn:ebay:apis:eBLBaseComponents" }),
)
);
$method = SOAP::Data->name('SetExpressCheckoutReq')->attr({xmlns=>$xmlns});
$response = $service->call($header, $method => $request);
my $result_hashref = $response->valueof('//SetExpressCheckoutResponse');
unless ($result_hashref) {
$Tag->error({ name => 'paypal_failure', set => errmsg('Unable to parse the PayPal response') });
return $Tag->deliver({ location => $checkouturl });
}
%result = %$result_hashref;
$::Scratch->{'token'} = $result{'Token'};
#::logDebug("PP".__LINE__.": result= ".::uneval(%result)); # ### NOTE
if (!$result{'Token'}) {
if ($result{'Ack'} eq 'Failure') {
$::Session->{'errors'}{'PaypalExpress'} = $result{'Errors'}{'LongMessage'} if ($result{'Errors'} !~ /ARRAY/);
for my $i (0 .. 3) {
$::Session->{'errors'}{'PaypalExpress'} .= " $result{'Errors'}[$i]{'LongMessage'}" if ($result{'Errors'} =~ /ARRAY/);
}
}
else {
my $accepted = uc($::Variable->{CREDIT_CARDS_ACCEPTED});
$::Session->{'errors'}{'PaypalExpress'} = errmsg("Paypal is currently unavailable - please use our secure payment system instead. We accept $accepted cards");
}
return $Tag->deliver({ location => $checkouturl })
}
#::logDebug("PP".__LINE__.": sandbox=$sandbox; host=$host");
# Now go off to Paypal
my $redirecturl = "https://www."."$sandbox"."paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=$result{Token}";
return $Tag->deliver({ location => $redirecturl });
}
#--------------------------------------------------------------------------------------------------
### Create a GET request and method, and read response