Filter:   InfoImg
download APIWrapper.cs
Language: C#
LOC: 593
Project Info
CommerceStarterKit
Server: CodePlex
Type: tfs
...mmerce.Web\App_Code\PayPal\
   APIWrapper.cs
   PayPalHelper.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
using System;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.IO;
using System.Web.Services.Protocols;
using System.Data;
using PayPalSvc;
namespace Commerce.PayPal {
	/// <summary>
	/// Summary description for APIWrapper.
	/// </summary>
	
	public class APIWrapper {
		
		
		#region Required Properties
		string _APIUserName="";
		string _APIPassword="";
		string _CertLocation="";
        string _CertPassword = "";
        Commerce.Common.CurrencyCode _currencyCode = Commerce.Common.CurrencyCode.USD;
        CurrencyCodeType ppCurrencyType = CurrencyCodeType.USD;


        public Commerce.Common.CurrencyCode CurrencyCode
        {
            get { return _currencyCode; }
        }
		public string APIUserName{
			get{return _APIUserName;}
		}
		public string APIPassword{
			get{return _APIPassword;}
		}
		public string CertLocation{
			get{return _CertLocation;}
		}
        public string CertPassword {
            get { return _CertPassword; }
        }
		#endregion

        PayPalAPISoapBinding service;
        PayPalAPIAASoapBinding service2;
       
        #region .ctor
        public APIWrapper(String apiUserName, string apiPassword, string certLocation, string certPassword, Commerce.Common.CurrencyCode currencyCode)
        {
            _APIUserName = apiUserName;
            _APIPassword = apiPassword;
            _CertLocation = certLocation;
            _CertPassword = certPassword;
            _currencyCode = currencyCode;

            string currCode = Enum.GetName(typeof(Commerce.Common.CurrencyCode), _currencyCode);
            ppCurrencyType = (CurrencyCodeType)Utility.StringToEnum(typeof(CurrencyCodeType), currCode);



            service = new PayPalAPISoapBinding();
            service.RequesterCredentials = new CustomSecurityHeaderType();
            service.RequesterCredentials.Credentials = new UserIdPasswordType();
            service.RequesterCredentials.Credentials.Username = _APIUserName;
            service.RequesterCredentials.Credentials.Password = _APIPassword;
            service.RequesterCredentials.Credentials.Subject = "";

            service2 = new PayPalAPIAASoapBinding();
            service2.RequesterCredentials = new CustomSecurityHeaderType();
            service2.RequesterCredentials.Credentials = new UserIdPasswordType();
            service2.RequesterCredentials.Credentials.Username = _APIUserName;
            service2.RequesterCredentials.Credentials.Password = _APIPassword;
            service2.RequesterCredentials.Credentials.Subject = "";

            FileStream fs = File.Open(_CertLocation, FileMode.Open, FileAccess.Read);

            byte[] buffer = new byte[fs.Length];

            int count = fs.Read(buffer, 0, buffer.Length);

            fs.Close();

            X509Certificate2 cert = new X509Certificate2(buffer, _CertPassword,X509KeyStorageFlags.MachineKeySet);
            service2.ClientCertificates.Add(cert);
            service.ClientCertificates.Add(cert);

        }
        #endregion

