Advertisement
jmawebtech

Payflow Pro Recurring Payment

Mar 11th, 2014
2,979
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 35.72 KB | None | 0 0
  1.     public class PayFlowProPaymentProcessor : BasePlugin, IPaymentMethod
  2.     {
  3.  
  4.         #region PayFlowPro 101
  5.  
  6.         ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  7.         // PayFlowPro 101
  8.         ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  9.         // A sale transaction requires the following objects to be set:
  10.         //      a) UserInfo Object: Info about the merchant making the transaction.
  11.         //      b) PFProConnectionData Object: The URL of the PayPal transaction server and the location of the local certificate.
  12.         //      c) Currency Object: The amount of money and currency type for this transaction.
  13.         //      d) BillTo Object: Customer's billing information.
  14.         //      e) CreditCard Object: Includes name of cardholder, cardnumber, expiration date, and card security code
  15.         //
  16.         //
  17.         // Of course, to make things confusing, some of these objects are used as parameters to other objects in an unintuitive way.
  18.         //
  19.         // To help you understand the relationships between thess objects, here's a basic diagram using the class names. (Not instance names.)
  20.         //
  21.         // SaleTransaction ---(Has A)---
  22.         //                              |---UserInfo
  23.         //                              |
  24.         //                              |---PFProConnectionData
  25.         //                              |
  26.         //                              |---Invoice---(Has A)-------
  27.         //                                                          |---Currency
  28.         //                                                          |
  29.         //                                                          |---BillTo
  30.         //                                                          |
  31.         //                                                          |---ShipTo*
  32.         //                              |---CardTender---(Has A)----
  33.         //                                                          |---CreditCard
  34.         //
  35.         // *ShipTo, which is a member of Invoice contains the shipping address. It is not required, but I have placed it in diagram
  36.         // and the code below.
  37.         //
  38.         ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  39.  
  40.         #endregion
  41.  
  42.  
  43.         #region Fields
  44.  
  45.         private readonly PayFlowProPaymentSettings _payFlowProPaymentSettings;
  46.         private readonly ISettingService _settingService;
  47.         private readonly ICurrencyService _currencyService;
  48.         private readonly CurrencySettings _currencySettings;
  49.         private readonly IWebHelper _webHelper;
  50.         private readonly StoreInformationSettings _storeInformationSettings;
  51.         private readonly ICustomerService _customerService;
  52.  
  53.         private const int PFP_SUCCESS = 0;
  54.         private const string US_DOLLARS = "USD";
  55.         private const string TRANSACTION_TYPE_SALE = "S";
  56.         private const string TRANSACTION_TYPE_DELAYED_CAPTURE = "D";
  57.  
  58.         #endregion
  59.  
  60.         #region Ctor
  61.  
  62.         public PayFlowProPaymentProcessor(PayFlowProPaymentSettings payFlowProPaymentSettings,
  63.             ISettingService settingService, ICurrencyService currencyService,
  64.             CurrencySettings currencySettings, IWebHelper webHelper,
  65.             StoreInformationSettings storeInformationSettings, ICustomerService customerService)
  66.         {
  67.             _payFlowProPaymentSettings = payFlowProPaymentSettings;
  68.             _settingService = settingService;
  69.             _currencyService = currencyService;
  70.             _currencySettings = currencySettings;
  71.             _webHelper = webHelper;
  72.             _storeInformationSettings = storeInformationSettings;
  73.             _customerService = customerService;
  74.         }
  75.  
  76.         #endregion
  77.  
  78.         #region Utilities
  79.  
  80.         /// <summary>
  81.         /// Gets PayFlowPro URL
  82.         /// </summary>
  83.         /// <returns></returns>
  84.         private string GetPayFlowProUrl()
  85.         {
  86.             return _payFlowProPaymentSettings.UseSandbox ? "pilot-payflowpro.paypal.com" : "payflowpro.paypal.com";
  87.         }
  88.  
  89.         protected string GetApiVersion()
  90.         {
  91.             return "4.3.1.0";
  92.         }
  93.  
  94.         #endregion
  95.  
  96.         #region Methods
  97.  
  98.         /// <summary>
  99.         /// Process a payment
  100.         /// </summary>
  101.         /// <param name="processPaymentRequest">Payment info required for an order processing</param>
  102.         /// <returns>Process payment result</returns>
  103.         public ProcessPaymentResult ProcessPayment(ProcessPaymentRequest processPaymentRequest)
  104.         {
  105.             /////////////////////////////////////////////////
  106.             //  UserInfo Section
  107.             /////////////////////////////////////////////////
  108.  
  109.             _payFlowProPaymentSettings.Unlock();
  110.             UserInfo userInfo = new UserInfo(_payFlowProPaymentSettings.User, _payFlowProPaymentSettings.Vendor,
  111.                 _payFlowProPaymentSettings.Partner, _payFlowProPaymentSettings.Password);
  112.             _payFlowProPaymentSettings.Lock();
  113.  
  114.             /////////////////////////////////////////////////
  115.             //  PFProConnectionData Section
  116.             /////////////////////////////////////////////////
  117.  
  118.             PayflowConnectionData connectionData = new PayflowConnectionData(GetPayFlowProUrl());
  119.  
  120.             /////////////////////////////////////////////////
  121.             //  Invoice Section
  122.             /////////////////////////////////////////////////
  123.  
  124.             // Refer to diagram above - to construct an Invoice object, we need to
  125.             // create a Currency and a BillTo object to pass to the Invoice ctor.
  126.  
  127.             PayPal.Payments.DataObjects.Currency currency = new PayPal.Payments.DataObjects.Currency(processPaymentRequest.OrderTotal, PayFlowProPaymentProcessor.US_DOLLARS);
  128.             currency.NoOfDecimalDigits = 2;
  129.             currency.Round = true;
  130.  
  131.             // Set the billing address information
  132.             BillTo billTo = new BillTo();
  133.             var customer = _customerService.GetCustomerById(processPaymentRequest.CustomerId);
  134.             billTo.Street = customer.BillingAddress.Address1;
  135.             billTo.Zip = customer.BillingAddress.ZipPostalCode;
  136.  
  137.             // Create a new Invoice data object and set the amount of sale
  138.             // and billing address information
  139.             Invoice invoice = new Invoice();
  140.             invoice.Amt = currency;
  141.             invoice.BillTo = billTo;
  142.  
  143.             if (customer.ShippingAddress != null)
  144.             {
  145.                 ShipTo shipTo = new ShipTo();
  146.                 Core.Domain.Common.Address shipAddr = customer.ShippingAddress;
  147.                 shipTo.ShipToFirstName = shipAddr.FirstName;
  148.                 shipTo.ShipToLastName = shipAddr.LastName;
  149.                 shipTo.ShipToStreet = shipAddr.Address1;
  150.                 shipTo.ShipToStreet2 = shipAddr.Address2;
  151.                 shipTo.ShipToCity = shipAddr.City;
  152.                 shipTo.ShipToState = shipAddr.StateProvince.Abbreviation;
  153.                 shipTo.ShipToZip = shipAddr.ZipPostalCode;
  154.                 invoice.ShipTo = shipTo;
  155.             }
  156.  
  157.             /////////////////////////////////////////////////
  158.             //  CardTender Section
  159.             /////////////////////////////////////////////////
  160.  
  161.             // Refer to diagram above - to construct an CardTender object, we need
  162.             // to create a CreditCard object to pass to the CardTender ctor.
  163.             // Note: Expiration date must be in MMYY format.
  164.             string expDate = string.Format("{0:00}{1}", processPaymentRequest.CreditCardExpireMonth, processPaymentRequest.CreditCardExpireYear.ToString().Substring(2));
  165.             CreditCard creditCard = new CreditCard(processPaymentRequest.CreditCardNumber, expDate);
  166.             creditCard.Name = processPaymentRequest.CreditCardName;
  167.             creditCard.Cvv2 = processPaymentRequest.CreditCardCvv2;
  168.  
  169.             CardTender cardTender = new CardTender(creditCard);
  170.  
  171.             /////////////////////////////////////////////////
  172.             //  SaleTransaction Section
  173.             /////////////////////////////////////////////////
  174.  
  175.             SaleTransaction saleXAction = new SaleTransaction(userInfo, connectionData, invoice, cardTender, PayflowUtility.RequestId);
  176.             saleXAction.Verbosity = "LOW";
  177.             //saleXAction.TrxType = "
  178.  
  179.             /////////////////////////////////////////////////
  180.             //  Let's do what we came here to do - Submit It!
  181.             /////////////////////////////////////////////////
  182.  
  183.             Response submitResponse = saleXAction.SubmitTransaction();
  184.             if (submitResponse == null)
  185.             {
  186.                 // If the Response instance is null, we have some strange problem that will prevent us from
  187.                 // continuing. We will have to abort processing.
  188.                 throw new Exception("Unknown error while processing sale transaction. Transaction aborted.");
  189.             }
  190.  
  191.             TransactionResponse transactionResponse = submitResponse.TransactionResponse;
  192.             if (transactionResponse == null)
  193.             {
  194.                 // If the TransactionResponse instance is null, we will have to abort processing.
  195.                 throw new Exception("Unknown error while processing sale transaction. Transaction aborted.");
  196.             }
  197.  
  198.             ProcessPaymentResult result = new ProcessPaymentResult();
  199.             if (transactionResponse.Result == PayFlowProPaymentProcessor.PFP_SUCCESS)
  200.             {
  201.                 result.CaptureTransactionId = transactionResponse.Pnref;
  202.                 result.CaptureTransactionResult = transactionResponse.RespMsg;
  203.                 result.NewPaymentStatus = PaymentStatus.Paid;
  204.                
  205.             }
  206.             else
  207.             {
  208.                 result.CaptureTransactionResult = transactionResponse.RespMsg;
  209.                 result.AddError(transactionResponse.RespMsg);
  210.             }
  211.  
  212.             return result;
  213.         }
  214.  
  215.         /// <summary>
  216.         /// Post process payment (used by payment gateways that require redirecting to a third-party URL)
  217.         /// </summary>
  218.         /// <param name="postProcessPaymentRequest">Payment info required for an order processing</param>
  219.         public void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
  220.         {
  221.             // Not required for PayFlowPro
  222.         }
  223.  
  224.         /// <summary>
  225.         /// Gets additional handling fee
  226.         /// </summary>
  227.         /// <returns>Additional handling fee</returns>
  228.         public decimal GetAdditionalHandlingFee()
  229.         {
  230.             return 0.00m;
  231.         }
  232.  
  233.         /// <summary>
  234.         /// Captures payment
  235.         /// </summary>
  236.         /// <param name="capturePaymentRequest">Capture payment request</param>
  237.         /// <returns>Capture payment result</returns>
  238.         public CapturePaymentResult Capture(CapturePaymentRequest capturePaymentRequest)
  239.         {
  240.             var result = new CapturePaymentResult();
  241.             result.AddError("Capture method not supported");
  242.             return result;
  243.         }
  244.  
  245.         /// <summary>
  246.         /// Refunds a payment
  247.         /// </summary>
  248.         /// <param name="refundPaymentRequest">Request</param>
  249.         /// <returns>Result</returns>
  250.         public RefundPaymentResult Refund(RefundPaymentRequest refundPaymentRequest)
  251.         {
  252.             var result = new RefundPaymentResult();
  253.            
  254.            
  255.              /////////////////////////////////////////////////
  256.             //  UserInfo Section
  257.             /////////////////////////////////////////////////
  258.  
  259.             _payFlowProPaymentSettings.Unlock();
  260.             UserInfo userInfo = new UserInfo(_payFlowProPaymentSettings.User, _payFlowProPaymentSettings.Vendor,
  261.                 _payFlowProPaymentSettings.Partner, _payFlowProPaymentSettings.Password);
  262.             _payFlowProPaymentSettings.Lock();
  263.  
  264.             /////////////////////////////////////////////////
  265.             //  PFProConnectionData Section
  266.             /////////////////////////////////////////////////
  267.  
  268.             PayflowConnectionData connectionData = new PayflowConnectionData(GetPayFlowProUrl());
  269.  
  270.             /////////////////////////////////////////////////
  271.             //  Invoice Section
  272.             /////////////////////////////////////////////////
  273.  
  274.             // Refer to diagram above - to construct an Invoice object, we need to
  275.             // create a Currency and a BillTo object to pass to the Invoice ctor.
  276.  
  277.             PayPal.Payments.DataObjects.Currency currency = new PayPal.Payments.DataObjects.Currency(refundPaymentRequest.AmountToRefund, PayFlowProPaymentProcessor.US_DOLLARS);
  278.             currency.NoOfDecimalDigits = 2;
  279.             currency.Round = true;
  280.  
  281.             // Set the billing address information
  282.             BillTo billTo = new BillTo();
  283.             var customer = refundPaymentRequest.Order.Customer;
  284.             billTo.Street = customer.BillingAddress.Address1;
  285.             billTo.Zip = customer.BillingAddress.ZipPostalCode;
  286.  
  287.             // Create a new Invoice data object and set the amount of sale
  288.             // and billing address information
  289.             Invoice invoice = new Invoice();
  290.             invoice.Amt = currency;
  291.             invoice.BillTo = billTo;
  292.  
  293.             if (customer.ShippingAddress != null)
  294.             {
  295.                 ShipTo shipTo = new ShipTo();
  296.                 Core.Domain.Common.Address shipAddr = customer.ShippingAddress;
  297.                 shipTo.ShipToFirstName = shipAddr.FirstName;
  298.                 shipTo.ShipToLastName = shipAddr.LastName;
  299.                 shipTo.ShipToStreet = shipAddr.Address1;
  300.                 shipTo.ShipToStreet2 = shipAddr.Address2;
  301.                 shipTo.ShipToCity = shipAddr.City;
  302.                 shipTo.ShipToState = shipAddr.StateProvince.Abbreviation;
  303.                 shipTo.ShipToZip = shipAddr.ZipPostalCode;
  304.                 invoice.ShipTo = shipTo;
  305.             }
  306.  
  307.            
  308.             ///////////////////////////////////////////////////////////////////
  309.  
  310.             // Create a new Credit Transaction.
  311.             // Following is an example of a independent credit type of transaction.
  312.             CreditTransaction Trans = new CreditTransaction(refundPaymentRequest.Order.CaptureTransactionId, userInfo, PayflowUtility.RequestId);
  313.  
  314.             // Submit the Transaction
  315.             Response Resp = Trans.SubmitTransaction();
  316.  
  317.             // Display the transaction response parameters.
  318.             if (Resp != null)
  319.             {
  320.                 // Get the Transaction Response parameters.
  321.                 TransactionResponse TrxnResponse =  Resp.TransactionResponse;
  322.  
  323.                 if (TrxnResponse != null)
  324.                 {
  325.                     Console.WriteLine("RESULT = " + TrxnResponse.Result);
  326.                     Console.WriteLine("PNREF = " + TrxnResponse.Pnref);
  327.                     Console.WriteLine("RESPMSG = " + TrxnResponse.RespMsg);
  328.                     Console.WriteLine("AUTHCODE = " + TrxnResponse.AuthCode);
  329.                     Console.WriteLine("AVSADDR = " + TrxnResponse.AVSAddr);
  330.                     Console.WriteLine("AVSZIP = " + TrxnResponse.AVSZip);
  331.                     Console.WriteLine("IAVS = " + TrxnResponse.IAVS);
  332.                     Console.WriteLine("CVV2MATCH = " + TrxnResponse.CVV2Match);
  333.                     // If value is true, then the Request ID has not been changed and the original response
  334.                     // of the original transction is returned.
  335.                     Console.WriteLine("DUPLICATE = " + TrxnResponse.Duplicate);
  336.                 }
  337.  
  338.                 // Get the Fraud Response parameters.
  339.                 FraudResponse FraudResp =  Resp.FraudResponse;
  340.                 // Display Fraud Response parameter
  341.                 if (FraudResp != null)
  342.                 {
  343.                     Console.WriteLine("PREFPSMSG = " + FraudResp.PreFpsMsg);
  344.                     Console.WriteLine("POSTFPSMSG = " + FraudResp.PostFpsMsg);
  345.                 }
  346.  
  347.                 // Display the response.
  348.                 Console.WriteLine(Environment.NewLine + PayflowUtility.GetStatus(Resp));   
  349.            
  350.                 // Get the Transaction Context and check for any contained SDK specific errors (optional code).
  351.                 PayPal.Payments.Common.Context TransCtx = Resp.TransactionContext;
  352.                 if (TransCtx != null && TransCtx.getErrorCount() > 0)
  353.                 {
  354.                     Console.WriteLine(Environment.NewLine + "Transaction Errors = " + TransCtx.ToString());
  355.                 }
  356.             }
  357.  
  358.             return result;
  359.         }
  360.  
  361.         /// <summary>
  362.         /// Voids a payment
  363.         /// </summary>
  364.         /// <param name="voidPaymentRequest">Request</param>
  365.         /// <returns>Result</returns>
  366.         public VoidPaymentResult Void(VoidPaymentRequest voidPaymentRequest)
  367.         {
  368.             var result = new VoidPaymentResult();
  369.  
  370.             _payFlowProPaymentSettings.Unlock();
  371.             UserInfo userInfo = new UserInfo(_payFlowProPaymentSettings.User, _payFlowProPaymentSettings.Vendor,
  372.                 _payFlowProPaymentSettings.Partner, _payFlowProPaymentSettings.Password);
  373.             _payFlowProPaymentSettings.Lock();
  374.  
  375.             /////////////////////////////////////////////////
  376.             //  PFProConnectionData Section
  377.             /////////////////////////////////////////////////
  378.  
  379.             PayflowConnectionData connectionData = new PayflowConnectionData(GetPayFlowProUrl());
  380.  
  381.  
  382.             ///////////////////////////////////////////////////////////////////
  383.  
  384.             // Create a new Void Transaction.
  385.             // The ORIGID is the PNREF no. for a previous transaction.
  386.             VoidTransaction Trans = new VoidTransaction(voidPaymentRequest.Order.CaptureTransactionId,
  387.                 userInfo, connectionData, PayflowUtility.RequestId);
  388.  
  389.             // Submit the Transaction
  390.             Response Resp = Trans.SubmitTransaction();
  391.  
  392.             if (Resp == null)
  393.             {
  394.                 // If the Response instance is null, we have some strange problem that will prevent us from
  395.                 // continuing. We will have to abort processing.
  396.                 throw new Exception("Unknown error while processing void transaction. Transaction aborted.");
  397.             }
  398.  
  399.             TransactionResponse transactionResponse = Resp.TransactionResponse;
  400.             if (transactionResponse == null)
  401.             {
  402.                 // If the TransactionResponse instance is null, we will have to abort processing.
  403.                 throw new Exception("Unknown error while processing void transaction. Transaction aborted.");
  404.             }
  405.  
  406.             if (transactionResponse.Result == PayFlowProPaymentProcessor.PFP_SUCCESS)
  407.             {
  408.                 result.NewPaymentStatus = Core.Domain.Payments.PaymentStatus.Voided;
  409.             }
  410.             else
  411.             {
  412.                 result.AddError(transactionResponse.RespMsg);
  413.             }
  414.  
  415.             return result;
  416.         }
  417.  
  418.         /// <summary>
  419.         /// Process recurring payment
  420.         /// </summary>
  421.         /// <param name="processPaymentRequest">Payment info required for an order processing</param>
  422.         /// <returns>Process payment result</returns>
  423.         public ProcessPaymentResult ProcessRecurringPayment(ProcessPaymentRequest processPaymentRequest)
  424.         {
  425.             var result = new ProcessPaymentResult();
  426.             /////////////////////////////////////////////////
  427.             //  UserInfo Section
  428.             /////////////////////////////////////////////////
  429.  
  430.             _payFlowProPaymentSettings.Unlock();
  431.             UserInfo userInfo = new UserInfo(_payFlowProPaymentSettings.User, _payFlowProPaymentSettings.Vendor,
  432.                 _payFlowProPaymentSettings.Partner, _payFlowProPaymentSettings.Password);
  433.             _payFlowProPaymentSettings.Lock();
  434.  
  435.             /////////////////////////////////////////////////
  436.             //  PFProConnectionData Section
  437.             /////////////////////////////////////////////////
  438.  
  439.             PayflowConnectionData connectionData = new PayflowConnectionData(GetPayFlowProUrl());
  440.  
  441.  
  442.             PayPal.Payments.DataObjects.Currency currency = new PayPal.Payments.DataObjects.Currency(processPaymentRequest.OrderTotal, PayFlowProPaymentProcessor.US_DOLLARS);
  443.             currency.NoOfDecimalDigits = 2;
  444.             currency.Round = true;
  445.      
  446.             // Set the billing address information
  447.             BillTo billTo = new BillTo();
  448.             var customer = _customerService.GetCustomerById(processPaymentRequest.CustomerId);
  449.             billTo.Street = customer.BillingAddress.Address1;
  450.             billTo.Zip = customer.BillingAddress.ZipPostalCode;
  451.             billTo.Email = customer.Email;
  452.             // Create a new Invoice data object and set the amount of sale
  453.             // and billing address information
  454.             Invoice invoice = new Invoice();
  455.             invoice.Amt = currency;
  456.             invoice.BillTo = billTo;
  457.             invoice.InvNum = processPaymentRequest.OrderGuid.ToString();
  458.             if (customer.ShippingAddress != null)
  459.             {
  460.                 ShipTo shipTo = new ShipTo();
  461.                 Core.Domain.Common.Address shipAddr = customer.ShippingAddress;
  462.                 shipTo.ShipToFirstName = shipAddr.FirstName;
  463.                 shipTo.ShipToLastName = shipAddr.LastName;
  464.                 shipTo.ShipToStreet = shipAddr.Address1;
  465.                 shipTo.ShipToStreet2 = shipAddr.Address2;
  466.                 shipTo.ShipToCity = shipAddr.City;
  467.                 shipTo.ShipToState = shipAddr.StateProvince.Abbreviation;
  468.                 shipTo.ShipToZip = shipAddr.ZipPostalCode;
  469.                 invoice.ShipTo = shipTo;
  470.             }
  471.  
  472.  
  473.  
  474.             /////////////////////////////////////////////////
  475.             //  CardTender Section
  476.             /////////////////////////////////////////////////
  477.  
  478.             // Refer to diagram above - to construct an CardTender object, we need
  479.             // to create a CreditCard object to pass to the CardTender ctor.
  480.             // Note: Expiration date must be in MMYY format.
  481.             string expDate = string.Format("{0:00}{1}", processPaymentRequest.CreditCardExpireMonth, processPaymentRequest.CreditCardExpireYear.ToString().Substring(2));
  482.             CreditCard creditCard = new CreditCard(processPaymentRequest.CreditCardNumber, expDate);
  483.             creditCard.Name = processPaymentRequest.CreditCardName;
  484.             creditCard.Cvv2 = processPaymentRequest.CreditCardCvv2;
  485.  
  486.             CardTender cardTender = new CardTender(creditCard);
  487.  
  488.             RecurringInfo RecurInfo = new RecurringInfo();
  489.             // The date that the first payment will be processed.
  490.             // This will be of the format mmddyyyy.
  491.             RecurInfo.Start = DateTime.UtcNow.AddDays(1).ToString("MMddyyyy");
  492.             RecurInfo.ProfileName = "PayPal";
  493.             RecurInfo.OptionalTrxAmt = new PayPal.Payments.DataObjects.Currency(199, "USD");
  494.             // Specifies how often the payment occurs. All PAYPERIOD values must use
  495.             // capital letters and can be any of WEEK / BIWK / SMMO / FRWK / MONT /
  496.             // QTER / SMYR / YEAR
  497.  
  498.             switch (processPaymentRequest.RecurringCyclePeriod)
  499.             {
  500.                 case RecurringProductCyclePeriod.Days:
  501.                     RecurInfo.PayPeriod = "DAY";
  502.                     break;
  503.                 case RecurringProductCyclePeriod.Weeks:
  504.                     RecurInfo.PayPeriod = "WEEK";
  505.                     break;
  506.                 case RecurringProductCyclePeriod.Months:
  507.                     RecurInfo.PayPeriod = "MONTH";
  508.                     break;
  509.                 case RecurringProductCyclePeriod.Years:
  510.                     RecurInfo.PayPeriod = "YEAR";
  511.                     break;
  512.                 default:
  513.                     throw new NopException("Not supported cycle period");
  514.             }
  515.  
  516.  
  517.             //RecurInfo.PayPeriod = "WEEK";
  518.             ///////////////////////////////////////////////////////////////////
  519.  
  520.             // Create a new Recurring Transaction.
  521.             RecurringTransaction Trans = new RecurringTransaction("A", RecurInfo,
  522.                 userInfo, connectionData, invoice, cardTender, PayflowUtility.RequestId);
  523.  
  524.             // Submit the Transaction
  525.             Response Resp = Trans.SubmitTransaction();
  526.  
  527.             //if (Resp != null)
  528.             //{
  529.             //    // Get the Transaction Response parameters.
  530.             //    TransactionResponse TrxnResponse = Resp.TransactionResponse;
  531.  
  532.             //    if (TrxnResponse != null)
  533.             //    {
  534.             //        Console.WriteLine("RESULT = " + TrxnResponse.Result);
  535.             //        Console.WriteLine("RESPMSG = " + TrxnResponse.RespMsg);
  536.             //    }
  537.  
  538.             //    // Get the Recurring Response parameters.
  539.             //    RecurringResponse RecurResponse = Resp.RecurringResponse;
  540.             //    if (RecurResponse != null)
  541.             //    {
  542.             //        Console.WriteLine("RPREF = " + RecurResponse.RPRef);
  543.             //        Console.WriteLine("PROFILEID = " + RecurResponse.ProfileId);
  544.             //    }
  545.             //}
  546.  
  547.             if (Resp == null)
  548.             {
  549.                 // If the Response instance is null, we have some strange problem that will prevent us from
  550.                 // continuing. We will have to abort processing.
  551.                 throw new Exception("Unknown error while processing sale transaction. Transaction aborted.");
  552.             }
  553.  
  554.             TransactionResponse transactionResponse = Resp.TransactionResponse;
  555.             if (transactionResponse == null)
  556.             {
  557.                 // If the TransactionResponse instance is null, we will have to abort processing.
  558.                 throw new Exception("Unknown error while processing sale transaction. Transaction aborted.");
  559.             }
  560.  
  561.             if (transactionResponse.Result == PayFlowProPaymentProcessor.PFP_SUCCESS)
  562.             {
  563.                 // Get the Recurring Response parameters.
  564.                 RecurringResponse RecurResponse = Resp.RecurringResponse;
  565.                 if (RecurResponse != null)
  566.                 {
  567.                     result.CaptureTransactionId = RecurResponse.RPRef;
  568.                     result.SubscriptionTransactionId = RecurResponse.ProfileId;
  569.                     result.NewPaymentStatus = PaymentStatus.Paid;
  570.                 }
  571.             }
  572.             else
  573.             {
  574.                 result.CaptureTransactionResult = transactionResponse.RespMsg;
  575.                 result.AddError(transactionResponse.RespMsg);
  576.             }
  577.  
  578.             // Display the response.
  579.             //result.AddError(Environment.NewLine + PayflowUtility.GetStatus(Resp));
  580.  
  581.             // Get the Transaction Context and check for any contained SDK specific errors (optional code).
  582.             PayPal.Payments.Common.Context TransCtx = Resp.TransactionContext;
  583.             if (TransCtx != null && TransCtx.getErrorCount() > 0)
  584.             {
  585.                 result.AddError(Environment.NewLine + "Transaction Errors = " + TransCtx.ToString());
  586.             }
  587.  
  588.             return result;
  589.  
  590.         }
  591.  
  592.         /// <summary>
  593.         /// Cancels a recurring payment
  594.         /// </summary>
  595.         /// <param name="cancelPaymentRequest">Request</param>
  596.         /// <returns>Result</returns>
  597.         public CancelRecurringPaymentResult CancelRecurringPayment(CancelRecurringPaymentRequest cancelPaymentRequest)
  598.         {
  599.             var result = new CancelRecurringPaymentResult();
  600.  
  601.             _payFlowProPaymentSettings.Unlock();
  602.             UserInfo userInfo = new UserInfo(_payFlowProPaymentSettings.User, _payFlowProPaymentSettings.Vendor,
  603.                 _payFlowProPaymentSettings.Partner, _payFlowProPaymentSettings.Password);
  604.             _payFlowProPaymentSettings.Lock();
  605.  
  606.             PayflowConnectionData connectionData = new PayflowConnectionData(GetPayFlowProUrl());
  607.  
  608.             RecurringInfo RecurInfo = new RecurringInfo();
  609.             //RecurInfo.OrigProfileId = "<PROFILE_ID>";  // RT0000001350
  610.             RecurInfo.OrigProfileId = cancelPaymentRequest.Order.SubscriptionTransactionId;
  611.             // Create a new Recurring Cancel Transaction.
  612.             RecurringCancelTransaction Trans = new RecurringCancelTransaction(
  613.                 userInfo, connectionData, RecurInfo, PayflowUtility.RequestId);
  614.  
  615.             // Submit the Transaction
  616.             Response Resp = Trans.SubmitTransaction();
  617.             // Display the transaction response parameters.
  618.  
  619.             // Display the transaction response parameters.
  620.             if (Resp != null)
  621.             {
  622.                 RecurringResponse RecurResponse = Resp.RecurringResponse;
  623.  
  624.                 if (RecurResponse.TrxResult != "0")
  625.                 {
  626.                     result.AddError(RecurResponse.TrxResult.ToString());
  627.                     result.AddError(RecurResponse.TrxRespMsg);
  628.                 }
  629.  
  630.  
  631.                 //if (TrxnResponse != null)
  632.                 //{
  633.                 //    Console.WriteLine("RESULT = " + TrxnResponse.Result);
  634.                 //    Console.WriteLine("RESPMSG = " + TrxnResponse.RespMsg);
  635.                 //}
  636.  
  637.                 // Get the Recurring Response parameters.
  638.                 //if (RecurResponse != null)
  639.                 //{
  640.                 //    Console.WriteLine("RPREF = " + RecurResponse.RPRef);
  641.                 //    Console.WriteLine("PROFILEID = " + RecurResponse.ProfileId);
  642.                 //}
  643.  
  644.                 // Display the response.
  645.                 //Console.WriteLine(Environment.NewLine + PayflowUtility.GetStatus(Resp));
  646.  
  647.  
  648.                 // Get the Transaction Context and check for any contained SDK specific errors (optional code).
  649.                 PayPal.Payments.Common.Context TransCtx = Resp.TransactionContext;
  650.                 //if (TransCtx != null && TransCtx.getErrorCount() > 0)
  651.                 //{
  652.                 //    Console.WriteLine(Environment.NewLine + "Transaction Errors = " + TransCtx.ToString());
  653.                 //}
  654.             }
  655.  
  656.            
  657.             return result;
  658.         }
  659.  
  660.         /// <summary>
  661.         /// Gets a value indicating whether customers can complete a payment after order is placed but not completed (for redirection payment methods)
  662.         /// </summary>
  663.         /// <param name="order">Order</param>
  664.         /// <returns>Result</returns>
  665.         public bool CanRePostProcessPayment(Order order)
  666.         {
  667.             if (order == null)
  668.                 throw new ArgumentNullException("order");
  669.  
  670.             //it's not a redirection payment method. So we always return false
  671.             return false;
  672.         }
  673.  
  674.         /// <summary>
  675.         /// Gets a route for provider configuration
  676.         /// </summary>
  677.         /// <param name="actionName">Action name</param>
  678.         /// <param name="controllerName">Controller name</param>
  679.         /// <param name="routeValues">Route values</param>
  680.         public void GetConfigurationRoute(out string actionName, out string controllerName, out RouteValueDictionary routeValues)
  681.         {
  682.             actionName = "Configure";
  683.             controllerName = "PaymentPayFlowPro";
  684.             routeValues = new RouteValueDictionary() { { "Namespaces", "Nop.Plugin.Payments.PayFlowPro.Controllers" }, { "area", null } };
  685.         }
  686.  
  687.         /// <summary>
  688.         /// Gets a route for payment info
  689.         /// </summary>
  690.         /// <param name="actionName">Action name</param>
  691.         /// <param name="controllerName">Controller name</param>
  692.         /// <param name="routeValues">Route values</param>
  693.         public void GetPaymentInfoRoute(out string actionName, out string controllerName, out RouteValueDictionary routeValues)
  694.         {
  695.             actionName = "PaymentInfo";
  696.             controllerName = "PaymentPayFlowPro";
  697.             routeValues = new RouteValueDictionary() { { "Namespaces", "Nop.Plugin.Payments.PayFlowPro.Controllers" }, { "area", null } };
  698.         }
  699.  
  700.         public Type GetControllerType()
  701.         {
  702.             return typeof(PaymentPayFlowProController);
  703.         }
  704.  
  705.         public override void Install()
  706.         {
  707.             var settings = new PayFlowProPaymentSettings()
  708.             {
  709.                 UseSandbox = true,
  710.                 User = "User Name",
  711.                 Vendor = "Vendor Id",
  712.                 Partner = "Partner",
  713.                 Password = "Password"
  714.             };
  715.  
  716.             settings.Lock();
  717.             _settingService.SaveSetting(settings);
  718.  
  719.             base.Install();
  720.         }
  721.  
  722.         /// <summary>
  723.         /// Verifies IPN
  724.         /// </summary>
  725.         /// <param name="formString">Form string</param>
  726.         /// <param name="values">Values</param>
  727.         /// <returns>Result</returns>
  728.         public bool VerifyIPN(string formString, out Dictionary<string, string> values)
  729.         {
  730.             //var req = (HttpWebRequest)WebRequest.Create(GetPaypalUrl());
  731.             //req.Method = "POST";
  732.             //req.ContentType = "application/x-www-form-urlencoded";
  733.  
  734.             //string formContent = string.Format("{0}&cmd=_notify-validate", formString);
  735.             //req.ContentLength = formContent.Length;
  736.  
  737.             //using (var sw = new StreamWriter(req.GetRequestStream(), Encoding.ASCII))
  738.             //{
  739.             //    sw.Write(formContent);
  740.             //}
  741.  
  742.             //string response = null;
  743.             //using (var sr = new StreamReader(req.GetResponse().GetResponseStream()))
  744.             //{
  745.             //    response = HttpUtility.UrlDecode(sr.ReadToEnd());
  746.             //}
  747.             //bool success = response.Trim().Equals("VERIFIED", StringComparison.OrdinalIgnoreCase);
  748.  
  749.             bool success = true;
  750.             values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  751.             foreach (string l in formString.Split('&'))
  752.             {
  753.                 string line = l.Trim();
  754.                 int equalPox = line.IndexOf('=');
  755.                 if (equalPox >= 0)
  756.                     values.Add(line.Substring(0, equalPox), line.Substring(equalPox + 1));
  757.             }
  758.  
  759.             return success;
  760.         }
  761.  
  762.         /// <summary>
  763.         /// Gets Paypal URL
  764.         /// </summary>
  765.         /// <returns></returns>
  766.         private string GetPaypalUrl()
  767.         {
  768.  
  769.             return _payFlowProPaymentSettings.UseSandbox ? "https://www.sandbox.paypal.com/us/cgi-bin/webscr" :
  770.                 "https://www.paypal.com/us/cgi-bin/webscr";
  771.         }
  772.  
  773.  
  774.  
  775.         #endregion
  776.  
  777.         #region Properies
  778.  
  779.         /// <summary>
  780.         /// Gets a value indicating whether capture is supported
  781.         /// </summary>
  782.         public bool SupportCapture
  783.         {
  784.             get
  785.             {
  786.                 return false;
  787.             }
  788.         }
  789.  
  790.         /// <summary>
  791.         /// Gets a value indicating whether partial refund is supported
  792.         /// </summary>
  793.         public bool SupportPartiallyRefund
  794.         {
  795.             get
  796.             {
  797.                 return false;
  798.             }
  799.         }
  800.  
  801.         /// <summary>
  802.         /// Gets a value indicating whether refund is supported
  803.         /// </summary>
  804.         public bool SupportRefund
  805.         {
  806.             get
  807.             {
  808.                 return true;
  809.             }
  810.         }
  811.  
  812.         /// <summary>
  813.         /// Gets a value indicating whether void is supported
  814.         /// </summary>
  815.         public bool SupportVoid
  816.         {
  817.             get
  818.             {
  819.                 return true;
  820.             }
  821.         }
  822.  
  823.         /// <summary>
  824.         /// Gets a recurring payment type of payment method
  825.         /// </summary>
  826.         public RecurringPaymentType RecurringPaymentType
  827.         {
  828.             get
  829.             {
  830.                 return RecurringPaymentType.Automatic;
  831.             }
  832.         }
  833.  
  834.         /// <summary>
  835.         /// Gets a payment method type
  836.         /// </summary>
  837.         public PaymentMethodType PaymentMethodType
  838.         {
  839.             get
  840.             {
  841.                 return PaymentMethodType.Standard;
  842.             }
  843.         }
  844.  
  845.         #endregion
  846.  
  847.  
  848.         public decimal GetAdditionalHandlingFee(System.Collections.Generic.IList<ShoppingCartItem> cart)
  849.         {
  850.             return 0;
  851.             //throw new NotImplementedException();
  852.         }
  853.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement