public ActionResult PayOrder(int orderId)
        {                        
            var model = new PaymentFormModel();

            try
            {
                model.OrderId = orderId;

                var order = _orderService.GetOrderById(orderId);

                if (order == null || order.Deleted)
                    return View("~/Plugins/Payments.PayPalAdvanced/Views/PaymentPayPalAdvanced/PaymentForm.cshtml", model);

                if (_workContext.CurrentCustomer.Id != order.CustomerId)
                    return new HttpUnauthorizedResult();

                if (order.OrderStatus == OrderStatus.Cancelled || order.PaymentStatus != PaymentStatus.Pending)
                    return RedirectToRoute("OrderDetails", new { orderId = order.Id });

                                                                
                // Create a new Invoice data object with the Amount, Billing Address etc. details.
                Invoice inv = new Invoice();
                decimal orderTotal = 0.0M;

                try
                {                    
                    // Set Amount.
                    orderTotal = Math.Round(order.OrderTotal, 2);
                    PayPal.Payments.DataObjects.Currency amt = new PayPal.Payments.DataObjects.Currency(orderTotal);
                    inv.Amt = amt;                    
                }
                catch (Exception ex)
                {
                    throw new Exception("Unable to create invoice amount: " + ex.Message);
                }

                inv.PoNum = order.Id.ToString();
                inv.InvNum = order.Id.ToString();

                try
                {
                    // Check license
                    bool isLicensed = this._licenseService.IsLicensed(HttpContext.Request.Url.Host);
                    if (!isLicensed && orderTotal > 5.00M)
                    {
                        return ShowLicenseInfo();
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception("Unable to verify plugin's license: " + ex.Message);
                }

                // Set the Billing Address details.
                BillTo billTo = new BillTo();

                // optional fields
                try
                {
                    billTo.FirstName = order.Customer.BillingAddress.FirstName;
                }
                catch { }
                try
                {
                    billTo.LastName = order.Customer.BillingAddress.LastName;
                }
                catch { }
                try
                {
                    billTo.Street = order.Customer.BillingAddress.Address1;
                }
                catch { }
                try
                {
                    billTo.City = order.Customer.BillingAddress.City;
                }
                catch { }
                try
                {
                    billTo.State = order.Customer.BillingAddress.StateProvince.Abbreviation;
                }
                catch { }
                try
                {
                    billTo.Zip = order.Customer.BillingAddress.ZipPostalCode;
                }
                catch { }
                try
                {
                    billTo.BillToCountry = order.Customer.BillingAddress.Country.NumericIsoCode.ToString();
                }
                catch { }

                inv.BillTo = billTo;

                // Set the Shipping Address details.
                //if (order.Customer.ShippingAddress != null)
                //{
                //    if (order.Customer.ShippingAddress.StateProvince != null && order.Customer.ShippingAddress.Country != null)
                //    {
                //        ShipTo shipTo = new ShipTo();
                //        shipTo.ShipToFirstName = order.Customer.ShippingAddress.FirstName;
                //        shipTo.ShipToLastName = order.Customer.ShippingAddress.LastName;
                //        shipTo.ShipToStreet = order.Customer.ShippingAddress.Address1;
                //        //shipTo.ShipToStreet2 = order.Customer.ShippingAddress.Address2;
                //        shipTo.ShipToCity = order.Customer.ShippingAddress.City;
                //        shipTo.ShipToState = order.Customer.ShippingAddress.StateProvince.Abbreviation;
                //        shipTo.ShipToZip = order.Customer.ShippingAddress.ZipPostalCode;
                //        shipTo.ShipToCountry = order.Customer.ShippingAddress.Country.NumericIsoCode.ToString();
                //        inv.ShipTo = shipTo;
                //    }
                //}


                // Create the Payflow Data Objects.
                // Create the User data object with the required user details.
                UserInfo payflowUser = null;
                try
                {
                    payflowUser = _payPalHelper.GetUserInfo();
                }
                catch (Exception ex)
                {
                    throw new Exception("Unable to create Payflow User object, check the configuration: " + ex.Message);
                }

                // Create the Payflow Connection data object with the required connection details.                        
                PayflowConnectionData payflowConn = null;
                try
                {
                    payflowConn = new PayflowConnectionData(_payPalHelper.GetPayflowProHost());
                }
                catch (Exception ex)
                {
                    throw new Exception("Unable to create Payflow connection, check the web.config: " + ex.Message);
                }

                string payflowRequestId = PayflowUtility.RequestId;
                Response resp;

                if (_payPalAdvancedPaymentSettings.TransactMode == TransactMode.Authorize)
                {
                    // Create a new Auth Transaction.
                    AuthorizationTransaction trans = null;
                    try
                    {
                        trans = new AuthorizationTransaction(payflowUser, payflowConn, inv, null, payflowRequestId);

                        trans.AddToExtendData(new ExtendData("CREATESECURETOKEN", "Y"));
                        trans.AddToExtendData(new ExtendData("SECURETOKENID", payflowRequestId));
                        if (_payPalAdvancedPaymentSettings.EnableMobileOptimizedLayout && this.IsMobileDevice())
                            trans.AddToExtendData(new ExtendData("TEMPLATE", "MOBILE"));

                        // Submit the Transaction
                        resp = trans.SubmitTransaction();
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("Error processing AuthorizationTransaction: " + ex.Message);
                    }
                }
                else
                {
                    // Create a new Sale Transaction.
                    SaleTransaction trans = null;
                    try
                    {
                        trans = new SaleTransaction(payflowUser, payflowConn, inv, null, payflowRequestId);

                        trans.AddToExtendData(new ExtendData("CREATESECURETOKEN", "Y"));
                        trans.AddToExtendData(new ExtendData("SECURETOKENID", payflowRequestId));
                        if (_payPalAdvancedPaymentSettings.EnableMobileOptimizedLayout && this.IsMobileDevice())
                            trans.AddToExtendData(new ExtendData("TEMPLATE", "MOBILE"));

                        // Submit the Transaction
                        resp = trans.SubmitTransaction();
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("Error processing SaleTransaction: " + ex.Message);
                    }
                }

                string paypalSecureToken = string.Empty;
                string paypalContent = string.Empty;

                // Process the Payflow response.
                if (resp != null)
                {
                    // Get the Transaction Response parameters.
                    TransactionResponse trxResp = resp.TransactionResponse;
                    if (trxResp != null)
                    {
                        if (trxResp.Result == 0)
                        {
                            paypalSecureToken = (from ExtendData edEntry in resp.ExtendDataList
                                                 where edEntry.ParamName == "SECURETOKEN"
                                                 select edEntry.ParamValue).FirstOrDefault();

                            model.PayflowSecureToken = paypalSecureToken.Trim();
                            model.PayflowSecureTokenId = payflowRequestId.Trim();
                            model.PayflowMode = _payPalAdvancedPaymentSettings.UseSandbox ? "TEST" : "LIVE";
                            model.PayflowUrl = _payPalHelper.GetPayflowLinkHost();
                            model.Success = true;
                        }
                        else
                        {
                            // Show error msg
                            model.ErrorMsg = string.Format("Error: {0} - {1}", trxResp.Result, trxResp.RespMsg != null ? trxResp.RespMsg : "");

                            // Log resp error
                            order.OrderNotes.Add(new OrderNote
                            {
                                Note = "Failed fetching PayPal Secure Token: " + model.ErrorMsg,
                                DisplayToCustomer = false,
                                CreatedOnUtc = DateTime.UtcNow
                            });

                            if (_orderService != null)
                            {
                                _orderService.UpdateOrder(order);
                            }

                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error(ex.Message, ex);
                model.ErrorMsg = "An error has occurred, please check System Log for more information.";
            }                       
            
            return View("~/Plugins/Payments.PayPalAdvanced/Views/PaymentPayPalAdvanced/PaymentForm.cshtml", model);
        }
        /// <summary>
        /// Refunds a payment
        /// </summary>
        /// <param name="refundPaymentRequest">Request</param>
        /// <returns>Result</returns>
        public RefundPaymentResult Refund(RefundPaymentRequest refundPaymentRequest)
        {
            var result = new RefundPaymentResult();
            
            // Check license
            bool isLicensed = this._licenseService.IsLicensed(HttpContext.Current.Request.Url.Host);
            if (!isLicensed && refundPaymentRequest.Order.OrderTotal > 5.00M)
            {
                result.AddError("The trial license can be used to submit order of $5.00 or less. Please purchase a full license at our website.");
                return result;
            }

            string transactionId = refundPaymentRequest.Order.CaptureTransactionId;

            // Create the Payflow Data Objects.
            // Create the User data object with the required user details.
            UserInfo payflowUser = _payPalHelper.GetUserInfo();

            // Create the Payflow Connection data object with the required connection details.                        
            PayflowConnectionData payflowConn = new PayflowConnectionData(_payPalHelper.GetPayflowProHost());

            // Create a new Invoice data object with the Amount, Billing Address etc. details.
            Invoice invoice = new Invoice();

            // Set Amount.
            PayPal.Payments.DataObjects.Currency refundAmount = new PayPal.Payments.DataObjects.Currency(refundPaymentRequest.AmountToRefund);
            invoice.Amt = refundAmount;
            invoice.PoNum = refundPaymentRequest.Order.Id.ToString();
            invoice.InvNum = refundPaymentRequest.Order.Id.ToString();

            CreditTransaction trans = new CreditTransaction(transactionId, payflowUser, payflowConn, invoice, PayflowUtility.RequestId);
            Response resp = trans.SubmitTransaction();
                                                
            // Process the Payflow response.
            if (resp != null)
            {
                // Get the Transaction Response parameters.
                TransactionResponse trxResp = resp.TransactionResponse;
                if (trxResp != null)
                {
                    if (trxResp.Result == 0)
                    {
                        if (refundPaymentRequest.IsPartialRefund)
                            result.NewPaymentStatus = PaymentStatus.PartiallyRefunded;
                        else
                            result.NewPaymentStatus = PaymentStatus.Refunded;
                    }
                    else
                    {
                        result.AddError(string.Format("Refund RESULT: {0}-{1}", trxResp.Result, trxResp.RespMsg));
                    }
                }
            }

            return result;
        }