        #region Info APIs
        public string RefundTransaction(string TransactionID, decimal RefundAmount, string Memo, string currencyCode){

			string sReturn="";
            CurrencyCodeType currType = (CurrencyCodeType)StringToEnum(typeof(CurrencyCodeType), currencyCode);
            // Create the Refund Request
            RefundTransactionRequestType refundRequest = new RefundTransactionRequestType();
            BasicAmountType amount = new BasicAmountType();
            amount.currencyID = currType;
			
            amount.Value=RefundAmount.ToString();
			refundRequest.Memo = Memo;
			refundRequest.Amount=amount;


            refundRequest.RefundType = RefundPurposeTypeCodeType.Partial;
			refundRequest.TransactionID = TransactionID;
			refundRequest.Version = "1.0";

            RefundTransactionReq request = new RefundTransactionReq();
			request.RefundTransactionRequest = refundRequest;


			try{
                RefundTransactionResponseType response = service.RefundTransaction(request);
			
				string ErrorCheck=CheckErrors(response);
				if (ErrorCheck!="") {
					sReturn=("The transaction was not successful: " + ErrorCheck);
				}
				else {
					sReturn=("Success");
				}
			}catch(Exception x){
				sReturn="SSL Failure, the transaction did not go through. Error: "+x.Message;

			}
			return sReturn;

		}
		public string RefundTransaction(string TransactionID, bool DoFullRefund){

			string sReturn="";
			
            // Create the Refund Request
            RefundTransactionRequestType refundRequest = new RefundTransactionRequestType();
            BasicAmountType amount = new BasicAmountType();
            
            CurrencyCodeType currType = (CurrencyCodeType)this._currencyCode;
            amount.currencyID = currType;
          
            if (DoFullRefund) {
                refundRequest.RefundType = RefundPurposeTypeCodeType.Full;
            } else {
                refundRequest.RefundType = RefundPurposeTypeCodeType.Partial;
            }
			refundRequest.TransactionID = TransactionID;
			refundRequest.Version = "1.0";

            RefundTransactionReq request = new RefundTransactionReq();
			request.RefundTransactionRequest = refundRequest;


			try{
                RefundTransactionResponseType response = service.RefundTransaction(request);
				string ErrorCheck=CheckErrors(response);
				if (ErrorCheck!="") {
                    sReturn = ErrorCheck;
				}
				else {
                    sReturn = "Success";

                }
			}catch(Exception x){
                sReturn = "SSL Failure, the transaction did not go through. Error: " + x.Message;

			}
            return sReturn;

        }
		
