This repository has been archived by the owner on Mar 25, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Gateway.cs
1177 lines (1045 loc) · 49.9 KB
/
Gateway.cs
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
// <copyright>
// Copyright 2013 by the Spark Development Network
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
//
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Composition;
using System.Data;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.ServiceModel;
using System.Text.RegularExpressions;
using cc.newspring.CyberSource.ITransactionProcessor;
using Rock;
using Rock.Attribute;
using Rock.Financial;
using Rock.Model;
using Rock.VersionInfo;
using Rock.Web.Cache;
namespace cc.newspring.CyberSource
{
/// <summary>
/// CyberSource Payment Gateway
/// </summary>
[Description( "CyberSource Payment Gateway" )]
[Export( typeof( GatewayComponent ) )]
[ExportMetadata( "ComponentName", "CyberSource" )]
[TextField( "Merchant ID", "The CyberSource merchant ID (case-sensitive)", true, "", "", 0, "MerchantID" )]
[MemoField( "Transaction Key", "The CyberSource transaction key", true, "", "", 0, "TransactionKey", 1 )]
[TextField( "Report User", "The CyberSource reporting user (case-sensitive)", true, "", "", 2, "ReportUser" )]
[TextField( "Report Password", "The CyberSource reporting password (case-sensitive)", true, "", "", 3, "ReportPassword" )]
[CustomRadioListField( "Mode", "Mode to use for transactions", "Live,Test", true, "Live", "", 4 )]
[TextField( "Live Gateway URL", "The CyberSource endpoint url to use for live transactions", true, "https://ics2wsa.ic3.com/commerce/1.x/transactionProcessor/", "", 5 )]
[TextField( "Test Gateway URL", "The CyberSource endpoint url to use for test transactions", true, "https://ics2wstesta.ic3.com/commerce/1.x/transactionProcessor/", "", 6 )]
[BooleanField( "Prompt for Name On Card", "Should users be prompted to enter name on the card", false, "", 7, "PromptForName" )]
[BooleanField( "Prompt for Bank Account Name", "Should users be prompted to enter a name for the bank account (in addition to routing and account numbers).", true, "", 8, "PromptForBankAccountName" )]
[BooleanField( "Prompt for Billing Address", "Should users be prompted to enter billing address", true, "", 9, "PromptForAddress" )]
public class Gateway : GatewayComponent
{
private static string GATEWAY_RESPONSE_SUCCESS = "100";
// Endpoint URL attribute provided for host changes ONLY
// Version updates require in-app service regeneration
private static string GATEWAY_VERSION = "1.127";
#region Gateway Component Implementation
/// <summary>
/// Gets a value indicating whether gateway provider needs first and last name on credit card as two distinct fields.
/// </summary>
/// <value>
/// <c>true</c> if [split name on card]; otherwise, <c>false</c>.
/// </value>
public override bool SplitNameOnCard
{
get
{
return true;
}
}
/// <summary>
/// Gets a value indicating whether the gateway requires the name on card for CC processing
/// </summary>
/// <value>
/// <c>true</c> if [name on card required]; otherwise, <c>false</c>.
/// </value>
public override bool PromptForNameOnCard( FinancialGateway financialGateway )
{
return GetAttributeValue( financialGateway, "PromptForName" ).AsBoolean();
}
/// <summary>
/// Prompts the name of for bank account.
/// </summary>
/// <param name="financialGateway">The financial gateway.</param>
/// <returns></returns>
public override bool PromptForBankAccountName( FinancialGateway financialGateway )
{
return GetAttributeValue( financialGateway, "PromptForBankAccountName" ).AsBoolean();
}
/// <summary>
/// Gets a value indicating whether [address required].
/// </summary>
/// <value>
/// <c>true</c> if [address required]; otherwise, <c>false</c>.
/// </value>
public override bool PromptForBillingAddress( FinancialGateway financialGateway )
{
return GetAttributeValue( financialGateway, "PromptForAddress" ).AsBoolean();
}
/// <summary>
/// Determines if this gateway supports saved accounts of the type indicated by currencyType
/// </summary>
/// <param name="currencyType">The currency type</param>
/// <returns></returns>
public override bool SupportsSavedAccount( DefinedValueCache currencyType )
{
var ach = Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_ACH.AsGuid();
var creditCard = Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_CREDIT_CARD.AsGuid();
var currencyTypeGuid = currencyType.Guid;
return currencyTypeGuid.Equals( ach ) || currencyTypeGuid.Equals( creditCard );
}
/// <summary>
/// Gets the supported payment schedules.
/// </summary>
/// <value>
/// The supported payment schedules.
/// </value>
public override List<DefinedValueCache> SupportedPaymentSchedules
{
get
{
var values = new List<DefinedValueCache>();
values.Add( DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.TRANSACTION_FREQUENCY_ONE_TIME ) );
values.Add( DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.TRANSACTION_FREQUENCY_WEEKLY ) );
values.Add( DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.TRANSACTION_FREQUENCY_BIWEEKLY ) );
values.Add( DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.TRANSACTION_FREQUENCY_TWICEMONTHLY ) );
values.Add( DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.TRANSACTION_FREQUENCY_MONTHLY ) );
values.Add( DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.TRANSACTION_FREQUENCY_YEARLY ) );
return values;
}
}
/// <summary>
/// Credits (Refunds) the specified transaction.
/// </summary>
/// <param name="origTransaction">The original transaction.</param>
/// <param name="errorMessage">The error message.</param>
/// <returns></returns>
public override FinancialTransaction Credit( FinancialTransaction origTransaction, decimal amount, string comment, out string errorMessage )
{
errorMessage = string.Empty;
if ( origTransaction == null )
{
errorMessage = "Original transaction cannot be null";
return null;
}
if ( string.IsNullOrWhiteSpace( origTransaction.TransactionCode ) )
{
errorMessage = "The transaction must have a TransactionCode to process a refund/credit";
return null;
}
if ( origTransaction.FinancialGateway == null )
{
errorMessage = "The transaction must have a FinancialGateway to process a refund/credit";
return null;
}
var financialGateway = origTransaction.FinancialGateway;
var request = GetMerchantInfo( financialGateway );
request.ccCreditService = new CCCreditService
{
run = "true",
captureRequestID = origTransaction.TransactionCode
};
request.comments = comment;
request.purchaseTotals = GetTotals();
request.purchaseTotals.grandTotalAmount = amount.ToString();
// Credit the transaction
ReplyMessage reply = SubmitTransaction( financialGateway, request, out errorMessage );
if ( reply != null && reply.reasonCode.Equals( GATEWAY_RESPONSE_SUCCESS ) )
{
var transactionGuid = new Guid( reply.merchantReferenceCode );
var transaction = new FinancialTransaction
{
Guid = transactionGuid,
TransactionCode = reply.requestID,
Summary = comment
};
return transaction;
}
else if ( string.IsNullOrEmpty( errorMessage ) )
{
errorMessage = string.Format( "Unable to credit this transaction.{0}", ProcessError( reply ) );
}
return null;
}
/// <summary>
/// Authorizes/tokenizes the specified payment info.
/// </summary>
/// <param name="paymentInfo">The payment info.</param>
/// <param name="errorMessage">The error message.</param>
/// <returns></returns>
public override FinancialTransaction Authorize( FinancialGateway financialGateway, PaymentInfo paymentInfo, out string errorMessage )
{
errorMessage = string.Empty;
RequestMessage request = GetPaymentInfo( financialGateway, paymentInfo );
if ( request == null )
{
errorMessage = "Payment type not implemented";
return null;
}
if ( request.recurringSubscriptionInfo == null )
{
request.recurringSubscriptionInfo = new RecurringSubscriptionInfo();
}
request.recurringSubscriptionInfo.frequency = "ON-DEMAND";
request.recurringSubscriptionInfo.amount = paymentInfo.Amount.ToString();
request.paySubscriptionCreateService = new PaySubscriptionCreateService();
request.paySubscriptionCreateService.run = "true";
request.purchaseTotals = GetTotals();
request.billTo = GetBillTo( paymentInfo );
request.item = GetItems( paymentInfo );
request.subscription = new Subscription();
if ( !paymentInfo.CurrencyTypeValue.Guid.Equals( new Guid( Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_CREDIT_CARD ) ) )
{
request.subscription.paymentMethod = "check";
}
if ( paymentInfo is ReferencePaymentInfo )
{
request.paySubscriptionCreateService.paymentRequestID = ( (ReferencePaymentInfo)paymentInfo ).TransactionCode;
}
// Authorize the transaction
ReplyMessage reply = SubmitTransaction( financialGateway, request, out errorMessage );
if ( reply != null && reply.reasonCode.Equals( GATEWAY_RESPONSE_SUCCESS ) )
{
var transactionGuid = new Guid( reply.merchantReferenceCode );
var transaction = new FinancialTransaction { Guid = transactionGuid };
transaction.TransactionCode = reply.requestID;
return transaction;
}
else if ( string.IsNullOrEmpty( errorMessage ) )
{
errorMessage = string.Format( "Unable to authorize this transaction.{0}", ProcessError( reply ) );
}
return null;
}
/// <summary>
/// Charges the specified payment info.
/// </summary>
/// <param name="paymentInfo">The payment info.</param>
/// <param name="errorMessage">The error message.</param>
/// <returns></returns>
public override FinancialTransaction Charge( FinancialGateway financialGateway, PaymentInfo paymentInfo, out string errorMessage )
{
errorMessage = string.Empty;
RequestMessage request = GetPaymentInfo( financialGateway, paymentInfo );
if ( request == null )
{
errorMessage = "Payment type not implemented";
return null;
}
request.purchaseTotals = GetTotals();
request.billTo = GetBillTo( paymentInfo );
request.item = GetItems( paymentInfo );
if ( !paymentInfo.CurrencyTypeValue.Guid.Equals( new Guid( Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_CREDIT_CARD ) ) )
{
request.ecDebitService = new ECDebitService();
request.ecDebitService.commerceIndicator = "internet";
request.ecDebitService.run = "true";
}
else
{
request.ccAuthService = new CCAuthService();
request.ccAuthService.commerceIndicator = "internet";
request.ccAuthService.run = "true";
request.ccCaptureService = new CCCaptureService();
request.ccCaptureService.run = "true";
}
// Charge the transaction
ReplyMessage reply = SubmitTransaction( financialGateway, request, out errorMessage );
if ( reply != null && reply.reasonCode.Equals( GATEWAY_RESPONSE_SUCCESS ) )
{
var transactionGuid = new Guid( reply.merchantReferenceCode );
var transaction = new FinancialTransaction { Guid = transactionGuid };
transaction.TransactionCode = reply.requestID;
return transaction;
}
else if ( string.IsNullOrEmpty( errorMessage ) )
{
errorMessage = string.Format( "Unable to process this order.{0}", ProcessError( reply ) );
}
return null;
}
/// <summary>
/// Adds the scheduled payment.
/// </summary>
/// <param name="schedule">The schedule.</param>
/// <param name="paymentInfo">The payment info.</param>
/// <param name="errorMessage">The error message.</param>
/// <returns></returns>
public override FinancialScheduledTransaction AddScheduledPayment( FinancialGateway financialGateway, PaymentSchedule schedule, PaymentInfo paymentInfo, out string errorMessage )
{
errorMessage = string.Empty;
RequestMessage request = GetPaymentInfo( financialGateway, paymentInfo );
if ( request == null )
{
errorMessage = "Payment type not implemented";
return null;
}
if ( request.recurringSubscriptionInfo == null )
{
request.recurringSubscriptionInfo = new RecurringSubscriptionInfo();
}
request.recurringSubscriptionInfo.startDate = GetStartDate( schedule );
request.recurringSubscriptionInfo.frequency = GetFrequency( schedule );
request.recurringSubscriptionInfo.amount = paymentInfo.Amount.ToString();
request.paySubscriptionCreateService = new PaySubscriptionCreateService();
request.paySubscriptionCreateService.run = "true";
request.purchaseTotals = GetTotals();
request.billTo = GetBillTo( paymentInfo );
request.item = GetItems( paymentInfo );
request.subscription = new Subscription();
if ( !paymentInfo.CurrencyTypeValue.Guid.Equals( new Guid( Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_CREDIT_CARD ) ) )
{
request.subscription.paymentMethod = "check";
}
if ( paymentInfo is ReferencePaymentInfo )
{
request.paySubscriptionCreateService.paymentRequestID = ( (ReferencePaymentInfo)paymentInfo ).TransactionCode;
}
// Schedule the payment
ReplyMessage reply = SubmitTransaction( financialGateway, request, out errorMessage );
if ( reply != null && reply.reasonCode.Equals( GATEWAY_RESPONSE_SUCCESS ) )
{
var transactionGuid = new Guid( reply.merchantReferenceCode );
var scheduledTransaction = new FinancialScheduledTransaction { Guid = transactionGuid };
scheduledTransaction.TransactionCode = reply.paySubscriptionCreateReply.subscriptionID;
scheduledTransaction.GatewayScheduleId = reply.paySubscriptionCreateReply.subscriptionID;
scheduledTransaction.FinancialGateway = financialGateway;
scheduledTransaction.FinancialGatewayId = financialGateway.Id;
GetScheduledPaymentStatus( scheduledTransaction, out errorMessage );
return scheduledTransaction;
}
else if ( string.IsNullOrEmpty( errorMessage ) )
{
errorMessage = string.Format( "Your order was not approved.{0}", ProcessError( reply ) );
}
return null;
}
/// <summary>
/// Reactivates the scheduled payment (CyberSource not supported).
/// </summary>
/// <param name="transaction">The transaction.</param>
/// <param name="errorMessage">The error message.</param>
/// <returns></returns>
public override bool ReactivateScheduledPayment( FinancialScheduledTransaction transaction, out string errorMessage )
{
errorMessage = string.Empty;
return false;
}
/// <summary>
/// Updates the scheduled payment.
/// </summary>
/// <param name="schedule">The schedule.</param>
/// <param name="paymentInfo">The payment info.</param>
/// <param name="errorMessage">The error message.</param>
/// <returns></returns>
public override bool UpdateScheduledPayment( FinancialScheduledTransaction transaction, PaymentInfo paymentInfo, out string errorMessage )
{
errorMessage = string.Empty;
var financialGateway = transaction.FinancialGateway;
RequestMessage request = GetPaymentInfo( financialGateway, paymentInfo );
if ( request == null )
{
errorMessage = "Payment type not implemented";
return false;
}
if ( request.recurringSubscriptionInfo == null )
{
request.recurringSubscriptionInfo = new RecurringSubscriptionInfo();
request.recurringSubscriptionInfo.subscriptionID = transaction.TransactionCode;
}
request.recurringSubscriptionInfo.amount = paymentInfo.Amount.ToString();
request.paySubscriptionUpdateService = new PaySubscriptionUpdateService();
request.paySubscriptionUpdateService.run = "true";
request.purchaseTotals = GetTotals();
request.billTo = GetBillTo( paymentInfo );
request.item = GetItems( paymentInfo );
request.subscription = new Subscription();
if ( !paymentInfo.CurrencyTypeValue.Guid.Equals( new Guid( Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_CREDIT_CARD ) ) )
{
request.subscription.paymentMethod = "check";
}
else
{
request.subscription.paymentMethod = "credit card";
}
// Update the schedule
ReplyMessage reply = SubmitTransaction( financialGateway, request, out errorMessage );
if ( reply != null && reply.reasonCode.Equals( GATEWAY_RESPONSE_SUCCESS ) )
{
return true;
}
else if ( string.IsNullOrEmpty( errorMessage ) )
{
errorMessage = string.Format( "Unable to update this transaction. {0}", ProcessError( reply ) );
}
return false;
}
/// <summary>
/// Cancels the scheduled payment.
/// </summary>
/// <param name="transaction">The transaction.</param>
/// <param name="errorMessage">The error message.</param>
/// <returns></returns>
public override bool CancelScheduledPayment( FinancialScheduledTransaction transaction, out string errorMessage )
{
errorMessage = string.Empty;
var financialGateway = transaction.FinancialGateway;
RequestMessage request = GetMerchantInfo( transaction.FinancialGateway, false );
request.recurringSubscriptionInfo = new RecurringSubscriptionInfo();
request.recurringSubscriptionInfo.subscriptionID = transaction.TransactionCode;
request.paySubscriptionUpdateService = new PaySubscriptionUpdateService();
request.recurringSubscriptionInfo.status = "cancel";
request.paySubscriptionUpdateService.run = "true";
// Cancel the payment
ReplyMessage reply = SubmitTransaction( financialGateway, request, out errorMessage );
if ( reply != null && reply.reasonCode.Equals( GATEWAY_RESPONSE_SUCCESS ) )
{
return true;
}
else if ( string.IsNullOrEmpty( errorMessage ) )
{
errorMessage = string.Format( "Unable to cancel this transaction. {0}", ProcessError( reply ) );
}
return false;
}
/// <summary>
/// Gets the scheduled payment status.
/// </summary>
/// <param name="transaction">The transaction.</param>
/// <param name="errorMessage">The error message.</param>
/// <returns></returns>
public override bool GetScheduledPaymentStatus( FinancialScheduledTransaction transaction, out string errorMessage )
{
errorMessage = string.Empty;
var financialGateway = transaction.FinancialGateway;
RequestMessage verifyRequest = GetMerchantInfo( financialGateway );
verifyRequest.paySubscriptionRetrieveService = new PaySubscriptionRetrieveService();
verifyRequest.paySubscriptionRetrieveService.run = "true";
verifyRequest.recurringSubscriptionInfo = new RecurringSubscriptionInfo();
verifyRequest.recurringSubscriptionInfo.subscriptionID = transaction.TransactionCode;
// Get the payment status
ReplyMessage reply = SubmitTransaction( financialGateway, verifyRequest, out errorMessage );
if ( reply != null && reply.reasonCode.Equals( GATEWAY_RESPONSE_SUCCESS ) )
{
transaction.IsActive = reply.paySubscriptionRetrieveReply.status.ToUpper() == "CURRENT";
var startDate = GetDate( reply.paySubscriptionRetrieveReply.startDate );
transaction.StartDate = startDate ?? transaction.StartDate;
transaction.NextPaymentDate = NextPaymentDate( startDate, reply.paySubscriptionRetrieveReply.frequency ) ?? transaction.NextPaymentDate;
transaction.NumberOfPayments = reply.paySubscriptionRetrieveReply.totalPayments.AsIntegerOrNull() ?? transaction.NumberOfPayments;
transaction.LastStatusUpdateDateTime = DateTime.Now;
return true;
}
else if ( string.IsNullOrEmpty( errorMessage ) )
{
errorMessage = ProcessError( reply );
}
return false;
}
/// <summary>
/// Gets the payments that have been processed for any scheduled transactions
/// </summary>
/// <param name="startDate">The start date.</param>
/// <param name="endDate">The end date.</param>
/// <param name="errorMessage">The error message.</param>
/// <returns></returns>
public override List<Payment> GetPayments( FinancialGateway financialGateway, DateTime startDate, DateTime endDate, out string errorMessage )
{
errorMessage = string.Empty;
List<Payment> paymentList = new List<Payment>();
var reportParams = new Dictionary<string, string>();
var reportingApi = new Reporting.Api(
GetAttributeValue( financialGateway, "MerchantID" ),
GetAttributeValue( financialGateway, "TransactionKey" ),
GetAttributeValue( financialGateway, "ReportUser" ),
GetAttributeValue( financialGateway, "ReportPassword" ),
GetAttributeValue( financialGateway, "Mode" ).Equals( "Live", StringComparison.CurrentCultureIgnoreCase )
);
TimeSpan timeDifference = endDate - startDate;
for ( int offset = 0; offset <= timeDifference.TotalDays; offset++ )
{
DateTime offsetDate = startDate.AddDays( offset ) < endDate ? startDate.AddDays( offset ) : endDate;
reportParams.Add( "date", offsetDate.ToString( "yyyy/MM/dd" ) );
DataTable dt = reportingApi.GetReport( "SubscriptionDetailReport", reportParams, out errorMessage );
if ( dt != null && dt.Rows.Count > 0 )
{
foreach ( DataRow row in dt.Rows )
{
var payment = new Payment();
decimal amount = decimal.MinValue;
payment.Amount = decimal.TryParse( row["Amount"].ToString(), out amount ) ? amount : 0.0M;
var time = DateTime.MinValue;
payment.TransactionDateTime = DateTime.TryParse( row["Time"].ToString(), out time ) ? time : DateTime.MinValue;
payment.TransactionCode = row["Code"].ToString();
payment.GatewayScheduleId = row["Schedule"].ToString();
payment.ScheduleActive = row["Status"].ToString() == "CURRENT";
paymentList.Add( payment );
}
}
reportParams.Clear();
}
if ( paymentList.Any() )
{
return paymentList;
}
else
{
errorMessage = "The subscription detail report did not return any data for the timeframe";
return null;
}
}
/// <summary>
/// Gets the reference number from the gateway for converting a transaction to a billing profile.
/// </summary>
/// <param name="transaction">The transaction.</param>
/// <param name="errorMessage">The error message.</param>
/// <returns></returns>
public override string GetReferenceNumber( FinancialTransaction transaction, out string errorMessage )
{
errorMessage = string.Empty;
var financialGateway = transaction.FinancialGateway;
RequestMessage request = GetMerchantInfo( financialGateway );
request.billTo = GetBillTo( transaction );
request.recurringSubscriptionInfo = new RecurringSubscriptionInfo();
request.recurringSubscriptionInfo.frequency = "ON-DEMAND";
request.recurringSubscriptionInfo.amount = "0";
request.paySubscriptionCreateService = new PaySubscriptionCreateService();
request.paySubscriptionCreateService.run = "true";
request.paySubscriptionCreateService.paymentRequestID = transaction.TransactionCode;
// Get the reference code
ReplyMessage reply = SubmitTransaction( financialGateway, request, out errorMessage );
if ( reply != null && reply.reasonCode == GATEWAY_RESPONSE_SUCCESS )
{
return reply.paySubscriptionCreateReply.subscriptionID;
}
else if ( string.IsNullOrEmpty( errorMessage ) )
{
errorMessage = ProcessError( reply );
}
return string.Empty;
}
/// <summary>
/// Gets the reference number needed to process future payments from this scheduled transaction.
/// </summary>
/// <param name="scheduledTransaction">The scheduled transaction.</param>
/// <param name="errorMessage">The error message.</param>
/// <returns></returns>
public override string GetReferenceNumber( FinancialScheduledTransaction scheduledTransaction, out string errorMessage )
{
errorMessage = string.Empty;
return scheduledTransaction.TransactionCode;
}
#endregion Gateway Component Implementation
#region Process Transaction
/// <summary>
/// Submits the transaction.
/// </summary>
/// <param name="request">The request.</param>
/// <returns></returns>
private ReplyMessage SubmitTransaction( FinancialGateway financialGateway, RequestMessage request, out string errorMessage )
{
ReplyMessage reply = new ReplyMessage();
TransactionProcessorClient client = GetProxyClient( financialGateway, out errorMessage );
// Error message already set, return
if ( client == null )
{
return null;
}
try
{
reply = client.runTransaction( request );
return reply;
}
catch ( TimeoutException e )
{
reply.reasonCode = "151";
reply.additionalData = e.ToString();
return reply;
}
catch ( FaultException e )
{
reply.reasonCode = "150";
reply.additionalData = e.ToString();
return reply;
}
catch ( Exception e )
{
reply.reasonCode = "";
reply.additionalData = e.ToString();
return reply;
}
}
/// <summary>
/// Processes the error message.
/// </summary>
/// <param name="reply">The reply.</param>
/// <returns></returns>
private string ProcessError( ReplyMessage reply )
{
// Make sure the reply is valid
if ( reply == null )
{
return "Invalid response from the paymnent gateway.";
}
int reasonCode = int.Parse( reply.reasonCode );
switch ( reasonCode )
{
// Missing field or fields
case 101:
return "\nThe following required fields are missing: " + string.Join( "\n", reply.missingField ?? new string[0] );
// Invalid field or fields
case 102:
return "\nThe following fields are invalid: " + string.Join( "\n", reply.invalidField ?? new string[0] );
// Partial payment approved
case 110:
return "\nOnly a partial amount of this transaction was approved.";
// General system failure
case 150:
return string.Format( "\nThe payment processor did not process your payment. {0}", reply.additionalData );
// System timeout
case 151:
return string.Format( "\nThe payment request timed out. {0}", reply.additionalData ); ;
// Service request timed out
case 152:
return "\nThe payment service timed out.";
// AVS check failed
case 200:
return "\nThe payment billing address did not match the bank's address on record. Please verify your address details.";
// Expired card
case 202:
return "\nThe card has expired. Please use a different card or select another form of payment.";
// Card declined
case 203:
return "\nThe card was declined without a reason given. Please use a different card or select another form of payment.";
// Insufficient funds
case 204:
return "\nInsufficient funds in the account. Please use another form of payment.";
// Stolen card
case 205:
return "\nThe card has been reported stolen. Please use a different card or select another form of payment.";
// Bank unavailable
case 207:
return "\nThe bank processor is temporarily unavailable. Please try again in a few minutes.";
// Card not active
case 208:
return "\nThe card is inactive or not authorized for internet transactions. Please use a different card or select another form of payment.";
// AmEx invalid CID
case 209:
return "\nThe card identification digit did not match. Please use a different card or select another form of payment.";
// Maxed out
case 210:
return "\nThe card has reached its credit limit. Please use a different card or select another form of payment.";
// Invalid verification #
case 211:
return "\nThe card verification number is invalid. Please verify your 3 or 4 digit verification number.";
// Frozen account
case 222:
return "\nThe selected account has been frozen. Please use another form of payment.";
// Invalid verification #
case 230:
return "\nThe card verification number is invalid. Please verify your 3 or 4 digit verification number.";
// Invalid account #
case 231:
return "\nThe account number is invalid. Please use another form of payment.";
// Invalid merchant config
case 234:
return "\nThe merchant configuration is invalid. Please contact CyberSource customer support.";
// Processor failure
case 236:
return "\nThe payment processor is offline. Please try again in a few minutes.";
// Card type not accepted
case 240:
return "\nThe card type is not accepted by the merchant. Please use another form of payment.";
// Payment processor timeout
case 250:
return "\nThe payment request was received but has not yet been processed.";
// Any others not identified
default:
return string.Format( "\nYour payment was not processed. {0}", reply.additionalData );
}
}
#endregion Process Transaction
#region Helper Methods
/// <summary>
/// Gets the merchant information.
/// </summary>
/// <returns></returns>
private RequestMessage GetMerchantInfo( FinancialGateway financialGateway, bool includeEnvironment = true )
{
if ( financialGateway.Attributes == null )
{
financialGateway.LoadAttributes();
}
RequestMessage request = new RequestMessage();
request.merchantID = GetAttributeValue( financialGateway, "MerchantID" );
request.merchantReferenceCode = Guid.NewGuid().ToString();
if ( includeEnvironment )
{
request.clientLibraryVersion = Environment.Version.ToString();
request.clientApplication = VersionInfo.GetRockProductVersionFullName();
request.clientApplicationVersion = VersionInfo.GetRockProductVersionNumber();
request.clientApplicationUser = GetAttributeValue( financialGateway, "OrganizationName" );
request.clientEnvironment =
Environment.OSVersion.Platform +
Environment.OSVersion.Version.ToString() + "-CLR" +
Environment.Version.ToString();
}
return request;
}
/// <summary>
/// Gets the proxy client.
/// </summary>
/// <param name="financialGateway">The financial gateway.</param>
/// <returns></returns>
private TransactionProcessorClient GetProxyClient( FinancialGateway financialGateway, out string errorMessage )
{
errorMessage = string.Empty;
string merchantID = GetAttributeValue( financialGateway, "MerchantID" );
string transactionkey = GetAttributeValue( financialGateway, "TransactionKey" );
string gatewayEndpoint = null;
if ( GetAttributeValue( financialGateway, "Mode" ).Equals( "Live", StringComparison.CurrentCultureIgnoreCase ) )
{
gatewayEndpoint = GetAttributeValue( financialGateway, "LiveGatewayURL" );
}
else
{
gatewayEndpoint = GetAttributeValue( financialGateway, "TestGatewayURL" );
}
EndpointAddress address = null;
if ( !string.IsNullOrEmpty( gatewayEndpoint ) )
{
gatewayEndpoint = gatewayEndpoint.EnsureTrailingForwardslash();
address = new EndpointAddress( string.Format( "{0}CyberSourceTransaction_{1}", gatewayEndpoint, GATEWAY_VERSION ) );
}
else
{
errorMessage = "Financial gateway is not configured with a valid endpoint.";
return null;
}
BasicHttpBinding binding = new BasicHttpBinding();
binding.Name = "ITransactionProcessor";
binding.MaxBufferSize = 2147483647;
binding.MaxBufferPoolSize = 2147483647;
binding.MaxReceivedMessageSize = 2147483647;
binding.ReaderQuotas.MaxDepth = 2147483647;
binding.ReaderQuotas.MaxArrayLength = 2147483647;
binding.ReaderQuotas.MaxBytesPerRead = 2147483647;
binding.ReaderQuotas.MaxStringContentLength = 2147483647;
binding.Security.Mode = BasicHttpSecurityMode.TransportWithMessageCredential;
var proxy = new TransactionProcessorClient( binding, address );
proxy.ClientCredentials.UserName.UserName = merchantID;
proxy.ClientCredentials.UserName.Password = transactionkey;
proxy.Endpoint.Address = address;
proxy.Endpoint.Binding = binding;
return proxy;
}
/// <summary>
/// Gets the payment information.
/// </summary>
/// <returns></returns>
private RequestMessage GetPaymentInfo( FinancialGateway financialGateway, PaymentInfo paymentInfo )
{
RequestMessage request = GetMerchantInfo( financialGateway );
if ( paymentInfo is CreditCardPaymentInfo )
{
var cc = paymentInfo as CreditCardPaymentInfo;
request.card = GetCard( cc );
}
else if ( paymentInfo is ACHPaymentInfo )
{
var ach = paymentInfo as ACHPaymentInfo;
request.check = GetCheck( ach );
}
else if ( paymentInfo is ReferencePaymentInfo )
{
var reference = paymentInfo as ReferencePaymentInfo;
request.recurringSubscriptionInfo = new RecurringSubscriptionInfo();
request.recurringSubscriptionInfo.subscriptionID = reference.ReferenceNumber;
}
else
{
return null;
}
return request;
}
/// <summary>
/// Gets the billing details from user submitted payment info.
/// </summary>
/// <param name="paymentInfo">The payment information.</param>
/// <returns></returns>
private BillTo GetBillTo( PaymentInfo paymentInfo )
{
BillTo billingInfo = new BillTo();
if ( paymentInfo.Phone == null )
{
paymentInfo.Phone = string.Empty;
}
if ( paymentInfo is CreditCardPaymentInfo )
{
var cc = paymentInfo as CreditCardPaymentInfo;
billingInfo.street1 = cc.BillingStreet1.Left( 50 );
billingInfo.city = cc.BillingCity.Left( 50 );
billingInfo.state = cc.BillingState.Left( 2 );
billingInfo.postalCode = cc.BillingPostalCode.Left( 10 );
}
else
{
billingInfo.street1 = paymentInfo.Street1.Left( 50 ); // up to 50 chars
billingInfo.city = paymentInfo.City.Left( 50 ); // up to 50 chars
billingInfo.state = paymentInfo.State.Left( 2 ); // only 2 chars
var zip = paymentInfo.PostalCode;
if ( !string.IsNullOrWhiteSpace( zip ) && zip.Length > 5 )
{
Regex.Replace( zip, @"^(.{5})(.{4})$", "$1-$2" ); // up to 9 chars with a separating -
}
billingInfo.postalCode = zip;
}
billingInfo.firstName = paymentInfo.FirstName.Left( 50 ); // up to 50 chars
billingInfo.lastName = paymentInfo.LastName.Left( 60 ); // up to 60 chars
billingInfo.email = paymentInfo.Email; // up to 255 chars
billingInfo.phoneNumber = paymentInfo.Phone.Left( 15 ); // up to 15 chars
var country = paymentInfo.Country ?? "US";
billingInfo.country = country.Left( 2 ); // only 2 chars
var ipAddr = Dns.GetHostEntry( Dns.GetHostName() ).AddressList
.FirstOrDefault( ip => ip.AddressFamily == AddressFamily.InterNetwork );
billingInfo.ipAddress = ipAddr.ToString(); // machine IP address
return billingInfo;
}
/// <summary>
/// Gets the bill to from a transaction.
/// </summary>
/// <param name="transaction">The transaction.</param>
/// <returns></returns>
private BillTo GetBillTo( FinancialTransaction transaction )
{
BillTo billingInfo = new BillTo();
billingInfo.customerID = transaction.AuthorizedPersonAlias.Id.ToString();
billingInfo.firstName = transaction.AuthorizedPersonAlias.Person.FirstName.Left( 50 ); // up to 50 chars
billingInfo.lastName = transaction.AuthorizedPersonAlias.Person.LastName.Left( 50 ); // up to 60 chars
billingInfo.email = transaction.AuthorizedPersonAlias.Person.Email.Left( 255 ); // up to 255 chars
billingInfo.ipAddress = Dns.GetHostEntry( Dns.GetHostName() )
.AddressList.FirstOrDefault( ip => ip.AddressFamily == AddressFamily.InterNetwork ).ToString();
return billingInfo;
}
/// <summary>
/// Gets the total payment item.
/// </summary>
/// <param name="paymentInfo">The payment information.</param>
/// <returns></returns>
private Item[] GetItems( PaymentInfo paymentInfo )
{
List<Item> itemList = new List<Item>();
Item item = new Item();
item.id = "0";
item.unitPrice = paymentInfo.Amount.ToString();
item.totalAmount = paymentInfo.Amount.ToString();
itemList.Add( item );
return itemList.ToArray();
}
/// <summary>
/// Gets the purchase totals.
/// </summary>
/// <returns></returns>
private PurchaseTotals GetTotals()
{
// paymentInfo not used here since fixed payment installments not implemented
PurchaseTotals purchaseTotals = new PurchaseTotals();
purchaseTotals.currency = "USD";
return purchaseTotals;
}
/// <summary>
/// Gets the card information.
/// </summary>
/// <param name="paymentInfo">The payment information.</param>
/// <returns></returns>
private Card GetCard( CreditCardPaymentInfo cc )
{
var card = new Card();
card.accountNumber = cc.Number.AsNumeric();
card.expirationMonth = cc.ExpirationDate.Month.ToString( "D2" );
card.expirationYear = cc.ExpirationDate.Year.ToString( "D4" );
card.cvNumber = cc.Code.AsNumeric();
card.cvIndicator = "1";
if ( cc.CreditCardTypeValue != null )
{
switch ( cc.CreditCardTypeValue.Value )
{
case "Visa":
card.cardType = "001";
break;
case "MasterCard":
card.cardType = "002";
break;
case "American Express":
card.cardType = "003";
break;