public override void AddOrderTokens(IList <Token> tokens, Nop.Core.Domain.Orders.Order order, int languageId, int vendorId = 0)
        {
            var miscPlugins = _pluginFinder.GetPlugins <MyOrderServicePlugin>(storeId: order.StoreId).ToList();

            if (miscPlugins.Count > 0)
            {
                //string orderID = BuildOrderID(order, languageId);
                NopResourceDisplayNameAttribute orderNumberKeyGBS = new NopResourceDisplayNameAttribute("Account.CustomerOrders.OrderNumber");

                tokens.Add(new Token("Order.GBSOrderID", order.DeserializeCustomValues()[orderNumberKeyGBS.DisplayName].ToString(), true));

                base.AddOrderTokens(tokens, order, languageId);
            }
        }
Example #2
0
        /// <summary>
        /// Process a payment
        /// </summary>
        /// <param name="processPaymentRequest">Payment info required for an order processing</param>
        /// <returns>Process payment result</returns>
        public ProcessPaymentResult ProcessPayment(ProcessPaymentRequest processPaymentRequest)
        {
            var result   = new ProcessPaymentResult();
            var customer = _customerService.GetCustomerById(processPaymentRequest.CustomerId);

            try
            {
                PrepareGBS();

                //var creditCard = new creditCardType
                //{
                //    cardNumber = processPaymentRequest.CreditCardNumber,
                //    expirationDate =
                //        processPaymentRequest.CreditCardExpireMonth.ToString("D2") + processPaymentRequest.CreditCardExpireYear,
                //    cardCode = processPaymentRequest.CreditCardCvv2
                //};

                ////standard api call to retrieve response
                //var paymentType = new paymentType { Item = creditCard };

                //transactionTypeEnum transactionType;

                //switch (_authorizeNetPaymentSettings.TransactMode)
                //{
                //    case TransactMode.Authorize:
                //        transactionType = transactionTypeEnum.authOnlyTransaction;
                //        break;
                //    case TransactMode.AuthorizeAndCapture:
                //        transactionType = transactionTypeEnum.authCaptureTransaction;
                //        break;
                //    default:
                //        throw new NopException("Not supported transaction mode");
                //}

                //var billTo = new customerAddressType
                //{
                //    firstName = customer.BillingAddress.FirstName,
                //    lastName = customer.BillingAddress.LastName,
                //    email = customer.BillingAddress.Email,
                //    address = customer.BillingAddress.Address1,
                //    city = customer.BillingAddress.City,
                //    zip = customer.BillingAddress.ZipPostalCode
                //};

                //if (!string.IsNullOrEmpty(customer.BillingAddress.Company))
                //    billTo.company = customer.BillingAddress.Company;

                //if (customer.BillingAddress.StateProvince != null)
                //    billTo.state = customer.BillingAddress.StateProvince.Abbreviation;

                //if (customer.BillingAddress.Country != null)
                //    billTo.country = customer.BillingAddress.Country.TwoLetterIsoCode;

                //var transactionRequest = new transactionRequestType
                //{
                //    transactionType = transactionType.ToString(),
                //    amount = Math.Round(processPaymentRequest.OrderTotal, 2),
                //    payment = paymentType,
                //    currencyCode = _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId).CurrencyCode,
                //    billTo = billTo,
                //    customerIP = _webHelper.GetCurrentIpAddress(),
                //    order = new orderType
                //    {
                //        //x_invoice_num is 20 chars maximum. hece we also pass x_description
                //        invoiceNumber = processPaymentRequest.OrderGuid.ToString().Substring(0, 20),
                //        description = string.Format("Full order #{0}", processPaymentRequest.OrderGuid)
                //    }
                //};

                //var request = new createTransactionRequest { transactionRequest = transactionRequest };

                //// instantiate the contoller that will call the service
                //var controller = new createTransactionController(request);
                //controller.Execute();

                //// get the response from the service (errors contained if any)



                //NOP WEB SERVICE CALL START HERE --------------------------------------------------------------------------------------------------------------------
                //create nop payment object from user data
                PaymentTransactionModel payment = new PaymentTransactionModel();
                payment.firstName     = customer.BillingAddress.FirstName;
                payment.lastName      = customer.BillingAddress.LastName;
                payment.streetAddress = customer.BillingAddress.Address1;
                payment.billingCity   = customer.BillingAddress.City;
                payment.postalCode    = customer.BillingAddress.ZipPostalCode;
                payment.countryCode   = customer.BillingAddress.Country.Name;
                if (payment.countryCode == "United States")
                {
                    payment.countryCode = "US";
                }
                else
                {
                    payment.countryCode = "US";
                }
                payment.cardExpireMonth = processPaymentRequest.CreditCardExpireMonth.ToString().Length == 1 ? "0" + processPaymentRequest.CreditCardExpireMonth.ToString() : processPaymentRequest.CreditCardExpireMonth.ToString(); //prepend 0 for single digit months
                payment.cardExpireYear  = processPaymentRequest.CreditCardExpireYear.ToString();
                payment.cardNum         = processPaymentRequest.CreditCardNumber;
                payment.orderAmount     = processPaymentRequest.OrderTotal.ToString();
                payment.pcDestZip       = (customer.ShippingAddress != null && customer.ShippingAddress.ZipPostalCode != null) ? customer.ShippingAddress.ZipPostalCode : String.Empty;
                Object value = null;
                NopResourceDisplayNameAttribute orderNumberKeyGBS = new NopResourceDisplayNameAttribute(("Account.CustomerOrders.OrderNumber"));
                if (processPaymentRequest.CustomValues.TryGetValue(orderNumberKeyGBS.DisplayName, out value))
                {
                    payment.orderID   = processPaymentRequest.CustomValues[orderNumberKeyGBS.DisplayName].ToString();
                    payment.pcOrderID = processPaymentRequest.CustomValues[orderNumberKeyGBS.DisplayName].ToString();
                }
                else
                {
                    payment.orderID   = "NA";
                    payment.pcOrderID = "NA";
                }
                payment.state   = customer.BillingAddress.StateProvince.Abbreviation;
                payment.tax     = _orderTotalCalculationService.GetTaxTotal((IList <ShoppingCartItem>)customer.ShoppingCartItems, false).ToString();
                payment.sandBox = _gbsPaymentSettings.UseSandbox;


                if (Convert.ToBoolean(processPaymentRequest.CustomValues["SavedProfile"]) == true)
                {
                    payment.createProfile = false;
                    payment.useProfile    = true;
                    payment.profileID     = processPaymentRequest.CustomValues["ProfileID"].ToString();
                }
                else
                {
                    payment.createProfile = true;
                    payment.useProfile    = false;
                    payment.profileID     = "";
                }


                //will need to be able to switch between sand and production version
                string address = _gbsPaymentSettings.GBSPaymentWebServiceAddress;



                GBSPaymentServiceClient gateway = new GBSPaymentServiceClient();

                //calls to GBSPaymentGateway function
                var response = gateway.AuthorizeAndCapture(payment, address, _gbsPaymentSettings.LoginId, _gbsPaymentSettings.Password);


                //use returned GBSTransactionResponse to tell nop what occured in submit
                switch (response.responseCode)
                {
                case GBSTransactionResponse.ResponseCodeType.Approved:
                    result.NewPaymentStatus = PaymentStatus.Authorized;
                    break;

                case GBSTransactionResponse.ResponseCodeType.Declined:
                case GBSTransactionResponse.ResponseCodeType.Error:
                    result.NewPaymentStatus = PaymentStatus.Voided;
                    break;

                default:
                    result.NewPaymentStatus = PaymentStatus.Voided;
                    break;
                }
                //validate
                if (GetErrors(response, result.Errors))
                {
                    return(result);
                }

                if (_gbsPaymentSettings.TransactMode == TransactMode.Authorize)
                {
                    result.AuthorizationTransactionCode = string.Format("{0},{1}", response.transactId, response.authCode);
                }
                //if (_authorizeNetPaymentSettings.TransactMode == TransactMode.AuthorizeAndCapture)
                //    result.CaptureTransactionId = string.Format("{0},{1}", response.transactionResponse.transId, response.transactionResponse.authCode);

                result.AuthorizationTransactionResult = string.Format("Approved ({0}: {1})", response.responseCode, response.authCode);
                //result.AvsResult = response.transactionResponse.avsResultCode;
                //result.NewPaymentStatus = _authorizeNetPaymentSettings.TransactMode == TransactMode.Authorize ? PaymentStatus.Authorized : PaymentStatus.Paid;

                //var congrats = "Congrats the payment was successful, now insert profile id into DB";

                bool storeProfile = Convert.ToBoolean(processPaymentRequest.CustomValues["StoreProfile"]);

                if (payment.createProfile == true && storeProfile == true)
                {
                    string nickName = String.IsNullOrEmpty(processPaymentRequest.CustomValues["NickName"].ToString()) ? "" : processPaymentRequest.CustomValues["NickName"].ToString();
                    nickName = nickName.Replace("'", "''");

                    string last4Digits = response.accountNum.ToString();
                    last4Digits = last4Digits.Substring(last4Digits.Length - 4);

                    DBManager manager = new DBManager();
                    Dictionary <string, string> paramDic = new Dictionary <string, string>();
                    paramDic.Add("@CustomerID", customer.Id.ToString());
                    paramDic.Add("@ProfileID", response.customerRefNum.ToString());
                    paramDic.Add("@NickName", nickName);
                    paramDic.Add("@Last4Digits", last4Digits);
                    paramDic.Add("@CardType", response.cardBrand.ToString());
                    paramDic.Add("@ExpMonth", payment.cardExpireMonth);
                    paramDic.Add("@ExpYear", payment.cardExpireYear);

                    string insert = "INSERT INTO Profiles (CustomerID, ProfileID, NickName, Last4Digits, CardType, ExpMonth, ExpYear) ";
                    insert += "VALUES ('" + customer.Id + "', '" + response.customerRefNum + "', '" + nickName + "', '" + last4Digits + "', '" + response.cardBrand + "', '" + payment.cardExpireMonth + "', '" + payment.cardExpireYear + "')";
                    try
                    {
                        manager.SetParameterizedQueryNoData(insert, paramDic);
                    }
                    catch (Exception ex)
                    {
                        try
                        {
                            _logger.Error("Payment Plugin Error inserting profile on auth : " + ex.Message + ": query = " + insert, ex, null);
                        }
                        catch (Exception ex1) {
                            _logger.Error("Payment Plugin Error inserting profile on auth with additional failure to log the sql statement : " + ex.Message, ex, null);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error("Payment Plugin Error : " + ex.Message, ex, null);
                throw new Exception("Payment Plugin Exception: " + ex.Message, ex);
            }

            return(result);
        }