        public string GetTransactionDetail(string transactionID, string delimiter){
			string sReturn="";
                GetTransactionDetailsRequestType detailRequest = new GetTransactionDetailsRequestType();
                detailRequest.TransactionID = transactionID;
                detailRequest.Version = "1.0";
                GetTransactionDetailsReq request = new GetTransactionDetailsReq();
                request.GetTransactionDetailsRequest = detailRequest;

                GetTransactionDetailsResponseType response = service.GetTransactionDetails(request);

                sReturn = response.Ack.ToString() + "\n";

                string sErrors = this.CheckErrors(response);
                if (sErrors == string.Empty) {
                    //build out the response
                    StringBuilder sb = new StringBuilder();
                    sb.Append("************** Payment Information ******************" + delimiter);

                    //payment info
                    PaymentInfoType payment = response.PaymentTransactionDetails.PaymentInfo;
                    sb.Append("ReceiptID: " + payment.ReceiptID + delimiter);
                    sb.Append("TransactionID: " + payment.TransactionID + delimiter);
                    sb.Append("PaymentDate: " + payment.PaymentDate + delimiter);
                    sb.Append("GrossAmount: " + GetAmountValue(payment.GrossAmount) + delimiter);
                    sb.Append("SettleAmount: " + GetAmountValue(payment.SettleAmount) + delimiter);
                    sb.Append("FeeAmount: " + GetAmountValue(payment.FeeAmount) + delimiter);
                    sb.Append("TaxAmount: " + GetAmountValue(payment.TaxAmount) + delimiter);
                    sb.Append("PaymentStatus: " + payment.PaymentStatus + delimiter);
                    sb.Append("PaymentType: " + payment.PaymentType + delimiter);
                    sb.Append("TransactionType: " + payment.TransactionType + delimiter);
                    sb.Append(delimiter);
                    //sReturn+=response.PaymentTransactionDetails.PaymentInfo.ToString();
                    sb.Append("************** Buyer Information ******************" + delimiter);

                    //receiver info
                    ReceiverInfoType receiver = response.PaymentTransactionDetails.ReceiverInfo;
                    sb.Append("Business: " + receiver.Business + delimiter);
                    sb.Append("Receiver: " + receiver.Receiver + delimiter);
                    sb.Append("ReceiverID: " + receiver.ReceiverID + delimiter);

                    /*
                     * --- Uncomment this to report Auction and Subscription info
                    sb.Append("************** Auction Information ******************"+delimiter);

                    AuctionInfoType auction=new AuctionInfoType();
                    sb.Append("BuyerID: "+auction.BuyerID+delimiter);
                    sb.Append("ClosingDate: "+auction.ClosingDate+delimiter);
                    sb.Append("ClosingDateSpecified: "+auction.ClosingDateSpecified+delimiter);
                    sb.Append("multiItem: "+auction.multiItem+delimiter);

                    sb.Append("************** Subscription Information ******************"+delimiter);

                    SubscriptionInfoType sub=new SubscriptionInfoType();

                    sb.Append("EffectiveDate: "+sub.EffectiveDate+delimiter);
                    sb.Append("EffectiveDateSpecified: "+sub.EffectiveDateSpecified+delimiter);
                    sb.Append("Password: "+sub.Password+delimiter);
                    sb.Append("reattempt: "+sub.reattempt+delimiter);
                    sb.Append("Recurrences: "+sub.Recurrences+delimiter);
                    sb.Append("recurring: "+sub.recurring+delimiter);
                    sb.Append("RetryTime: "+sub.RetryTime+delimiter);
                    sb.Append("RetryTimeSpecified: "+sub.RetryTimeSpecified+delimiter);
                    sb.Append("SubscriptionDate: "+sub.SubscriptionDate+delimiter);
                    sb.Append("SubscriptionDateSpecified: "+sub.SubscriptionDateSpecified+delimiter);
                    sb.Append("SubscriptionID: "+sub.SubscriptionID+delimiter);
                    sb.Append("Terms: "+sub.Terms+delimiter);
                    sb.Append("Username: "+sub.Username+delimiter);
                    */
                    sReturn = sb.ToString();
                } else {
                    sReturn = sErrors;
                }

            return sReturn;
						
		}
		public DataTable GetTransactionSearch(DateTime StartDate,TransactionSearchParam param, string delimiter){
			DataTable table=new DataTable("results");
            TransactionSearchRequestType transSearch = new TransactionSearchRequestType();

			// Set up the TransactionSearch
            TransactionSearchReq request = new TransactionSearchReq();
			transSearch.StartDate=StartDate;

            request.TransactionSearchRequest = new TransactionSearchRequestType();
			transSearch.Version = "1.0";
			transSearch.CurrencyCodeSpecified = false;
			transSearch.EndDateSpecified = false;
			transSearch.StatusSpecified = false;

			//set the params
			transSearch.StartDate=StartDate;
			transSearch.EndDate = param.EndDate;
			
			#region args list
			int args=1;
			if(param.TransactionID!=""){
				transSearch.TransactionID = param.TransactionID;
				args++;
			}

			if(param.Amount!=""){
                transSearch.Amount = new BasicAmountType();
				transSearch.Amount.Value = param.Amount;
				args++;
			}
			if(param.PayerEmail!=""){
				transSearch.Payer = param.PayerEmail;
				args++;
			}

			if(param.Currency!=""){
				transSearch.CurrencyCodeSpecified = true;
				args++;
			}

			if(param.ItemNumber!=""){
				transSearch.AuctionItemNumber = param.ItemNumber;
				args++;
			}

			if(param.LastName!=""){
                transSearch.PayerName = new PersonNameType();
				transSearch.PayerName.LastName = param.LastName;
				args++;
			}

			if(param.FirstName!=""){
                transSearch.PayerName = new PersonNameType();
				transSearch.PayerName.FirstName = param.FirstName;
				args++;
			}

			if(param.PaymentStatus!=""){
				transSearch.StatusSpecified = true;
				args++;
			}

			if(param.PaymentType!=""){
				transSearch.TransactionClassSpecified = true;
				args++;
			}
			#endregion

			request.TransactionSearchRequest=transSearch;

			//if there are more than 0 args set, run the transaction
			if(args>0){
				//run the transactioon
                TransactionSearchResponseType response = service.TransactionSearch(request);

				if(response!=null){
					if(response.PaymentTransactions!=null){
						//build the columns out
						DataColumn cTransactionID=new DataColumn("TransactionID");
						DataColumn cFeeAmount=new DataColumn("FeeAmount");
						DataColumn cGrossAmount=new DataColumn("GrossAmount");
						DataColumn cNetAmount=new DataColumn("NetAmount");
						DataColumn cPayer=new DataColumn("Payer");
						DataColumn cPayerDisplayName=new DataColumn("PayerDisplayName");
						DataColumn cStatus=new DataColumn("Status");
						DataColumn cTimestamp=new DataColumn("Timestamp");
						DataColumn cType=new DataColumn("Type");

						table.Columns.Add(cTransactionID);
						table.Columns.Add(cFeeAmount);
						table.Columns.Add(cGrossAmount);
						table.Columns.Add(cNetAmount);
						table.Columns.Add(cPayer);
						table.Columns.Add(cPayerDisplayName);
						table.Columns.Add(cStatus);
						table.Columns.Add(cTimestamp);
						table.Columns.Add(cType);

						DataRow dr;
                        foreach (PaymentTransactionSearchResultType trans in response.PaymentTransactions) {
							dr=table.NewRow();
							dr["TransactionID"]=trans.TransactionID;			
							dr["FeeAmount"]=GetAmountValue(trans.FeeAmount);			
							dr["GrossAmount"]=GetAmountValue(trans.GrossAmount);			
							dr["NetAmount"]=GetAmountValue(trans.NetAmount);			
							dr["Payer"]=trans.Payer;			
							dr["PayerDisplayName"]=trans.PayerDisplayName;			
							dr["Status"]=trans.Status;			
							dr["Timestamp"]=trans.Timestamp.ToLongDateString();			
							dr["Type"]=trans.Type.ToString();			

							table.Rows.Add(dr);
						}	
					}
					
				}				

			}else{

				throw new Exception("You must specify at least one search paramater");

			}
			
			return table;
		}
	    public string RunTransactionSearch(DateTime StartDate,TransactionSearchParam param, string delimiter){
    	
		    string sOut="";
            TransactionSearchRequestType transSearch = new TransactionSearchRequestType();

		    // Set up the TransactionSearch
            TransactionSearchReq request = new TransactionSearchReq();
		    transSearch.StartDate=StartDate;

            request.TransactionSearchRequest = new TransactionSearchRequestType();
		    transSearch.Version = "1.0";
		    transSearch.CurrencyCodeSpecified = false;
		    transSearch.EndDateSpecified = false;
		    transSearch.StatusSpecified = false;

		    //set the params
		    transSearch.StartDate=StartDate;
		    transSearch.EndDate = param.EndDate;
    		
		    #region args list
		    int args=1;
		    if(param.TransactionID!=""){
			    transSearch.TransactionID = param.TransactionID;
			    args++;
		    }

		    if(param.Amount!=""){
                transSearch.Amount = new BasicAmountType();
			    transSearch.Amount.Value = param.Amount;
			    args++;
		    }
		    if(param.PayerEmail!=""){
			    transSearch.Payer = param.PayerEmail;
			    args++;
		    }

		    if(param.Currency!=""){
			    transSearch.CurrencyCodeSpecified = true;
			    args++;
		    }

		    if(param.ItemNumber!=""){
			    transSearch.AuctionItemNumber = param.ItemNumber;
			    args++;
		    }

		    if(param.LastName!=""){
                transSearch.PayerName = new PersonNameType();
			    transSearch.PayerName.LastName = param.LastName;
			    args++;
		    }

		    if(param.FirstName!=""){
                transSearch.PayerName = new PersonNameType();
			    transSearch.PayerName.FirstName = param.FirstName;
			    args++;
		    }

		    if(param.PaymentStatus!=""){
			    transSearch.StatusSpecified = true;
			    args++;
		    }

		    if(param.PaymentType!=""){
			    transSearch.TransactionClassSpecified = true;
			    args++;
		    }
		    #endregion

		    request.TransactionSearchRequest=transSearch;

		    //if there are more than 0 args set, run the transaction
		    if(args>0){
			    //run the transactioon
			    TransactionSearchResponseType response = service.TransactionSearch(request);

			    StringBuilder sb=new StringBuilder();
			    sb.Append("Status: "+response.Ack.ToString()+delimiter);
			    sb.Append("*********** Results ***************"+delimiter);
			    if(response!=null){
				    sb.Append( "Ack"+response.Ack +delimiter);
				    sb.Append( "Version"+response.Version+delimiter );
				    sb.Append( "Build"+response.Build +delimiter);
				    sb.Append( "CorrelationID"+response.CorrelationID+delimiter );
    			
				    if (response.TimestampSpecified )
					    sb.Append( "Timestamp"+response.Timestamp+delimiter );
				    else
					    sb.Append( "Timestamp Not specified"+delimiter );
    				
				    //PaymentTransactionSearchResultType[] trans=new PaymentTransactionSearchResultType();
    				
				    //sb.Append( "PaymentTransactions: "+response.PaymentTransactions.Length.ToString()+delimiter );
				    if(response.PaymentTransactions!=null){
					    foreach(PaymentTransactionSearchResultType trans in response.PaymentTransactions){
    										
						    sb.Append("TransactionID: "+trans.TransactionID+delimiter);
						    sb.Append("FeeAmount: "+GetAmountValue(trans.FeeAmount)+delimiter);
						    sb.Append("GrossAmount: "+GetAmountValue(trans.GrossAmount)+delimiter);
						    sb.Append("NetAmount: "+GetAmountValue(trans.NetAmount)+delimiter);
						    sb.Append("Payer: "+trans.Payer+delimiter);
						    sb.Append("PayerDisplayName: "+trans.PayerDisplayName+delimiter);
						    sb.Append("Status: "+trans.Status+delimiter);
						    sb.Append("Timestamp: "+trans.Timestamp.ToLongDateString()+delimiter);
						    sb.Append("Type: "+trans.Type.ToString()+delimiter);
						    sb.Append("--"+delimiter+delimiter);


					    }	
				    }
    				
				    sOut=sb.ToString();
			    }else{
				    sOut=sb.ToString()+delimiter+"No Results!";
			    }				

		    }else{

			    throw new Exception("You must specify at least one search paramater");

		    }
    		
		    return sOut;
        }
        #endregion

        #region Payment APIs
        public string SetExpressCheckout(string billToEmail, decimal dTotal, string returnUrl, string cancelUrl)
        {
            
            PayPalSvc.SetExpressCheckoutReq setRequest = new SetExpressCheckoutReq();
            PayPalSvc.SetExpressCheckoutRequestDetailsType setDetails = new SetExpressCheckoutRequestDetailsType();
            setRequest.SetExpressCheckoutRequest = new SetExpressCheckoutRequestType();

            setDetails.BuyerEmail = billToEmail;
            setDetails.OrderTotal = GetBasicAmount(dTotal);


            setDetails.ReturnURL = returnUrl;
            setDetails.CancelURL = cancelUrl;
            
            setRequest.SetExpressCheckoutRequest.Version = "1.0";
            setRequest.SetExpressCheckoutRequest.SetExpressCheckoutRequestDetails = setDetails;
            PayPalSvc.SetExpressCheckoutResponseType setResponse=service2.SetExpressCheckout(setRequest);

            string errors = this.CheckErrors(setResponse);
            string sOut = "";
            if (errors == string.Empty) {
                sOut = setResponse.Token;
            } else {
                sOut = errors;
            }
            return sOut;
        }

        public Commerce.Common.Address GetExpressCheckout(string token) {
            //PayerInfo payer = new PayerInfo();
            Commerce.Common.Address payer = new Commerce.Common.Address();

            PayPalSvc.GetExpressCheckoutDetailsReq req = new GetExpressCheckoutDetailsReq();
            PayPalSvc.GetExpressCheckoutDetailsRequestType requestType = new GetExpressCheckoutDetailsRequestType();

           
            requestType.Token=token;
            requestType.Version = "1.0";

            req.GetExpressCheckoutDetailsRequest = requestType;

            PayPalSvc.GetExpressCheckoutDetailsResponseType response= service2.GetExpressCheckoutDetails(req);

            string sOut = "";
            
            string errors = this.CheckErrors(response);
            if (errors == string.Empty) {
                string ack = response.Ack.ToString();
                payer.Email = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Payer;
                payer.PayPalPayerID = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.PayerID;
                payer.FirstName = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.PayerName.FirstName;
                payer.LastName = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.PayerName.LastName;
                payer.Address1 = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.Street1;
                payer.Address2 = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.Street2;
                payer.City = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.CityName;
                payer.StateOrRegion = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.StateOrProvince;
                payer.Zip = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.PostalCode;
                payer.PayPalToken = response.GetExpressCheckoutDetailsResponseDetails.Token;
                payer.Country = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.CountryName;
            } else {
                payer.PayPalPayerID = errors;
            }
            return payer;
        }
        //This is TOTAL HACK
        //PayPal should be smarter than this.
        //have to round the digits to 2 decimal places
        //otherwise you get an invalid total error
        decimal RoundIt(decimal dPrice,int roundTo) {
            return Math.Round(dPrice, roundTo);
        }
        public Commerce.Common.Transaction DoExpressCheckout(Commerce.Common.Order order, bool AuthOnly) {
            
            //validate that the token is applied to the BillingAddress
            //same with PayerID
            if(String.IsNullOrEmpty(order.BillingAddress.PayPalPayerID))
                throw new Exception("No payer ID set for the BillingAddress of the order");

             if(String.IsNullOrEmpty(order.BillingAddress.PayPalToken))
                throw new Exception("No Token set for the BillingAddress of the order");
           
            PayPalSvc.DoExpressCheckoutPaymentReq checkoutRequest = new DoExpressCheckoutPaymentReq();
            DoExpressCheckoutPaymentRequestType checkoutReqType = new DoExpressCheckoutPaymentRequestType();
            DoExpressCheckoutPaymentRequestDetailsType checkoutDetails = new DoExpressCheckoutPaymentRequestDetailsType();
            PaymentDetailsType paymentDetails = new PaymentDetailsType();

            if (!AuthOnly) {
                checkoutDetails.PaymentAction = PaymentActionCodeType.Sale;
            } else {
                checkoutDetails.PaymentAction = PaymentActionCodeType.Authorization;

            }
            int roundTo = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalDigits;
            checkoutDetails.Token = order.BillingAddress.PayPalToken;
            checkoutDetails.PayerID = order.BillingAddress.PayPalPayerID;
            checkoutReqType.Version = "1.0";
            decimal dTotal = order.OrderTotal;

            paymentDetails.OrderTotal = GetBasicAmount(RoundIt(dTotal,roundTo));
            paymentDetails.ShippingTotal = this.GetBasicAmount(RoundIt(order.ShippingAmount,roundTo));
            paymentDetails.TaxTotal = this.GetBasicAmount(RoundIt(order.TaxAmount,roundTo));
            paymentDetails.Custom = order.OrderNumber;
            paymentDetails.ItemTotal = GetBasicAmount(RoundIt(order.CalculateSubTotal(), roundTo));
            //paymentDetails.OrderDescription = orderDescription;
            
            
            //This tells PayPal that the CSK is making the call. Please leave this
            //as it helps us keep going :):) (not monetarily, just with some love from PayPal).
            paymentDetails.ButtonSource = "CSK 2.1.0";
            //load up the payment items
            PaymentDetailsItemType item;

            int itemCount = order.Items.Count;

            PaymentDetailsItemType[] items = new PaymentDetailsItemType[itemCount];
            
            for (int i = 0; i < itemCount; i++) {
                item = new PaymentDetailsItemType();
                item.Name = order.Items[i].ProductName;
                item.Number = order.Items[i].Sku;
                item.Quantity = order.Items[i].Quantity.ToString();
                item.Amount = GetBasicAmount(RoundIt(order.Items[i].PricePaid, roundTo));
                items[i] = item;
            }
            paymentDetails.PaymentDetailsItem = items;
            checkoutRequest.DoExpressCheckoutPaymentRequest = checkoutReqType;
            checkoutRequest.DoExpressCheckoutPaymentRequest.DoExpressCheckoutPaymentRequestDetails = checkoutDetails;
            checkoutRequest.DoExpressCheckoutPaymentRequest.DoExpressCheckoutPaymentRequestDetails.PaymentDetails = paymentDetails;
            PayPalSvc.DoExpressCheckoutPaymentResponseType response=service2.DoExpressCheckoutPayment(checkoutRequest);
            
            string errors = this.CheckErrors(response);
            string sOut = "";
            Commerce.Common.Transaction trans = new Commerce.Common.Transaction();
            if (errors == string.Empty) {
                trans.GatewayResponse = response.Ack.ToString();
                trans.AuthorizationCode = response.DoExpressCheckoutPaymentResponseDetails.PaymentInfo.TransactionID;
                
            } else {
                trans.GatewayResponse = errors;
            }

            //return out the transactionID
            return trans;


        }


        static object StringToEnum(Type t, string Value)
        {
            object oOut = null;
            foreach (System.Reflection.FieldInfo fi in t.GetFields())
                if (fi.Name == Value)
                    oOut = fi.GetValue(null);    // We use null because
            return oOut;
        }
        public Commerce.Common.Transaction DoDirectCheckout(Commerce.Common.Order order, bool AuthOnly)
        {
            
            PayPalSvc.DoDirectPaymentReq req = new DoDirectPaymentReq();
            req.DoDirectPaymentRequest = new DoDirectPaymentRequestType();
            req.DoDirectPaymentRequest.Version = "1.0";

            DoDirectPaymentRequestDetailsType details=new DoDirectPaymentRequestDetailsType();
            details.CreditCard = new CreditCardDetailsType();
            details.CreditCard.CardOwner = new PayerInfoType();
            details.CreditCard.CardOwner.Address = new AddressType();
            details.CreditCard.CardOwner.PayerName = new PersonNameType();
            details.PaymentDetails = new PaymentDetailsType();

            CountryCodeType payerCountry = CountryCodeType.US;
            if (order.BillingAddress.Country != "US")
            {
                try
                {
                    payerCountry = (CountryCodeType)StringToEnum(typeof(CountryCodeType), order.BillingAddress.Country);
                }
                catch
                {
                }
            }

            details.CreditCard.CardOwner.Address.Country = payerCountry;
            details.CreditCard.CardOwner.PayerCountry = payerCountry;
            
            details.CreditCard.CardOwner.Address.CountrySpecified = true;
            details.CreditCard.CardOwner.Address.Street1 = order.BillingAddress.Address1;
            details.CreditCard.CardOwner.Address.Street2 = order.BillingAddress.Address2;
            details.CreditCard.CardOwner.Address.CityName = order.BillingAddress.City;
            details.CreditCard.CardOwner.Address.StateOrProvince = order.BillingAddress.StateOrRegion;
            details.CreditCard.CardOwner.Address.PostalCode = order.BillingAddress.Zip;

            details.CreditCard.CardOwner.PayerName.FirstName = order.BillingAddress.FirstName;
            details.CreditCard.CardOwner.PayerName.LastName = order.BillingAddress.LastName;


            //the basics
            int roundTo=System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalDigits;
            decimal dTotal = Math.Round(order.CalculateSubTotal(), roundTo) + Math.Round(order.TaxAmount, roundTo) + Math.Round(order.ShippingAmount, roundTo);
            
            details.PaymentDetails.OrderTotal = GetBasicAmount(dTotal);
            details.PaymentDetails.ShippingTotal = this.GetBasicAmount(Math.Round(order.ShippingAmount, roundTo));
            details.PaymentDetails.TaxTotal = this.GetBasicAmount(Math.Round(order.TaxAmount, roundTo));
            details.PaymentDetails.Custom = order.OrderNumber;
            details.PaymentDetails.ItemTotal = GetBasicAmount(Math.Round(order.CalculateSubTotal(), roundTo));
            details.PaymentDetails.ButtonSource = "CSK 2.1.1";
           
           

            //credit card
            details.CreditCard.CreditCardNumber = order.CreditCardNumber;
            CreditCardTypeType ccType = CreditCardTypeType.Visa;
            switch(order.CreditCardType){
                case Commerce.Common.CreditCardType.MasterCard:
                    ccType = CreditCardTypeType.MasterCard;
                    break;
                case Commerce.Common.CreditCardType.Amex:
                    ccType = CreditCardTypeType.Amex;
                    break;
            }

            details.CreditCard.CreditCardType = ccType;
            details.CreditCard.ExpMonth = Convert.ToInt16(order.CreditCardExpireMonth);
            details.CreditCard.ExpYear = Convert.ToInt16(order.CreditCardExpireYear);
            details.CreditCard.CVV2 = order.CreditCardSecurityNumber;

            //set the IP - required
            details.IPAddress = order.UserIP;

            //set the req var to details
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails = details;

            //sale type
            if (AuthOnly) {
                details.PaymentAction = PaymentActionCodeType.Authorization;
            } else {
                details.PaymentAction = PaymentActionCodeType.Sale;
            }

            //send the request
            DoDirectPaymentResponseType response = service2.DoDirectPayment(req);
            
            string errors = this.CheckErrors(response);
            Commerce.Common.Transaction trans = new Commerce.Common.Transaction();
            trans.OrderID = order.OrderID;
            
            string sOut = "";
            if (errors == string.Empty) {
                trans.GatewayResponse = response.Ack.ToString();
                trans.AuthorizationCode = response.TransactionID;
                trans.CVV2Code = response.CVV2Code;

            } else {
                trans.GatewayResponse = errors;
                throw new Exception(errors);
            }
            return trans;
        }


        #endregion

	    #region Helper Functions	
        
        string GetAmountValue(BasicAmountType amount) {
            
            //coerce it to a decimal
            decimal dAmount = decimal.Parse(amount.ToString());
            
            string sOut = "";
            try {
                sOut = dAmount.ToString("c");
            } catch {
                sOut = "--";
            }
            return sOut;
        }

        BasicAmountType GetBasicAmount(decimal amount) {
            BasicAmountType bAmount = new BasicAmountType();
            bAmount.Value = amount.ToString();
            
            //this is lame....
            //why you have to specify a currency for each amount
            //is beyond me... oh well...
            //says alot for duck-typing...
            //if you have a better way to do this, it's about 2 am here
            //and I'll send you $10
            bAmount.currencyID = ppCurrencyType;
            return bAmount;
        }            
    
        string CheckErrors(AbstractResponseType abstractResponse) {
		    bool errorsExist = false;
		    string errorList="";
		    // First, check the Obvious.  Make sure Ack is not Success
		    if (!abstractResponse.Ack.Equals(AckCodeType.Success)) {
			    errorsExist = true;
		    }
		    // Check to make sure there is nothing in the Errors Collection
		    if (abstractResponse.Errors!=null) {
			    if (abstractResponse.Errors.Length > 0) {
				    errorsExist = true;
				    // Do something with the errors
                    errorList = "ERROR: ";
                    for (int i = 0; i < abstractResponse.Errors.Length; i++) {
					    // Access each error abstractResponse.Errors[i] and do something
					    errorList+=abstractResponse.Errors[i].LongMessage+ " ("+ abstractResponse.Errors[i].ErrorCode+")"+Environment.NewLine;
				    }
			    }
		    }
		return errorList;
	    }
		
        public class TransactionSearchParam{
			public DateTime EndDate=DateTime.UtcNow;
			public string TransactionID="";
			public string Amount="";
			public string Currency="";
			public string ItemNumber="";
			public string PayerEmail="";
			public string LastName="";
			public string FirstName="";
			public string Receiver="";
			public string ReceiptID="";
			public string PaymentStatus="";
			public string PaymentType="";
           
		}

    		

    }
	    #endregion
	

}