/// <summary>
 /// Validate the object.
 /// </summary>
 /// <exception cref="Rest.ValidationException">
 /// Thrown if validation fails
 /// </exception>
 public virtual void Validate()
 {
     if (BillTo != null)
     {
         BillTo.Validate();
     }
 }
Пример #2
0
        public virtual void UpdateBillTo(BillTo address)
        {
            if (address == null)
            {
                throw new ArgumentNullException(nameof(address));
            }

            //some validation
            if (address.CountryId == 0)
            {
                address.CountryId = null;
            }
            if (address.StateProvinceId == 0)
            {
                address.StateProvinceId = null;
            }

            _billToRepository.Update(address);

            //cache
            _cacheManager.RemoveByPattern(NopCommonDefaults.AddressesPatternCacheKey);

            //event notification
            _eventPublisher.EntityUpdated(address);
        }
Пример #3
0
    public RequestMessage refundRequest()
    {
        RequestMessage request = new RequestMessage();

        // we will let the client pick up the merchantID
        // from the config file.  In multi-merchant scenarios,
        // you would set a merchantID in each request.

        // this sample requests for refund

        // Credit Card Authorization

        request.ccCreditService     = new CCCreditService();
        request.ccCreditService.run = "true";
        request.ccCreditService.reconciliationID = "7189912a5HVUHCYNR";
        request.merchantReferenceCode            = "your_merchant_reference_code";
        request.ccCreditService.refundReason     = "1";

        BillTo billTo = new BillTo();

        billTo.firstName  = "John";
        billTo.lastName   = "Doe";
        billTo.street1    = "1295 Charleston Road";
        billTo.city       = "Mountain View";
        billTo.state      = "CA";
        billTo.postalCode = "94043";
        billTo.country    = "US";
        billTo.email      = "*****@*****.**";
        billTo.ipAddress  = "10.7.111.111";
        request.billTo    = billTo;

        Card card = new Card();

        card.accountNumber   = "4111111111111111";
        card.expirationMonth = "12";
        card.expirationYear  = "2020";
        request.card         = card;


        PurchaseTotals purchaseTotals = new PurchaseTotals();

        purchaseTotals.currency = "USD";
        request.purchaseTotals  = purchaseTotals;

        // there are two items in this sample
        request.item = new Item[2];

        Item item = new Item();

        item.id         = "0";
        item.unitPrice  = "12.34";
        request.item[0] = item;

        item            = new Item();
        item.id         = "1";
        item.unitPrice  = "56.78";
        request.item[1] = item;

        return(request);
    }
Пример #4
0
        private Invoice GetInvoice(PaymentInfo paymentInfo)
        {
            var ppBillingInfo = new BillTo();

            ppBillingInfo.FirstName = paymentInfo.FirstName;
            ppBillingInfo.LastName  = paymentInfo.LastName;
            ppBillingInfo.Email     = paymentInfo.Email;
            ppBillingInfo.PhoneNum  = paymentInfo.Phone;
            ppBillingInfo.Street    = paymentInfo.Street;
            ppBillingInfo.State     = paymentInfo.State;
            ppBillingInfo.Zip       = paymentInfo.Zip;

            if (paymentInfo is CreditCardPaymentInfo)
            {
                var cc = paymentInfo as CreditCardPaymentInfo;
                ppBillingInfo.Street = cc.BillingStreet;
                ppBillingInfo.City   = cc.BillingCity;
                ppBillingInfo.State  = cc.BillingState;
                ppBillingInfo.Zip    = cc.BillingZip;
            }

            var ppAmount = new Currency(paymentInfo.Amount);

            var ppInvoice = new Invoice();

            ppInvoice.Amt    = ppAmount;
            ppInvoice.BillTo = ppBillingInfo;

            return(ppInvoice);
        }
Пример #5
0
        private Invoice GetInvoice(PaymentInfo paymentInfo)
        {
            var ppBillingInfo = new BillTo();

            ppBillingInfo.FirstName     = paymentInfo.FirstName;
            ppBillingInfo.LastName      = paymentInfo.LastName;
            ppBillingInfo.Email         = paymentInfo.Email;
            ppBillingInfo.PhoneNum      = paymentInfo.Phone;
            ppBillingInfo.Street        = paymentInfo.Street1;
            ppBillingInfo.BillToStreet2 = paymentInfo.Street2;
            ppBillingInfo.State         = paymentInfo.State;
            ppBillingInfo.Zip           = paymentInfo.PostalCode;
            ppBillingInfo.BillToCountry = paymentInfo.Country;

            if (paymentInfo is CreditCardPaymentInfo)
            {
                var cc = paymentInfo as CreditCardPaymentInfo;
                ppBillingInfo.Street        = cc.BillingStreet1;
                ppBillingInfo.BillToStreet2 = cc.BillingStreet2;
                ppBillingInfo.City          = cc.BillingCity;
                ppBillingInfo.State         = cc.BillingState;
                ppBillingInfo.Zip           = cc.BillingPostalCode;
                ppBillingInfo.BillToCountry = cc.BillingCountry;
            }

            var ppAmount = new Currency(paymentInfo.Amount);

            var ppInvoice = new Invoice();

            ppInvoice.Amt    = ppAmount;
            ppInvoice.BillTo = ppBillingInfo;
            ppInvoice.Desc   = paymentInfo.Description;
            return(ppInvoice);
        }
Пример #6
0
 public static void AddShopperFields(ref BillTo billTo, Shopper shopper)
 {
     billTo.firstName  = shopper.firstName;
     billTo.lastName   = shopper.lastName;
     billTo.street1    = shopper.street1;
     billTo.city       = shopper.city;
     billTo.state      = shopper.state;
     billTo.country    = shopper.country;
     billTo.postalCode = shopper.postalCode;
     billTo.email      = shopper.email;
 }
        private static BillTo CreateBillTo(CreditCardPaymentRequest req)
        {
            // Create the BillTo object.
            BillTo Bill = new BillTo();

            Bill.BillToStreet  = req.BillingInformation.BillingAddress;
            Bill.BillToStreet2 = req.BillingInformation.BillingAddressLine2;
            Bill.BillToCity    = req.BillingInformation.BillingCity;
            Bill.BillToState   = req.BillingInformation.BillingState;
            Bill.BillToZip     = req.BillingInformation.BilingZipcode;
            return(Bill);
        }
Пример #8
0
        /// <summary>
        /// Gets the bill to from a transaction.
        /// </summary>
        /// <param name="transaction">The transaction.</param>
        /// <returns></returns>
        private BillTo GetBillTo(FinancialTransaction transaction)
        {
            BillTo billingInfo = new BillTo();

            billingInfo.customerID = transaction.AuthorizedPersonAlias.Id.ToString();
            billingInfo.firstName  = transaction.AuthorizedPersonAlias.Person.FirstName.Left(50);        // up to 50 chars
            billingInfo.lastName   = transaction.AuthorizedPersonAlias.Person.LastName.Left(50);         // up to 60 chars
            billingInfo.email      = transaction.AuthorizedPersonAlias.Person.Email.Left(255);           // up to 255 chars
            billingInfo.ipAddress  = Dns.GetHostEntry(Dns.GetHostName())
                                     .AddressList.FirstOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork).ToString();

            return(billingInfo);
        }
Пример #9
0
        private Invoice GetInvoice(PaymentInfo paymentInfo)
        {
            var ppBillingInfo = new BillTo();

            // If giving from a Business, FirstName will be blank
            // The Gateway might require a FirstName, so just put '-' if no FirstName was provided
            if (paymentInfo.FirstName.IsNullOrWhiteSpace())
            {
                paymentInfo.FirstName = "-";
            }

            ppBillingInfo.FirstName     = paymentInfo.FirstName;
            ppBillingInfo.LastName      = paymentInfo.LastName;
            ppBillingInfo.Email         = paymentInfo.Email;
            ppBillingInfo.PhoneNum      = paymentInfo.Phone;
            ppBillingInfo.Street        = paymentInfo.Street1;
            ppBillingInfo.BillToStreet2 = paymentInfo.Street2;
            ppBillingInfo.City          = paymentInfo.City;
            ppBillingInfo.State         = paymentInfo.State;
            ppBillingInfo.Zip           = paymentInfo.PostalCode;
            ppBillingInfo.BillToCountry = paymentInfo.Country;

            if (paymentInfo is CreditCardPaymentInfo)
            {
                var cc = paymentInfo as CreditCardPaymentInfo;
                ppBillingInfo.FirstName     = cc.NameOnCard;
                ppBillingInfo.LastName      = cc.LastNameOnCard;
                ppBillingInfo.Street        = cc.BillingStreet1;
                ppBillingInfo.BillToStreet2 = cc.BillingStreet2;
                ppBillingInfo.City          = cc.BillingCity;
                ppBillingInfo.State         = cc.BillingState;
                ppBillingInfo.Zip           = cc.BillingPostalCode;
                ppBillingInfo.BillToCountry = cc.BillingCountry;
            }

            var ppAmount = new Currency(paymentInfo.Amount);

            var ppInvoice = new Invoice();

            ppInvoice.Amt      = ppAmount;
            ppInvoice.BillTo   = ppBillingInfo;
            ppInvoice.Comment1 = paymentInfo.Comment1;
            ppInvoice.Comment2 = paymentInfo.Comment2;
            ppInvoice.Desc     = paymentInfo.Description;
            return(ppInvoice);
        }
Пример #10
0
        void ReleaseDesignerOutlets()
        {
            if (Amount != null)
            {
                Amount.Dispose();
                Amount = null;
            }

            if (BillTo != null)
            {
                BillTo.Dispose();
                BillTo = null;
            }

            if (ReferenceNumber != null)
            {
                ReferenceNumber.Dispose();
                ReferenceNumber = null;
            }
        }
Пример #11
0
        private static BillTo CreateBillTo(BillingInformation billingInformation)
        {
            if (billingInformation == null)
            {
                return(null);
            }
            BillTo Bill = new BillTo();

            Bill.BillToStreet    = billingInformation.BillingAddress;
            Bill.BillToStreet2   = billingInformation.BillingAddressLine2;
            Bill.BillToCity      = billingInformation.BillingCity;
            Bill.BillToState     = billingInformation.BillingState;
            Bill.BillToZip       = billingInformation.BilingZipcode;
            Bill.BillToCountry   = billingInformation.Country;
            Bill.BillToFirstName = billingInformation.BillToFirstName;
            Bill.BillToLastName  = billingInformation.BillToLastName;
            Bill.BillToEmail     = billingInformation.BillToEmail;
            Bill.BillToPhone     = billingInformation.BillToPhone;
            return(Bill);
        }
Пример #12
0
        /// <summary>
        /// Gets the billing details from user submitted payment info.
        /// </summary>
        /// <param name="paymentInfo">The payment information.</param>
        /// <returns></returns>
        private BillTo GetBillTo(PaymentInfo paymentInfo)
        {
            BillTo billingInfo = new BillTo();

            billingInfo.firstName   = paymentInfo.FirstName.Left(50);       // up to 50 chars
            billingInfo.lastName    = paymentInfo.LastName.Left(60);        // up to 60 chars
            billingInfo.email       = paymentInfo.Email;                    // up to 255 chars
            billingInfo.phoneNumber = paymentInfo.Phone.Left(15);           // up to 15 chars
            billingInfo.street1     = paymentInfo.Street1.Left(50);         // up to 50 chars
            billingInfo.city        = paymentInfo.City.Left(50);            // up to 50 chars
            billingInfo.state       = paymentInfo.State.Left(2);            // only 2 chars

            var zip = paymentInfo.PostalCode;

            if (!string.IsNullOrWhiteSpace(zip) && zip.Length > 5)
            {
                Regex.Replace(zip, @"^(.{5})(.{4})$", "$1-$2");             // up to 9 chars with a separating -
            }
            billingInfo.postalCode = zip;

            var country = paymentInfo.Country ?? "US";

            billingInfo.country = country.Left(2);                          // only 2 chars

            var ipAddr = Dns.GetHostEntry(Dns.GetHostName()).AddressList
                         .FirstOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork);

            billingInfo.ipAddress = ipAddr.ToString();                      // machine IP address

            if (paymentInfo is CreditCardPaymentInfo)
            {
                var cc = paymentInfo as CreditCardPaymentInfo;
                billingInfo.street1    = cc.BillingStreet1.Left(50);
                billingInfo.city       = cc.BillingCity.Left(50);
                billingInfo.state      = cc.BillingState.Left(2);
                billingInfo.postalCode = cc.BillingPostalCode.Left(10);
            }

            return(billingInfo);
        }
Пример #13
0
    public RequestMessage applePayAuthRequest()
    {
        RequestMessage request = new RequestMessage();

        // we will let the client pick up the merchantID
        // from the config file.  In multi-merchant scenarios,
        // you would set a merchantID in each request.

        // this sample requests auth of apple pay

        // Credit Card Authorization
        request.ccAuthService      = new CCAuthService();
        request.ccAuthService.run  = "true";
        request.ccAuthService.cavv = "ABCDEFabcdefABCDEFabcdef0987654321234567";
        request.ccAuthService.commerceIndicator = "internet";
        request.ccAuthService.xid = "ABCDEFabcdefABCDEFabcdef0987654321234567";

        // add required fields

        request.merchantReferenceCode = "your_merchant_reference_code";

        BillTo billTo = new BillTo();

        billTo.firstName  = "John";
        billTo.lastName   = "Doe";
        billTo.street1    = "1295 Charleston Road";
        billTo.city       = "Mountain View";
        billTo.state      = "CA";
        billTo.postalCode = "94043";
        billTo.country    = "US";
        billTo.email      = "*****@*****.**";
        billTo.ipAddress  = "10.7.111.111";
        request.billTo    = billTo;

        Card card = new Card();

        card.accountNumber   = "4111111111111111";
        card.expirationMonth = "12";
        card.expirationYear  = "2020";
        request.card         = card;

        PurchaseTotals purchaseTotals = new PurchaseTotals();

        purchaseTotals.currency = "USD";
        request.purchaseTotals  = purchaseTotals;

        // there are two items in this sample
        request.item = new Item[2];

        Item item = new Item();

        item.id         = "0";
        item.unitPrice  = "12.34";
        request.item[0] = item;

        item            = new Item();
        item.id         = "1";
        item.unitPrice  = "56.78";
        request.item[1] = item;

        PaymentNetworkToken paymentNetworkToken = new PaymentNetworkToken();

        paymentNetworkToken.transactionType = "1";
        request.paymentNetworkToken         = paymentNetworkToken;
        request.paymentSolution             = "001";
        // add optional fields here per your business needs

        return(request);
    }
        /// <summary>
        /// Process payment
        /// </summary>
        /// <param name="paymentInfo">Payment info required for an order processing</param>
        /// <param name="customer">Customer</param>
        /// <param name="orderGuid">Unique order identifier</param>
        /// <param name="processPaymentResult">Process payment result</param>
        public void ProcessPayment(PaymentInfo paymentInfo, Customer customer, Guid orderGuid, ref ProcessPaymentResult processPaymentResult)
        {
            InitSettings();
            TransactMode transactionMode = GetCurrentTransactionMode();

            //little hack here
            CultureInfo userCulture = Thread.CurrentThread.CurrentCulture;
            NopContext.Current.SetCulture(new CultureInfo("en-US"));
            try
            {
                Invoice invoice = new Invoice();

                BillTo to = new BillTo();
                to.FirstName = paymentInfo.BillingAddress.FirstName;
                to.LastName = paymentInfo.BillingAddress.LastName;
                to.Street = paymentInfo.BillingAddress.Address1;
                to.City = paymentInfo.BillingAddress.City;
                to.Zip = paymentInfo.BillingAddress.ZipPostalCode;
                if (paymentInfo.BillingAddress.StateProvince != null)
                    to.State = paymentInfo.BillingAddress.StateProvince.Abbreviation;
                invoice.BillTo = to;

                if (paymentInfo.ShippingAddress != null)
                {
                    ShipTo to2 = new ShipTo();
                    to2.ShipToFirstName = paymentInfo.ShippingAddress.FirstName;
                    to2.ShipToLastName = paymentInfo.ShippingAddress.LastName;
                    to2.ShipToStreet = paymentInfo.ShippingAddress.Address1;
                    to2.ShipToCity = paymentInfo.ShippingAddress.City;
                    to2.ShipToZip = paymentInfo.ShippingAddress.ZipPostalCode;
                    if (paymentInfo.ShippingAddress.StateProvince != null)
                        to2.ShipToState = paymentInfo.ShippingAddress.StateProvince.Abbreviation;
                    invoice.ShipTo = to2;
                }

                invoice.InvNum = orderGuid.ToString();
                decimal orderTotal = Math.Round(paymentInfo.OrderTotal, 2);
                invoice.Amt = new PayPal.Payments.DataObjects.Currency(orderTotal, IoC.Resolve<ICurrencyService>().PrimaryStoreCurrency.CurrencyCode);

                string creditCardExp = string.Empty;
                if (paymentInfo.CreditCardExpireMonth < 10)
                {
                    creditCardExp = "0" + paymentInfo.CreditCardExpireMonth.ToString();
                }
                else
                {
                    creditCardExp = paymentInfo.CreditCardExpireMonth.ToString();
                }
                creditCardExp = creditCardExp + paymentInfo.CreditCardExpireYear.ToString().Substring(2, 2);
                CreditCard credCard = new CreditCard(paymentInfo.CreditCardNumber, creditCardExp);
                credCard.Cvv2 = paymentInfo.CreditCardCvv2;
                CardTender tender = new CardTender(credCard);
                // <vendor> = your merchant (login id)
                // <user> = <vendor> unless you created a separate <user> for Payflow Pro
                // partner = paypal
                UserInfo userInfo = new UserInfo(user, vendor, partner, password);
                string url = GetPaypalUrl();
                PayflowConnectionData payflowConnectionData = new PayflowConnectionData(url, 443, null, 0, null, null);

                Response response = null;
                if (transactionMode == TransactMode.Authorize)
                {
                    response = new AuthorizationTransaction(userInfo, payflowConnectionData, invoice, tender, PayflowUtility.RequestId).SubmitTransaction();
                }
                else
                {
                    response = new SaleTransaction(userInfo, payflowConnectionData, invoice, tender, PayflowUtility.RequestId).SubmitTransaction();
                }

                if (response.TransactionResponse != null)
                {
                    if (response.TransactionResponse.Result == 0)
                    {
                        processPaymentResult.AuthorizationTransactionId = response.TransactionResponse.Pnref;
                        processPaymentResult.AuthorizationTransactionResult = response.TransactionResponse.RespMsg;

                        if (transactionMode == TransactMode.Authorize)
                        {
                            processPaymentResult.PaymentStatus = PaymentStatusEnum.Authorized;
                        }
                        else
                        {
                            processPaymentResult.PaymentStatus = PaymentStatusEnum.Paid;
                        }
                    }
                    else
                    {
                        processPaymentResult.Error = string.Format("{0} - {1}", response.TransactionResponse.Result, response.TransactionResponse.RespMsg);
                        processPaymentResult.FullError = string.Format("Response Code : {0}. Response Description : {1}", response.TransactionResponse.Result, response.TransactionResponse.RespMsg);
                    }
                }
                else
                {
                    processPaymentResult.Error = "Error during checkout";
                    processPaymentResult.FullError = "Error during checkout";
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                NopContext.Current.SetCulture(userCulture);
            }
        }
        /// <summary>
        /// Prepare custom address attributes
        /// </summary>
        /// <param name="models">List of address attribute models</param>
        /// <param name="address">Address</param>
        public virtual void PrepareCustomAddressAttributes(IList <AddressModel.AddressAttributeModel> models, BillTo address)
        {
            if (models == null)
            {
                throw new ArgumentNullException(nameof(models));
            }

            var attributes = _addressAttributeService.GetAllAddressAttributes();

            foreach (var attribute in attributes)
            {
                var attributeModel = new AddressModel.AddressAttributeModel
                {
                    Id                   = attribute.Id,
                    Name                 = attribute.Name,
                    IsRequired           = attribute.IsRequired,
                    AttributeControlType = attribute.AttributeControlType,
                };

                if (attribute.ShouldHaveValues())
                {
                    //values
                    var attributeValues = _addressAttributeService.GetAddressAttributeValues(attribute.Id);
                    foreach (var attributeValue in attributeValues)
                    {
                        var attributeValueModel = new AddressModel.AddressAttributeValueModel
                        {
                            Id            = attributeValue.Id,
                            Name          = attributeValue.Name,
                            IsPreSelected = attributeValue.IsPreSelected
                        };
                        attributeModel.Values.Add(attributeValueModel);
                    }
                }

                //set already selected attributes
                var selectedAddressAttributes = address?.CustomAttributes;
                switch (attribute.AttributeControlType)
                {
                case AttributeControlType.DropdownList:
                case AttributeControlType.RadioList:
                case AttributeControlType.Checkboxes:
                {
                    if (!string.IsNullOrEmpty(selectedAddressAttributes))
                    {
                        //clear default selection
                        foreach (var item in attributeModel.Values)
                        {
                            item.IsPreSelected = false;
                        }

                        //select new values
                        var selectedValues = _addressAttributeParser.ParseAddressAttributeValues(selectedAddressAttributes);
                        foreach (var attributeValue in selectedValues)
                        {
                            foreach (var item in attributeModel.Values)
                            {
                                if (attributeValue.Id == item.Id)
                                {
                                    item.IsPreSelected = true;
                                }
                            }
                        }
                    }
                }
                break;

                case AttributeControlType.ReadonlyCheckboxes:
                {
                    //do nothing
                    //values are already pre-set
                }
                break;

                case AttributeControlType.TextBox:
                case AttributeControlType.MultilineTextbox:
                {
                    if (!string.IsNullOrEmpty(selectedAddressAttributes))
                    {
                        var enteredText = _addressAttributeParser.ParseValues(selectedAddressAttributes, attribute.Id);
                        if (enteredText.Any())
                        {
                            attributeModel.DefaultValue = enteredText[0];
                        }
                    }
                }
                break;

                case AttributeControlType.ColorSquares:
                case AttributeControlType.ImageSquares:
                case AttributeControlType.Datepicker:
                case AttributeControlType.FileUpload:
                default:
                    //not supported attribute control types
                    break;
                }

                models.Add(attributeModel);
            }
        }
        /// <summary>
        /// Process payment
        /// </summary>
        /// <param name="paymentInfo">Payment info required for an order processing</param>
        /// <param name="customer">Customer</param>
        /// <param name="orderGuid">Unique order identifier</param>
        /// <param name="processPaymentResult">Process payment result</param>
        public void ProcessPayment(PaymentInfo paymentInfo, Customer customer, Guid orderGuid, ref ProcessPaymentResult processPaymentResult)
        {
            InitSettings();
            TransactMode transactionMode = GetCurrentTransactionMode();

            //little hack here
            CultureInfo userCulture = Thread.CurrentThread.CurrentCulture;

            NopContext.Current.SetCulture(new CultureInfo("en-US"));
            try
            {
                Invoice invoice = new Invoice();

                BillTo to = new BillTo();
                to.FirstName = paymentInfo.BillingAddress.FirstName;
                to.LastName  = paymentInfo.BillingAddress.LastName;
                to.Street    = paymentInfo.BillingAddress.Address1;
                to.City      = paymentInfo.BillingAddress.City;
                to.Zip       = paymentInfo.BillingAddress.ZipPostalCode;
                if (paymentInfo.BillingAddress.StateProvince != null)
                {
                    to.State = paymentInfo.BillingAddress.StateProvince.Abbreviation;
                }
                invoice.BillTo = to;

                if (paymentInfo.ShippingAddress != null)
                {
                    ShipTo to2 = new ShipTo();
                    to2.ShipToFirstName = paymentInfo.ShippingAddress.FirstName;
                    to2.ShipToLastName  = paymentInfo.ShippingAddress.LastName;
                    to2.ShipToStreet    = paymentInfo.ShippingAddress.Address1;
                    to2.ShipToCity      = paymentInfo.ShippingAddress.City;
                    to2.ShipToZip       = paymentInfo.ShippingAddress.ZipPostalCode;
                    if (paymentInfo.ShippingAddress.StateProvince != null)
                    {
                        to2.ShipToState = paymentInfo.ShippingAddress.StateProvince.Abbreviation;
                    }
                    invoice.ShipTo = to2;
                }

                invoice.InvNum = orderGuid.ToString();
                decimal orderTotal = Math.Round(paymentInfo.OrderTotal, 2);
                invoice.Amt = new PayPal.Payments.DataObjects.Currency(orderTotal, CurrencyManager.PrimaryStoreCurrency.CurrencyCode);

                string creditCardExp = string.Empty;
                if (paymentInfo.CreditCardExpireMonth < 10)
                {
                    creditCardExp = "0" + paymentInfo.CreditCardExpireMonth.ToString();
                }
                else
                {
                    creditCardExp = paymentInfo.CreditCardExpireMonth.ToString();
                }
                creditCardExp = creditCardExp + paymentInfo.CreditCardExpireYear.ToString().Substring(2, 2);
                CreditCard credCard = new CreditCard(paymentInfo.CreditCardNumber, creditCardExp);
                credCard.Cvv2 = paymentInfo.CreditCardCvv2;
                CardTender tender = new CardTender(credCard);
                // <vendor> = your merchant (login id)
                // <user> = <vendor> unless you created a separate <user> for Payflow Pro
                // partner = paypal
                UserInfo userInfo = new UserInfo(user, vendor, partner, password);
                string   url      = GetPaypalUrl();
                PayflowConnectionData payflowConnectionData = new PayflowConnectionData(url, 443, null, 0, null, null);

                Response response = null;
                if (transactionMode == TransactMode.Authorize)
                {
                    response = new AuthorizationTransaction(userInfo, payflowConnectionData, invoice, tender, PayflowUtility.RequestId).SubmitTransaction();
                }
                else
                {
                    response = new SaleTransaction(userInfo, payflowConnectionData, invoice, tender, PayflowUtility.RequestId).SubmitTransaction();
                }

                if (response.TransactionResponse != null)
                {
                    if (response.TransactionResponse.Result == 0)
                    {
                        processPaymentResult.AuthorizationTransactionId     = response.TransactionResponse.Pnref;
                        processPaymentResult.AuthorizationTransactionResult = response.TransactionResponse.RespMsg;

                        if (transactionMode == TransactMode.Authorize)
                        {
                            processPaymentResult.PaymentStatus = PaymentStatusEnum.Authorized;
                        }
                        else
                        {
                            processPaymentResult.PaymentStatus = PaymentStatusEnum.Paid;
                        }
                    }
                    else
                    {
                        processPaymentResult.Error     = string.Format("{0} - {1}", response.TransactionResponse.Result, response.TransactionResponse.RespMsg);
                        processPaymentResult.FullError = string.Format("Response Code : {0}. Response Description : {1}", response.TransactionResponse.Result, response.TransactionResponse.RespMsg);
                    }
                }
                else
                {
                    processPaymentResult.Error     = "Error during checkout";
                    processPaymentResult.FullError = "Error during checkout";
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                NopContext.Current.SetCulture(userCulture);
            }
        }
Пример #17
0
        public static void Main(string[] Args)
        {
            Console.WriteLine("------------------------------------------------------");
            Console.WriteLine("Executing Sample from File: DODataUpload.cs");
            Console.WriteLine("------------------------------------------------------");

            // Create the Data Objects.
            // Create the User data object with the required user details.
            UserInfo User = new UserInfo("<user>", "<vendor>", "<partner>", "<password>");

            // Create the Payflow  Connection data object with the required connection details.
            // Values of connection details can also be passed in the constructor of
            // PayflowConnectionData. This will override the values passed in the App config file.
            // Example values passed below are as follows:
            // Payflow Pro Host address : pilot-payflowpro.paypal.com
            // Payflow Pro Host Port : 443
            // Timeout : 45 ( in seconds )
            PayflowConnectionData Connection = new PayflowConnectionData("pilot-payflowpro.paypal.com", 443, 45);

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

            // Remember, we do not send in an amount.

            Inv.PoNum  = "PO12345";
            Inv.InvNum = "INV12345";

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

            Bill.BillToStreet = "123 Main St.";
            Bill.BillToZip    = "12345";
            Inv.BillTo        = Bill;

            // Create a new Payment Device - Credit Card data object.
            // The input parameters are Credit Card Number and Expiration Date of the Credit Card.
            CreditCard CC = new CreditCard("5105105105105100", "0115");

            // Create a new Tender - Card Tender data object.
            CardTender Card = new CardTender(CC);

            // Create a new Base Transaction.
            BaseTransaction Trans = new BaseTransaction("L", User, Connection, Inv, Card, PayflowUtility.RequestId);

            // Submit the Transaction
            Response Resp = Trans.SubmitTransaction();

            // Display the transaction response parameters.
            if (Resp != null)
            {
                // Get the Transaction Response parameters.
                TransactionResponse TrxnResponse = Resp.TransactionResponse;

                if (TrxnResponse != null)
                {
                    Console.WriteLine("RESULT = " + TrxnResponse.Result);
                    Console.WriteLine("PNREF = " + TrxnResponse.Pnref);
                    Console.WriteLine("RESPMSG = " + TrxnResponse.RespMsg);
                    Console.WriteLine("TRANSTIME = " + TrxnResponse.TransTime);
                }

                // Display the response.
                Console.WriteLine(Environment.NewLine + PayflowUtility.GetStatus(Resp));


                // Get the Transaction Context and check for any contained SDK specific errors (optional code).
                Context TransCtx = Resp.TransactionContext;
                if (TransCtx != null && TransCtx.getErrorCount() > 0)
                {
                    Console.WriteLine(Environment.NewLine + "Transaction Errors = " + TransCtx.ToString());
                }
            }
            Console.WriteLine("Press Enter to Exit ...");
            Console.ReadLine();
        }
Пример #18
0
        public static void Main(string[] Args)
        {
            Console.WriteLine("------------------------------------------------------");
            Console.WriteLine("Executing Sample from File: DOFraudFilters.cs");
            Console.WriteLine("------------------------------------------------------");

            // Create the Data Objects.
            // Create the User data object with the required user details.
            UserInfo User = new UserInfo("<user>", "<vendor>", "<partner>", "<password>");

            // Create the Payflow  Connection data object with the required connection details.
            // The PAYFLOW_HOST property is defined in the App config file.
            PayflowConnectionData Connection = new PayflowConnectionData();

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

            // Set Amount.
            Currency Amt = new Currency(new decimal(51.00));

            Inv.Amt    = Amt;
            Inv.PoNum  = "PO12345";
            Inv.InvNum = "INV12345";

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

            Bill.BillToStreet = "677 Main St.";
            Bill.BillToZip    = "12345";
            Inv.BillTo        = Bill;

            CustomerInfo CustInfo = new CustomerInfo();

            CustInfo.CustIP  = "10.1.1.1";             // IP Velocity Filter
            Inv.CustomerInfo = CustInfo;

            // Create a new Payment Device - Credit Card data object.
            // The input parameters are Credit Card Number and Expiration Date of the Credit Card.
            CreditCard CC = new CreditCard("5105105105105100", "0115");

            CC.Cvv2 = "444";

            // Create a new Tender - Card Tender data object.
            CardTender Card = new CardTender(CC);
            ///////////////////////////////////////////////////////////////////

            // Create a new Sale Transaction with purchase price ceiling amount filter set to $50.
            SaleTransaction Trans = new SaleTransaction(
                User, Connection, Inv, Card, PayflowUtility.RequestId);

            // Set the Verbosity of the transaction to HIGH to get maximum information in the response.
            Trans.Verbosity = "HIGH";

            // Submit the Transaction
            Response Resp = Trans.SubmitTransaction();

            // Display the transaction response parameters.

            if (Resp != null)
            {
                // Get the Transaction Response parameters.
                TransactionResponse TrxnResponse = Resp.TransactionResponse;

                if (TrxnResponse != null)
                {
                    Console.WriteLine("RESULT = " + TrxnResponse.Result);
                    Console.WriteLine("PNREF = " + TrxnResponse.Pnref);
                    Console.WriteLine("RESPMSG = " + TrxnResponse.RespMsg);
                    Console.WriteLine("AUTHCODE = " + TrxnResponse.AuthCode);
                    Console.WriteLine("AVSADDR = " + TrxnResponse.AVSAddr);
                    Console.WriteLine("AVSZIP = " + TrxnResponse.AVSZip);
                    Console.WriteLine("IAVS = " + TrxnResponse.IAVS);
                    Console.WriteLine("HOSTCODE = " + TrxnResponse.HostCode);
                    Console.WriteLine("PROCAVS = " + TrxnResponse.ProcAVS);
                    Console.WriteLine("CVV2MATCH = " + TrxnResponse.CVV2Match);
                }

                // Get the Fraud Response parameters.
                FraudResponse FraudResp = Resp.FraudResponse;

                // Display Fraud Response parameter
                if (FraudResp != null)
                {
                    Console.WriteLine("PREFPSMSG = " + FraudResp.PreFpsMsg);
                    Console.WriteLine("POSTFPSMSG = " + FraudResp.PostFpsMsg);

                    // The following lines of code dealing with PreXmlData and PostXmlData will return all th rules
                    // that were triggered by the Fraud Service. For Example, let's assume the both AVS and CSC (CVV2)
                    // failed, the FraudResp.PostFpsMsg would something similar to:
                    // "Review: More than one rule was triggered for Review".
                    //
                    // The Fps_PreXmlData is returned as an Xml string. This is converted into Data Objects
                    // with the object hierarchy as shown below:
                    // FpsXmlData
                    // >>>>>>>>> List of Rule objects
                    // >>>>>>>>>>>>>>>>>> List of RuleVendorParm objects.
                    FpsXmlData PreXmlData = FraudResp.Fps_PreXmlData;
                    if (PreXmlData != null)
                    {
                        // Get the list of Rules.
                        ArrayList RulesList = PreXmlData.Rules;
                        if (RulesList != null && RulesList.Count > 0)
                        {
                            IEnumerator RulesEnum = RulesList.GetEnumerator();
                            Rule        DORule    = null;
                            // Loop through the list of Rules.
                            while (RulesEnum.MoveNext())
                            {
                                DORule = (Rule)RulesEnum.Current;
                                Console.WriteLine("------------------------------------------------------");
                                Console.WriteLine("PRE-XML DATA");
                                Console.WriteLine("------------------------------------------------------");
                                Console.WriteLine("Rule Number = " + DORule.Num.ToString());
                                Console.WriteLine("Rule Id = " + DORule.RuleId);
                                Console.WriteLine("Rule Alias = " + DORule.RuleAlias);
                                Console.WriteLine("Rule Description = " + DORule.RuleDescription);
                                Console.WriteLine("Action = " + DORule.Action);
                                Console.WriteLine("Triggered Message = " + DORule.TriggeredMessage);

                                // Get the list of Rule Vendor Parameters.
                                ArrayList RuleVendorParmsList = DORule.RuleVendorParms;

                                if (RuleVendorParmsList != null && RuleVendorParmsList.Count > 0)
                                {
                                    IEnumerator RuleParametersEnum = RuleVendorParmsList.GetEnumerator();
                                    // Loop through the list of Rule Parameters.
                                    while (RuleParametersEnum.MoveNext())
                                    {
                                        RuleParameter DORuleParam = (RuleParameter)RuleParametersEnum.Current;
                                        Console.WriteLine("Number = " + DORuleParam.Num.ToString());
                                        Console.WriteLine("Name = " + DORuleParam.Name);
                                        Console.WriteLine("Type = " + DORuleParam.Type);
                                        Console.WriteLine("Value = " + DORuleParam.Value);
                                    }
                                }
                            }
                        }
                        // The Fps_PostXmlData is returned as an Xml string. This is converted into Data Objects
                        // with the object hierarchy as shown below:
                        // FpsXmlData
                        // >>>>>>>>> List of Rule objects
                        // >>>>>>>>>>>>>>>>>> List of RuleVendorParm objects.
                        FpsXmlData PostXmlData = FraudResp.Fps_PostXmlData;
                        if (PostXmlData != null)
                        {
                            // Get the list of Rules.
                            ArrayList PostRulesList = PostXmlData.Rules;
                            if (PostRulesList != null && PostRulesList.Count > 0)
                            {
                                IEnumerator RulesEnum = PostRulesList.GetEnumerator();
                                Rule        DORule    = null;
                                // Loop through the list of Rules.
                                while (RulesEnum.MoveNext())
                                {
                                    DORule = (Rule)RulesEnum.Current;
                                    Console.WriteLine("------------------------------------------------------");
                                    Console.WriteLine("POST-XML DATA");
                                    Console.WriteLine("------------------------------------------------------");
                                    Console.WriteLine("Rule Number = " + DORule.Num.ToString());
                                    Console.WriteLine("Rule Id = " + DORule.RuleId);
                                    Console.WriteLine("Rule Alias = " + DORule.RuleAlias);
                                    Console.WriteLine("Rule Description = " + DORule.RuleDescription);
                                    Console.WriteLine("Action = " + DORule.Action);
                                    Console.WriteLine("Triggered Message = " + DORule.TriggeredMessage);

                                    // Get the list of Rule Vendor Parameters.
                                    ArrayList RuleVendorParmsList = DORule.RuleVendorParms;

                                    if (RuleVendorParmsList != null && RuleVendorParmsList.Count > 0)
                                    {
                                        IEnumerator RuleParametersEnum = RuleVendorParmsList.GetEnumerator();
                                        // Loop through the list of Rule Parameters.
                                        while (RuleParametersEnum.MoveNext())
                                        {
                                            RuleParameter DORuleParam = (RuleParameter)RuleParametersEnum.Current;
                                            Console.WriteLine("Number = " + DORuleParam.Num.ToString());
                                            Console.WriteLine("Name = " + DORuleParam.Name);
                                            Console.WriteLine("Type = " + DORuleParam.Type);
                                            Console.WriteLine("Value = " + DORuleParam.Value);
                                        }
                                    }
                                }
                            }
                        }
                    }

                    // Display the response.
                    Console.WriteLine(Environment.NewLine + PayflowUtility.GetStatus(Resp));

                    // Get the Transaction Context and check for any contained SDK specific errors (optional code).
                    Context TransCtx = Resp.TransactionContext;
                    if (TransCtx != null && TransCtx.getErrorCount() > 0)
                    {
                        Console.WriteLine(Environment.NewLine + "Transaction Errors = " + TransCtx.ToString());
                    }

                    Console.WriteLine("Press Enter to Exit ...");
                    Console.ReadLine();
                }
            }
        }
Пример #19
0
        public override String ProcessCard(int OrderNumber, int CustomerID, Decimal OrderTotal, bool useLiveTransactions, TransactionModeEnum TransactionMode, AspDotNetStorefrontCore.Address UseBillingAddress, String CardExtraCode, AspDotNetStorefrontCore.Address UseShippingAddress, String CAVV, String ECI, String XID, out String AVSResult, out String AuthorizationResult, out String AuthorizationCode, out String AuthorizationTransID, out String TransactionCommandOut, out String TransactionResponse)
        {
            AVSResult             = "N/A";
            AuthorizationResult   = "N/A";
            AuthorizationCode     = "N/A";
            AuthorizationTransID  = "N/A";
            TransactionCommandOut = "N/A";
            TransactionResponse   = String.Empty;

            String signedPARes = String.Empty;
            String result      = AppLogic.ro_OK;

            CustomerSession cSession = new CustomerSession(CustomerID);

            if (cSession["3Dsecure.PaRes"].Length != 0)
            {
                signedPARes = cSession["3Dsecure.PaRes"];
                // After grabbing it, clear out the session PaRes so it won't be re-used ever again.
                cSession["3Dsecure.PaRes"] = String.Empty;
            }

            Configuration conf = new Configuration();

            conf.KeysDirectory = AppLogic.AppConfig("CYBERSOURCE.keysDirectory");
            conf.KeyFilename   = AppLogic.AppConfig("CYBERSOURCE.keyFilename");
            conf.MerchantID    = AppLogic.AppConfig("CYBERSOURCE.merchantID");
            conf.ServerURL     = CommonLogic.IIF(useLiveTransactions, AppLogic.AppConfig("CYBERSOURCE.LiveURL"), AppLogic.AppConfig("CYBERSOURCE.TestURL"));
            if (AppLogic.AppConfigBool("CYBERSOURCE.UsePIT"))
            {
                conf.ServerURL = AppLogic.AppConfig("CYBERSOURCE.PITURL");
            }


            RequestMessage request = new RequestMessage();

            request.clientApplication        = "AspDotNetStorefront";
            request.clientApplicationVersion = AppLogic.AppConfig("StoreVersion");
            request.clientApplicationUser    = CustomerID.ToString();

            request.merchantReferenceCode = "Order # " + OrderNumber.ToString() + " " + Localization.ToNativeDateTimeString(System.DateTime.Now);

            int  CardTypeID  = DB.GetSqlN("select CardTypeID N from CreditCardType where CardType = " + DB.SQuote(UseBillingAddress.CardType));
            bool Try3DSecure = CommonLogic.IntegerIsInIntegerList(CardTypeID, AppLogic.AppConfig("3DSECURE.CreditCardTypeIDs"));

            if (Try3DSecure)
            {
                if (signedPARes == String.Empty)
                {
                    request.payerAuthEnrollService     = new PayerAuthEnrollService();
                    request.payerAuthEnrollService.run = "true";
                    if (AppLogic.AppConfig("CYBERSOURCE.paCountryCode") != "")
                    {
                        request.payerAuthEnrollService.countryCode = AppLogic.AppConfig("CYBERSOURCE.paCountryCode");
                    }
                    if (AppLogic.AppConfig("CYBERSOURCE.paMerchantName") != "")
                    {
                        request.payerAuthEnrollService.merchantName = AppLogic.AppConfig("CYBERSOURCE.paMerchantName");
                    }
                    if (AppLogic.AppConfig("CYBERSOURCE.paMerchantURL") != "")
                    {
                        request.payerAuthEnrollService.merchantURL = AppLogic.AppConfig("CYBERSOURCE.paMerchantURL");
                    }
                    request.payerAuthEnrollService.httpAccept    = CommonLogic.ServerVariables("HTTP_ACCEPT");
                    request.payerAuthEnrollService.httpUserAgent = CommonLogic.ServerVariables("HTTP_USER_AGENT");
                }
                else
                {
                    request.payerAuthValidateService             = new PayerAuthValidateService();
                    request.payerAuthValidateService.signedPARes = signedPARes;
                    request.payerAuthValidateService.run         = "true";
                }
            }

            request.ccAuthService     = new CCAuthService();
            request.ccAuthService.run = "true";

            if (CAVV.Trim().Length != 0)
            {     // only gets set as a result of 3D Secure processing
                if (GetCardTypeFieldValue(UseBillingAddress.CardType) == "002")
                { // for MasterCard
                    request.ccAuthService.xid  = XID;
                    request.ccAuthService.cavv = CAVV;
                }
            }

            request.merchantID = AppLogic.AppConfig("CYBERSOURCE.merchantID");

            if (TransactionMode == TransactionModeEnum.authcapture)
            {
                request.ccCaptureService     = new CCCaptureService();
                request.ccCaptureService.run = "true";
            }

            BillTo billTo = new BillTo();

            billTo.firstName   = UseBillingAddress.FirstName;
            billTo.lastName    = UseBillingAddress.LastName;
            billTo.company     = UseBillingAddress.Company;
            billTo.street1     = UseBillingAddress.Address1;
            billTo.street2     = UseBillingAddress.Address2;
            billTo.city        = UseBillingAddress.City;
            billTo.state       = UseBillingAddress.State;
            billTo.postalCode  = UseBillingAddress.Zip;
            billTo.country     = AppLogic.GetCountryTwoLetterISOCode(UseBillingAddress.Country);
            billTo.phoneNumber = UseBillingAddress.Phone.PadRight(6, '1');
            billTo.email       = CommonLogic.IIF(UseBillingAddress.EMail.Length > 2, UseBillingAddress.EMail, "*****@*****.**");
            billTo.ipAddress   = CommonLogic.CustomerIpAddress();
            request.billTo     = billTo;

            if (UseShippingAddress != null)
            {
                ShipTo ShipTo = new ShipTo();
                ShipTo.firstName   = UseShippingAddress.FirstName;
                ShipTo.lastName    = UseShippingAddress.LastName;
                ShipTo.company     = UseShippingAddress.Company;
                ShipTo.street1     = UseShippingAddress.Address1;
                ShipTo.street2     = UseShippingAddress.Address2;
                ShipTo.city        = UseShippingAddress.City;
                ShipTo.state       = UseShippingAddress.State;
                ShipTo.postalCode  = UseShippingAddress.Zip;
                ShipTo.country     = AppLogic.GetCountryTwoLetterISOCode(UseShippingAddress.Country);
                ShipTo.phoneNumber = UseShippingAddress.Phone.PadRight(6, '1');
                ShipTo.email       = CommonLogic.IIF(UseShippingAddress.EMail.Length > 2, UseShippingAddress.EMail, "*****@*****.**");
                request.shipTo     = ShipTo;
            }

            Card card = new Card();

            card.accountNumber = UseBillingAddress.CardNumber;
            if (CardExtraCode.Trim().Length != 0)
            {
                card.cvIndicator = "1";
                card.cvNumber    = CardExtraCode;
            }
            else
            {
                card.cvIndicator = "0";
            }

            if (!String.IsNullOrEmpty(UseBillingAddress.CardStartDate) && UseBillingAddress.CardStartDate != "00")
            {
                card.startMonth = UseBillingAddress.CardStartDate.Substring(0, 2);
                card.startYear  = UseBillingAddress.CardStartDate.Substring(4, 2);
            }

            if (UseBillingAddress.CardIssueNumber.Length != 0)
            {
                card.issueNumber = UseBillingAddress.CardIssueNumber;
            }
            card.expirationMonth = UseBillingAddress.CardExpirationMonth;
            card.expirationYear  = UseBillingAddress.CardExpirationYear;

            if (Try3DSecure)
            {
                card.cardType = GetCardTypeFieldValue(UseBillingAddress.CardType);
                if (card.cardType == "000")
                {
                    return(" Error in configuration. Card type " + UseBillingAddress.CardType + " is not recognized by the gateway.");
                }
            }

            request.card = card;

            request.item = new Item[1];
            Item the_item = new Item();

            the_item.id        = "0";
            the_item.unitPrice = Localization.CurrencyStringForGatewayWithoutExchangeRate(OrderTotal);
            request.item[0]    = the_item;

            PurchaseTotals ptotal = new PurchaseTotals();

            ptotal.currency         = Localization.StoreCurrency();                                         // Currency REQUIRED
            ptotal.grandTotalAmount = Localization.CurrencyStringForGatewayWithoutExchangeRate(OrderTotal); // Not needed - can use instead of item price, I think it's better..
            request.purchaseTotals  = ptotal;                                                               // Neccessary

            result = "ERROR: ";


            try
            {
                ReplyMessage reply = SoapClient.RunTransaction(conf, request);

                if (Try3DSecure && request.payerAuthEnrollService != null)
                {
                    if (request.payerAuthEnrollService.run == "true")
                    { // we have some data that needs stored
                        string LookupResult = String.Empty;
                        if (reply.payerAuthEnrollReply != null &&
                            reply.payerAuthEnrollReply.paReq != null &&
                            reply.payerAuthEnrollReply.paReq.Length > 0)
                        { // will be null if card not enrolled
                            // the paReq comes back encoded, Streamline requires it to be decoded.
                            string sPAReq = CommonLogic.UnzipBase64DataToString(reply.payerAuthEnrollReply.paReq);
                            LookupResult += "paReq=" + XmlCommon.PrettyPrintXml(sPAReq) + System.Environment.NewLine;
                        }
                        if (reply.payerAuthEnrollReply != null &&
                            reply.payerAuthEnrollReply.proofXML != null)
                        {
                            /****************************************************************
                            *  Store the complete proofXML whenever it is                  *
                            *  returned. If you ever need to show proof of                 *
                            *  enrollment checking, you will need to parse the string      *
                            *  for the information required by the card association.       *
                            ****************************************************************/
                            LookupResult += "proofXML data =";
                            LookupResult += System.Environment.NewLine + XmlCommon.PrettyPrintXml(reply.payerAuthEnrollReply.proofXML);
                        }
                        if (LookupResult != String.Empty)
                        { // encode it to store in the session, it will be decoded before being saved to the database
                            byte[] str = Encoding.UTF8.GetBytes(LookupResult);
                            cSession["3DSecure.LookupResult"] = Convert.ToBase64String(str);
                        }
                    }
                }

                if (reply.decision == "REJECT" && reply.reasonCode == "475")
                { // card enrolled, must perform 3D Secure processing (reasonCode == 475)
                    cSession["3DSecure.CustomerID"]  = CustomerID.ToString();
                    cSession["3DSecure.OrderNumber"] = OrderNumber.ToString();
                    cSession["3DSecure.MD"]          = OrderNumber.ToString();
                    cSession["3DSecure.ACSUrl"]      = reply.payerAuthEnrollReply.acsURL;
                    cSession["3DSecure.paReq"]       = reply.payerAuthEnrollReply.paReq;
                    cSession["3DSecure.XID"]         = reply.payerAuthEnrollReply.xid;
                    cSession.UpdateCustomerSession(null, null);
                    result = AppLogic.ro_3DSecure; // This is what triggers the 3D Secure IFRAME to be used.
                    return(result);
                }

                if (reply.decision == "ACCEPT" || reply.decision == "REVIEW")
                {
                    result = AppLogic.ro_OK;
                    if (AppLogic.TransactionModeIsAuthCapture())
                    {
                        AVSResult            = reply.ccAuthReply.avsCode;
                        AuthorizationResult  = reply.ccCaptureReply.reasonCode;
                        AuthorizationCode    = reply.ccAuthReply.authorizationCode;
                        AuthorizationTransID = reply.requestID;
                    }
                    else
                    {
                        AVSResult            = reply.ccAuthReply.avsCode;
                        AuthorizationResult  = reply.reasonCode;
                        AuthorizationCode    = reply.ccAuthReply.authorizationCode;
                        AuthorizationTransID = reply.requestID;
                    }
                    if (signedPARes.Length > 0)
                    {
                        if (reply.payerAuthValidateReply != null)
                        {
                            if (reply.payerAuthValidateReply.ucafAuthenticationData != null)
                            { // MasterCard SecureCode
                                AuthorizationResult += System.Environment.NewLine + "CAVV: " + reply.payerAuthValidateReply.ucafAuthenticationData;
                                AuthorizationResult += System.Environment.NewLine + "ECI: " + reply.payerAuthValidateReply.ucafCollectionIndicator;
                            }
                            else
                            { // Visa VBV
                                AuthorizationResult += System.Environment.NewLine + "CAVV: " + reply.payerAuthValidateReply.cavv;
                                AuthorizationResult += System.Environment.NewLine + "ECI: " + reply.payerAuthValidateReply.eci;
                            }
                        }
                        AuthorizationResult += System.Environment.NewLine + "signedPARes: ";
                        // Streamline requires saving the decoded PARes to the database
                        string sPARes = CommonLogic.UnzipBase64DataToString(signedPARes);

                        // zap the signature since it is long and we don't need it
                        String t1  = "<Signature ";
                        String t2  = "</Signature>";
                        String sig = t1 + CommonLogic.ExtractToken(sPARes, t1, t2) + t2;
                        AuthorizationResult += System.Environment.NewLine + XmlCommon.PrettyPrintXml(sPARes.Replace(sig, ""));
                    }
                }
                else
                {
                    result = "Your transaction was NOT approved, reason code: " + reply.reasonCode + ". ";
                    if (reply.reasonCode == "476" && reply.payerAuthValidateReply != null)
                    {
                        result += reply.payerAuthValidateReply.authenticationStatusMessage
                                  + ". Please try another payment method.";
                    }

                    else
                    {
                        result += GetReasonCodeDescription(reply.reasonCode);

                        if (reply.missingField != null)
                        {
                            foreach (string fieldname in reply.missingField)
                            {
                                result += "[" + fieldname + "]";
                            }
                        }

                        if (reply.invalidField != null)
                        {
                            foreach (string fieldname in reply.invalidField)
                            {
                                result += "[" + fieldname + "]";
                            }
                        }
                    }
                }
            }
            catch (SignException se)
            {
                result += "Error calling Cybersource gateway. Please retry your order in a few minutes or select another checkout payment option. "
                          + String.Format("Failed to sign the request with error code {0} and message {1}.", DB.SQuote(se.ErrorCode.ToString()), DB.SQuote(se.Message));
            }
            catch (SoapHeaderException she)
            {
                result += String.Format("A SOAP header exception was returned with fault code {0} and message {1}.", DB.SQuote(she.Code.ToString()), DB.SQuote(she.Message));
            }
            catch (SoapBodyException sbe)
            {
                result += String.Format("A SOAP body exception was returned with fault code {0} and message {1}.", DB.SQuote(sbe.Code.ToString()), DB.SQuote(sbe.Message));
            }
            catch (WebException we)
            {
                result += String.Format("Failed to get a response with status {0} and mmessage {1}", DB.SQuote(we.Status.ToString()), DB.SQuote(we.Message));
            }
            catch (Exception ex)
            {
                // See requirements at the top of this file.
                result += "Error calling Cybersource gateway. Please retry your order in a few minutes or select another checkout payment option.";
                result += " Error message: Make sure the required components for Cybersource are installed on the server. " + ex.Message;
                result += " <> " + ex.ToString();
            }
            return(result);
        }
Пример #20
0
    static void Main(string[] args)
    {
        RequestMessage request = new RequestMessage();

        request.merchantID = MERCHANT_ID;

        // Before using this example, replace the generic value with your
        // reference number for the current transaction.
        request.merchantReferenceCode = "test01";

        // To help us troubleshoot any problems that you may encounter,
        // please include the following information about your application.
        request.clientLibrary = ".NET WCF";
        request.clientLibraryVersion = Environment.Version.ToString();
        request.clientEnvironment =
            Environment.OSVersion.Platform +
            Environment.OSVersion.Version.ToString();

        // This section contains a sample transaction request for the authorization
        // service with complete billing, payment card, and purchase (two items) information.
        request.ccAuthService = new CCAuthService();
        request.ccAuthService.run = "true";

        BillTo billTo = new BillTo();
        billTo.firstName = "John";
        billTo.lastName = "Doe";
        billTo.street1 = "1295 Charleston Road";
        billTo.city = "Mountain View";
        billTo.state = "CA";
        billTo.postalCode = "94043";
        billTo.country = "US";
        billTo.email = "*****@*****.**";
        billTo.ipAddress = "10.7.111.111";
        request.billTo = billTo;

        Card card = new Card();
        card.accountNumber = "4111111111111111";
        card.expirationMonth = "12";
        card.expirationYear = "2020";
        request.card = card;

        PurchaseTotals purchaseTotals = new PurchaseTotals();
        purchaseTotals.currency = "USD";
        request.purchaseTotals = purchaseTotals;

        request.item = new Item[2];

        Item item = new Item();
        item.id = "0";
        item.unitPrice = "12.34";
        request.item[0] = item;

        item = new Item();
        item.id = "1";
        item.unitPrice = "56.78";
        request.item[1] = item;

        try
        {
            TransactionProcessorClient proc = new TransactionProcessorClient();

            proc.ChannelFactory.Credentials.UserName.UserName = request.merchantID;
            proc.ChannelFactory.Credentials.UserName.Password = TRANSACTION_KEY;

            ReplyMessage reply = proc.runTransaction(request);

            // To retrieve individual reply fields, follow these examples.
            Console.WriteLine("decision = " + reply.decision);
            Console.WriteLine("reasonCode = " + reply.reasonCode);
            Console.WriteLine("requestID = " + reply.requestID);
            Console.WriteLine("requestToken = " + reply.requestToken);
            Console.WriteLine("ccAuthReply.reasonCode = " + reply.ccAuthReply.reasonCode);
        }
        catch (TimeoutException e)
        {
            Console.WriteLine("TimeoutException: " + e.Message + "\n" + e.StackTrace);
        }
        catch (FaultException e)
        {
            Console.WriteLine("FaultException: " + e.Message + "\n" + e.StackTrace);
        }
        catch (CommunicationException e)
        {
            Console.WriteLine("CommunicationException: " + e.Message + "\n" + e.StackTrace);
        }
    }
Пример #21
0
        protected virtual void PrepareCustomAddressAttributes(AddressModel model,
                                                              BillTo address, string overrideAttributesXml = "")
        {
            var attributes = _addressAttributeService.GetAllAddressAttributes();

            foreach (var attribute in attributes)
            {
                var attributeModel = new AddressAttributeModel
                {
                    Id                   = attribute.Id,
                    Name                 = _localizationService.GetLocalized(attribute, x => x.Name),
                    IsRequired           = attribute.IsRequired,
                    AttributeControlType = attribute.AttributeControlType,
                };

                if (attribute.ShouldHaveValues())
                {
                    //values
                    var attributeValues = _addressAttributeService.GetAddressAttributeValues(attribute.Id);
                    foreach (var attributeValue in attributeValues)
                    {
                        var attributeValueModel = new AddressAttributeValueModel
                        {
                            Id            = attributeValue.Id,
                            Name          = _localizationService.GetLocalized(attributeValue, x => x.Name),
                            IsPreSelected = attributeValue.IsPreSelected
                        };
                        attributeModel.Values.Add(attributeValueModel);
                    }
                }

                //set already selected attributes
                var selectedAddressAttributes = !string.IsNullOrEmpty(overrideAttributesXml) ?
                                                overrideAttributesXml :
                                                (address != null ? address.CustomAttributes : null);
                switch (attribute.AttributeControlType)
                {
                case AttributeControlType.DropdownList:
                case AttributeControlType.RadioList:
                case AttributeControlType.Checkboxes:
                {
                    if (!string.IsNullOrEmpty(selectedAddressAttributes))
                    {
                        //clear default selection
                        foreach (var item in attributeModel.Values)
                        {
                            item.IsPreSelected = false;
                        }

                        //select new values
                        var selectedValues = _addressAttributeParser.ParseAddressAttributeValues(selectedAddressAttributes);
                        foreach (var attributeValue in selectedValues)
                        {
                            foreach (var item in attributeModel.Values)
                            {
                                if (attributeValue.Id == item.Id)
                                {
                                    item.IsPreSelected = true;
                                }
                            }
                        }
                    }
                }
                break;

                case AttributeControlType.ReadonlyCheckboxes:
                {
                    //do nothing
                    //values are already pre-set
                }
                break;

                case AttributeControlType.TextBox:
                case AttributeControlType.MultilineTextbox:
                {
                    if (!string.IsNullOrEmpty(selectedAddressAttributes))
                    {
                        var enteredText = _addressAttributeParser.ParseValues(selectedAddressAttributes, attribute.Id);
                        if (enteredText.Any())
                        {
                            attributeModel.DefaultValue = enteredText[0];
                        }
                    }
                }
                break;

                case AttributeControlType.ColorSquares:
                case AttributeControlType.ImageSquares:
                case AttributeControlType.Datepicker:
                case AttributeControlType.FileUpload:
                default:
                    //not supported attribute control types
                    break;
                }

                model.CustomAddressAttributes.Add(attributeModel);
            }
        }
Пример #22
0
        public string SamplePaymentsData()
        {
            //Create the Sample Data using Model Classes of Payments API


            var clientReferenceInformation = new ClientReferenceInformation {
                code = "TC50171_3"
            };

            var processingInformation = new ProcessingInformation {
                commerceIndicator = "internet"
            };

            var subMerchant = new SubMerchant
            {
                cardAcceptorID     = "1234567890",
                country            = "US",
                phoneNumber        = "650-432-0000",
                address1           = "900 Metro Center",
                postalCode         = "94404-2775",
                locality           = "Foster Cit",
                name               = "Visa Inc",
                administrativeArea = "CA",
                region             = "PEN",
                email              = "*****@*****.**"
            };

            var aggregatorInformation = new AggregatorInformation
            {
                subMerchant  = subMerchant,
                name         = "V-Internatio",
                aggregatorID = "123456789"
            };

            var billTo = new BillTo
            {
                country            = "US",
                lastName           = "VDP",
                address2           = "Address 2",
                address1           = "201 S. Division St.",
                postalCode         = "48104-2201",
                locality           = "Ann Arbor",
                administrativeArea = "MI",
                firstName          = "RTS",
                phoneNumber        = "999999999",
                district           = "MI",
                buildingNumber     = "123",
                company            = "Visa",
                email = "*****@*****.**"
            };

            var amountDetails = new AmountDetails
            {
                totalAmount = "102.21",
                currency    = "USD"
            };

            var orderInformation = new OrderInformation
            {
                billTo        = billTo,
                amountDetails = amountDetails
            };

            var card = new Card
            {
                expirationYear  = "2031",
                number          = "5555555555554444",
                securityCode    = "123",
                expirationMonth = "12",
                type            = "002"
            };

            var paymentInformation = new PaymentInformation {
                card = card
            };

            var payments = new Payments
            {
                clientReferenceInformation = clientReferenceInformation,
                processingInformation      = processingInformation,
                aggregatorInformation      = aggregatorInformation,
                orderInformation           = orderInformation,
                paymentInformation         = paymentInformation
            };

            return(JsonConvert.SerializeObject(payments, Formatting.Indented));
        }
        /// <summary>
        /// Process payment
        /// </summary>
        /// <param name="paymentInfo">Payment info required for an order processing</param>
        /// <param name="customer">Customer</param>
        /// <param name="OrderGuid">Unique order identifier</param>
        /// <param name="processPaymentResult">Process payment result</param>
        public void ProcessPayment(PaymentInfo paymentInfo, Customer customer, Guid OrderGuid, ref ProcessPaymentResult processPaymentResult)
        {
            InitSettings();
            TransactMode transactionMode = GetCurrentTransactionMode();

            //little hack here
            CultureInfo userCulture = Thread.CurrentThread.CurrentCulture;
            NopContext.Current.SetCulture(new CultureInfo("en-US"));
            try
            {
                BillTo to = new BillTo();
                to.FirstName = paymentInfo.BillingAddress.FirstName;
                to.LastName = paymentInfo.BillingAddress.LastName;
                to.Street = paymentInfo.BillingAddress.Address1;
                to.City = paymentInfo.BillingAddress.City;
                to.Zip = paymentInfo.BillingAddress.ZipPostalCode;
                if (paymentInfo.BillingAddress.StateProvince != null)
                    to.State = paymentInfo.BillingAddress.StateProvince.Abbreviation;
                ShipTo to2 = new ShipTo();
                to2.ShipToFirstName = paymentInfo.ShippingAddress.FirstName;
                to2.ShipToLastName = paymentInfo.ShippingAddress.LastName;
                to2.ShipToStreet = paymentInfo.ShippingAddress.Address1;
                to2.ShipToCity = paymentInfo.ShippingAddress.City;
                to2.ShipToZip = paymentInfo.ShippingAddress.ZipPostalCode;
                if (paymentInfo.ShippingAddress.StateProvince != null)
                    to2.ShipToState = paymentInfo.ShippingAddress.StateProvince.Abbreviation;

                Invoice invoice = new Invoice();
                invoice.BillTo = to;
                invoice.ShipTo = to2;
                invoice.InvNum = OrderGuid.ToString();
                //For values which have more than two decimal places 
                //Currency Amt = new Currency(new decimal(25.1214));
                //Amt.NoOfDecimalDigits = 2;
                //If the NoOfDecimalDigits property is used then it is mandatory to set one of the following properties to true.
                //Amt.Round = true;
                //Amt.Truncate = true;
                //Inv.Amt = Amt;
                decimal orderTotal = Math.Round(paymentInfo.OrderTotal, 2);
                //UNDONE USD only
                invoice.Amt = new PayPal.Payments.DataObjects.Currency(orderTotal, CurrencyManager.PrimaryStoreCurrency.CurrencyCode);

                string creditCardExp = string.Empty;
                if (paymentInfo.CreditCardExpireMonth < 10)
                {
                    creditCardExp = "0" + paymentInfo.CreditCardExpireMonth.ToString();
                }
                else
                {
                    creditCardExp = paymentInfo.CreditCardExpireMonth.ToString();
                }
                creditCardExp = creditCardExp + paymentInfo.CreditCardExpireYear.ToString().Substring(2, 2);
                CreditCard credCard = new CreditCard(paymentInfo.CreditCardNumber, creditCardExp);
                credCard.Cvv2 = paymentInfo.CreditCardCVV2;
                CardTender tender = new CardTender(credCard);
                // <vendor> = your merchant (login id)  
                // <user> = <vendor> unless you created a separate <user> for Payflow Pro
                // partner = paypal
                UserInfo userInfo = new UserInfo(user, vendor, partner, password);
                string url = GetPaypalUrl();
                PayflowConnectionData payflowConnectionData = new PayflowConnectionData(url, 443, null, 0, null, null);

                Response response = null;
                if (transactionMode == TransactMode.Authorize)
                {
                    response = new AuthorizationTransaction(userInfo, payflowConnectionData, invoice, tender, PayflowUtility.RequestId).SubmitTransaction();
                }
                else
                {
                    response = new SaleTransaction(userInfo, payflowConnectionData, invoice, tender, PayflowUtility.RequestId).SubmitTransaction();
                }

                if (response.TransactionResponse != null)
                {
                    if (response.TransactionResponse.Result == 0)
                    {
                        processPaymentResult.AuthorizationTransactionID = response.TransactionResponse.Pnref;
                        processPaymentResult.AuthorizationTransactionResult = response.TransactionResponse.RespMsg;

                        if (transactionMode == TransactMode.Authorize)
                        {
                            processPaymentResult.PaymentStatus = PaymentStatusEnum.Authorized;
                        }
                        else
                        {
                            processPaymentResult.PaymentStatus = PaymentStatusEnum.Paid;
                        }
                    }
                    else
                    {
                        processPaymentResult.Error = string.Format("{0} - {1}", response.TransactionResponse.Result, response.TransactionResponse.RespMsg);
                        processPaymentResult.FullError = string.Format("Response Code : {0}. Response Description : {1}", response.TransactionResponse.Result, response.TransactionResponse.RespMsg);
                    }
                }
                else
                {
                    processPaymentResult.Error = "Error during checkout";
                    processPaymentResult.FullError = "Error during checkout";
                }
            }
            catch (Exception exc)
            {
                throw;
            }
            finally
            {
                NopContext.Current.SetCulture(userCulture);
            }
        }
Пример #24
0
        public ActionResult CreateBilling(UserBillingInformationInput input)
        {
            if (!ModelState.IsValid)
            {
                ViewBag.errMessages = string.Join("; ", ModelState.Values
                                                  .SelectMany(x => x.Errors)
                                                  .Select(x => x.ErrorMessage));

                return(View(input));
            }

            // var xPrice = (decimal)input.SpecialPostingCost;
            if (!ModelState.IsValid)
            {
                return(View(input));
            }

            //be sure the amount paid is the amount required*/

            RequestMessage request = new RequestMessage();

            request.merchantID = MERCHANT_ID;

            // To help us troubleshoot any problems that you may encounter,
            // please include the following information about your application.
            request.clientLibrary        = ".NET WCF";
            request.clientLibraryVersion = Environment.Version.ToString();
            request.clientEnvironment    =
                Environment.OSVersion.Platform +
                Environment.OSVersion.Version.ToString();

            // This section contains a sample transaction request for the authorization
            // service with complete billing, payment card, and purchase (two items) information.
            request.ccAuthService     = new CCAuthService();
            request.ccAuthService.run = "true";


            BillTo billTo = new BillTo();

            billTo.firstName   = input.FirstName;
            billTo.lastName    = input.LastName;
            billTo.street1     = input.BillingAddress;
            billTo.city        = input.City;
            billTo.postalCode  = input.BillingZipCode;
            billTo.country     = input.Country;
            billTo.email       = input.BillingContactEmail;
            billTo.ipAddress   = GetPublicIP();
            billTo.phoneNumber = input.BillingContactNumber;

            request.billTo = billTo;

            Card card = new Card();

            card.accountNumber   = input.CreditCardNumber; // "4111111111111111";
            card.expirationMonth = input.ExpiryDate.PadLeft(2);
            card.expirationYear  = input.ExpiryDate.PadRight(4);
            card.cvNumber        = input.CardCode;
            request.card         = card;

            PurchaseTotals purchaseTotals = new PurchaseTotals();

            purchaseTotals.currency = "SGD";
            if (input.Subscription.Equals("100$/Month"))
            {
                purchaseTotals.originalAmount = "100";
            }
            else if (input.Subscription.Equals("600$/Semi-Annual"))
            {
                purchaseTotals.originalAmount = "600";
            }
            else if (input.Subscription.Equals("1200$/Annual"))
            {
                purchaseTotals.originalAmount = "1200";
            }
            request.purchaseTotals = purchaseTotals;

            // Before using this example, replace the generic value with your
            // reference number for the current transaction.
            request.merchantReferenceCode = "U" + input.UserId + "A" + purchaseTotals.originalAmount;
            request.item = new Item[1];

            Item item = new Item();

            item.id         = "0";
            item.unitPrice  = purchaseTotals.originalAmount;
            request.item[0] = item;


            try
            {
                TransactionProcessorClient proc = new TransactionProcessorClient();

                proc.ChannelFactory.Credentials.UserName.UserName = request.merchantID;
                proc.ChannelFactory.Credentials.UserName.Password = TRANSACTION_KEY;

                ReplyMessage reply = proc.runTransaction(request);

                if (reply.decision == "ACCEPT")
                {
                    SaveOrderState();
                    ProcessReply(reply);
                    var userBillingInformation = service.Create(new UserBillingInformation
                    {
                        FirstName            = input.FirstName,
                        LastName             = input.LastName,
                        BillingAddress       = input.BillingAddress,
                        BillingZipCode       = input.BillingZipCode,
                        BillingContactNumber = input.BillingContactNumber,
                        BillingContactEmail  = input.BillingContactEmail,
                        CreditCardNumber     = input.CreditCardNumber,
                        ExpiryDate           = input.ExpiryDate,
                        UserId = input.UserId
                    });

                    service.Save();

                    var user = serviceUser.Where(o => o.Id.Equals(input.UserId)).SingleOrDefault();

                    User selectedUser = serviceUser.Get(user.Id);
                    selectedUser.PaymentStatus = "Active";
                    serviceUser.Save();


                    using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Db"].ConnectionString))
                        using (var command = new SqlCommand("sp_send_dbmail", conn)
                        {
                            CommandType = CommandType.StoredProcedure
                        })
                        {
                            conn.Open();
                            command.Parameters.Add(new SqlParameter("@profile_name", "DBMail Profile"));
                            command.Parameters.Add(new SqlParameter("@recipients", input.BillingContactEmail));
                            command.Parameters.Add(new SqlParameter("@subject", "AppWiz Billing Info registration"));
                            command.Parameters.Add(new SqlParameter("@from_address",
                                                                    ConfigurationManager.AppSettings["EmailHost"]));
                            command.Parameters.Add(new SqlParameter("@Body", "AppWiz payment acknowledgement."));
                            command.ExecuteNonQuery();
                            conn.Close();
                        }
                    return(RedirectToAction("Index", "Application"));
                }
            }
            catch (TimeoutException e)
            {
                //Console.WriteLine("TimeoutException: " + e.Message + "\n" + e.StackTrace);
                // return Json("TimeoutException: " + e.Message + "\n" + e.StackTrace);
                return(Json(false));
            }
            catch (FaultException e)
            {
                //Console.WriteLine("FaultException: " + e.Message + "\n" + e.StackTrace);
                return(Json(false));
            }
            catch (CommunicationException e)
            {
                //Console.WriteLine("CommunicationException: " + e.Message + "\n" + e.StackTrace);
                return(Json(false));
            }

            return(Json(false));
        }
Пример #25
0
        /// <summary>
        /// Gets the bill to from a transaction.
        /// </summary>
        /// <param name="transaction">The transaction.</param>
        /// <returns></returns>
        private BillTo GetBillTo( FinancialTransaction transaction )
        {
            BillTo billingInfo = new BillTo();
            billingInfo.customerID = transaction.AuthorizedPersonAlias.Id.ToString();
            billingInfo.firstName = transaction.AuthorizedPersonAlias.Person.FirstName.Left( 50 );       // up to 50 chars
            billingInfo.lastName = transaction.AuthorizedPersonAlias.Person.LastName.Left( 50 );         // up to 60 chars
            billingInfo.email = transaction.AuthorizedPersonAlias.Person.Email.Left( 255 );              // up to 255 chars
            billingInfo.ipAddress = Dns.GetHostEntry( Dns.GetHostName() )
                .AddressList.FirstOrDefault( ip => ip.AddressFamily == AddressFamily.InterNetwork ).ToString();

            return billingInfo;
        }
Пример #26
0
        /// <summary>
        /// Gets the billing details from user submitted payment info.
        /// </summary>
        /// <param name="paymentInfo">The payment information.</param>
        /// <returns></returns>
        private BillTo GetBillTo( PaymentInfo paymentInfo )
        {
            BillTo billingInfo = new BillTo();

            if ( paymentInfo.Phone == null )
            {
                paymentInfo.Phone = string.Empty;
            }

            if ( paymentInfo is CreditCardPaymentInfo )
            {
                var cc = paymentInfo as CreditCardPaymentInfo;
                billingInfo.street1 = cc.BillingStreet1.Left( 50 );
                billingInfo.city = cc.BillingCity.Left( 50 );
                billingInfo.state = cc.BillingState.Left( 2 );
                billingInfo.postalCode = cc.BillingPostalCode.Left( 10 );
            }
            else
            {
                billingInfo.street1 = paymentInfo.Street1.Left( 50 );           // up to 50 chars
                billingInfo.city = paymentInfo.City.Left( 50 );                 // up to 50 chars
                billingInfo.state = paymentInfo.State.Left( 2 );                // only 2 chars

                var zip = paymentInfo.PostalCode;
                if ( !string.IsNullOrWhiteSpace( zip ) && zip.Length > 5 )
                {
                    Regex.Replace( zip, @"^(.{5})(.{4})$", "$1-$2" );           // up to 9 chars with a separating -
                }
                billingInfo.postalCode = zip;
            }

            billingInfo.firstName = paymentInfo.FirstName.Left( 50 );       // up to 50 chars
            billingInfo.lastName = paymentInfo.LastName.Left( 60 );         // up to 60 chars
            billingInfo.email = paymentInfo.Email;                          // up to 255 chars
            billingInfo.phoneNumber = paymentInfo.Phone.Left( 15 );         // up to 15 chars

            var country = paymentInfo.Country ?? "US";
            billingInfo.country = country.Left( 2 );                        // only 2 chars

            var ipAddr = Dns.GetHostEntry( Dns.GetHostName() ).AddressList
                .FirstOrDefault( ip => ip.AddressFamily == AddressFamily.InterNetwork );
            billingInfo.ipAddress = ipAddr.ToString();                      // machine IP address

            return billingInfo;
        }
Пример #27
0
		static void Main(string[] args)
		{
			RequestMessage request = new RequestMessage();

            // we will let the client pick up the merchantID
            // from the config file.  In multi-merchant scenarios,
            // you would set a merchantID in each request.

            // this sample requests auth and capture
	
			// Credit Card Authorization
			request.ccAuthService = new CCAuthService();
			request.ccAuthService.run = "true";

			// Credit Card Capture
			request.ccCaptureService = new CCCaptureService();
			request.ccCaptureService.run = "true";


			// add required fields

			request.merchantReferenceCode = "your_merchant_reference_code";

			BillTo billTo = new BillTo();
			billTo.firstName = "John";
			billTo.lastName = "Doe";
			billTo.street1 = "1295 Charleston Road";
			billTo.city = "Mountain View";
			billTo.state = "CA";
			billTo.postalCode = "94043";
			billTo.country = "US";
			billTo.email = "*****@*****.**";
			billTo.ipAddress = "10.7.111.111";
			request.billTo = billTo;

			Card card = new Card();
			card.accountNumber = "4111111111111111";
			card.expirationMonth = "12";
			card.expirationYear = "2020";
			request.card = card;

			PurchaseTotals purchaseTotals = new PurchaseTotals();
			purchaseTotals.currency = "USD";
			request.purchaseTotals = purchaseTotals;

			// there are two items in this sample
			request.item = new Item[2];

			Item item = new Item();
			item.id = "0";
			item.unitPrice = "12.34";
			request.item[0] = item;

			item = new Item();
			item.id = "1";
			item.unitPrice = "56.78";
			request.item[1] = item;

			// add optional fields here per your business needs

			try
			{
				ReplyMessage reply = SoapClient.RunTransaction( request );
				SaveOrderState();
				ProcessReply( reply );
			}
           /*** There are many specific exceptions that could be caught here. Only a few are provided as examples. 
             This is a Windows Communication Foundation (WCF) Client and uses exceptions from the System.ServiceModel
             Namespaces. Please refer to the Microsoft documentation to better understand what these exceptions mean.
                
            ***/

           //System.ServiceModel Exception examples.
            catch (EndpointNotFoundException e)
            {
                // This is thrown when a remote endpoint could not be found or reached.  
                // The remote endpoint is down, the client network connection is down, 
                // the remote endpoint is unreachable, or because the remote network is unreachable.

                SaveOrderState();
                HandleException(e);
            }
            catch (ChannelTerminatedException e)
            {
                // This is typically thrown on the client when a channel is terminated due to the server closing the connection.
                SaveOrderState();
                HandleException(e);
            }
            //System.ServiceModel.Security Exception example.
            catch (MessageSecurityException e)
            {
                //Represents an exception that occurred when there is something wrong with the security applied on a message. Possibly a bad signature.
                SaveOrderState();
                HandleSecurityException(e);
            }
            //System.Security.Cryptography exception    
            catch (CryptographicException ce)
            {
                //Represents a problem with your X509 certificate (.p12 file) or a problem creating a signature from the certificate.
                SaveOrderState();
                HandleCryptoException(ce);
            }
            //System.Net exception    
            catch (WebException we)
            {
                //The WebException class is thrown by classes descended from WebRequest and WebResponse that implement pluggable protocols for accessing the Internet.
                SaveOrderState();
                HandleWebException(we);
            }
            //Any other exception!
            catch (Exception e)
            {
                SaveOrderState();
                HandleException(e);
            }

            Console.WriteLine("Press Return to end...");
            Console.ReadLine();
		}
        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);
        }
Пример #29
0
        public static void Main(string[] Args)
        {
            Console.WriteLine("------------------------------------------------------");
            Console.WriteLine("Executing Sample from File: DORecurringPayment.cs");
            Console.WriteLine("------------------------------------------------------");

            // Create the Data Objects.
            // Create the User data object with the required user details.
            UserInfo User = new UserInfo("<user>", "<vendor>", "<partner>", "<password>");

            // Create the Payflow  Connection data object with the required connection details.
            // The PAYFLOW_HOST property is defined in the App config file.
            PayflowConnectionData Connection = new PayflowConnectionData();

            RecurringInfo RecurInfo = new RecurringInfo();

            RecurInfo.OrigProfileId = "<PROFILE_ID>"; // RT0000001350
            RecurInfo.PaymentNum    = "2";            // The failed payment to be retried.

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

            // Set Amount.
            Currency Amt = new Currency(new decimal(25.12));

            Inv.Amt    = Amt;
            Inv.PoNum  = "PO12345";
            Inv.InvNum = "INV12345";

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

            Bill.BillToStreet = "123 Main St.";
            Bill.BillToZip    = "12345";
            Inv.BillTo        = Bill;
            ///////////////////////////////////////////////////////////////////

            // Create a new Recurring Payment Transaction.
            RecurringPaymentTransaction Trans = new RecurringPaymentTransaction(
                User, Connection, RecurInfo, Inv, PayflowUtility.RequestId);

            // Submit the Transaction
            Response Resp = Trans.SubmitTransaction();

            // Display the transaction response parameters.
            if (Resp != null)
            {
                // Get the Transaction Response parameters.
                TransactionResponse TrxnResponse = Resp.TransactionResponse;

                if (TrxnResponse != null)
                {
                    Console.WriteLine("RESULT = " + TrxnResponse.Result);
                    Console.WriteLine("RESPMSG = " + TrxnResponse.RespMsg);
                }

                // Get the Recurring Response parameters.
                RecurringResponse RecurResponse = Resp.RecurringResponse;
                if (RecurResponse != null)
                {
                    Console.WriteLine("RPREF = " + RecurResponse.RPRef);
                    Console.WriteLine("PROFILEID = " + RecurResponse.ProfileId);
                }

                // Display the response.
                Console.WriteLine(Environment.NewLine + PayflowUtility.GetStatus(Resp));

                // Get the Transaction Context and check for any contained SDK specific errors (optional code).
                Context TransCtx = Resp.TransactionContext;
                if (TransCtx != null && TransCtx.getErrorCount() > 0)
                {
                    Console.WriteLine(Environment.NewLine + "Transaction Errors = " + TransCtx.ToString());
                }
            }
            Console.WriteLine("Press Enter to Exit ...");
            Console.ReadLine();
        }
Пример #30
0
        public static void Main(string[] Args)
        {
            Console.WriteLine("------------------------------------------------------");
            Console.WriteLine("Executing Sample from File: DORecurringModify.cs");
            Console.WriteLine("------------------------------------------------------");

            // Create the Data Objects.
            // Create the User data object with the required user details.
            UserInfo User = new UserInfo("<user>", "<vendor>", "<partner>", "<password>");

            // Create the Payflow  Connection data object with the required connection details.
            // The PAYFLOW_HOST property is defined in the App config file.
            PayflowConnectionData Connection = new PayflowConnectionData();

            RecurringInfo RecurInfo = new RecurringInfo();

            RecurInfo.OrigProfileId = "<PROFILE_ID>";              // RT0000001350
            RecurInfo.ProfileName   = "<PROFILE_NAME>";            // Test_Profile

            // Create a new Invoice data object with the Amount, Billing Address etc. details for the data you
            // want to change.
            Invoice Inv = new Invoice();

            // Set Amount.
            Currency Amt = new Currency(new decimal(25.12));

            Inv.Amt    = Amt;
            Inv.PoNum  = "PO12345";
            Inv.InvNum = "INV12345";

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

            Bill.BillToStreet = "123 Main St.";
            Bill.BillToZip    = "12345";
            Bill.BillToEmail  = "*****@*****.**";
            Bill.BillToPhone  = "123-123-1234";
            Inv.BillTo        = Bill;

            // If you want to modify the credit card information, create a new Payment Device - Credit Card data object.
            // The input parameters are Credit Card Number and Expiration Date of the Credit Card.
            CreditCard CC = new CreditCard("5105105105105100", "0115");

            // Create a new Tender - Card Tender data object.
            CardTender Card = new CardTender(CC);

            // If NO card details available and want to modify only information like E-Mail or Phone Number, use following:
            //RecurringModifyTransaction Trans = new RecurringModifyTransaction(User, Connection, RecurInfo, Inv, null, PayflowUtility.RequestId);

            // If you want to modify the RecurringInfo information only, use the following:
            //RecurringModifyTransaction Trans = new RecurringModifyTransaction(User, Connection, RecurInfo, PayflowUtility.RequestId);

            // Create a new Recurring Modify Transaction.
            RecurringModifyTransaction Trans = new RecurringModifyTransaction(User, Connection, RecurInfo, Inv, Card, PayflowUtility.RequestId);

            // Submit the Transaction
            Response Resp = Trans.SubmitTransaction();

            // Display the transaction response parameters.
            if (Resp != null)
            {
                // Get the Transaction Response parameters.
                TransactionResponse TrxnResponse = Resp.TransactionResponse;

                if (TrxnResponse != null)
                {
                    Console.WriteLine("RESULT = " + TrxnResponse.Result);
                    Console.WriteLine("RESPMSG = " + TrxnResponse.RespMsg);
                }

                // Get the Recurring Response parameters.
                RecurringResponse RecurResponse = Resp.RecurringResponse;
                if (RecurResponse != null)
                {
                    Console.WriteLine("RPREF = " + RecurResponse.RPRef);
                    Console.WriteLine("PROFILEID = " + RecurResponse.ProfileId);
                }

                // Display the response.
                Console.WriteLine(Environment.NewLine + PayflowUtility.GetStatus(Resp));

                // Get the Transaction Context and check for any contained SDK specific errors (optional code).
                Context TransCtx = Resp.TransactionContext;
                if (TransCtx != null && TransCtx.getErrorCount() > 0)
                {
                    Console.WriteLine(Environment.NewLine + "Transaction Errors = " + TransCtx.ToString());
                }
            }
            Console.WriteLine("Press Enter to Exit ...");
            Console.ReadLine();
        }
Пример #31
0
        public static void Main(string[] Args)
        {
            Console.WriteLine("------------------------------------------------------");
            Console.WriteLine("Executing Sample from File: DOSale_Base.cs");
            Console.WriteLine("------------------------------------------------------");

            // Create the Data Objects.
            // Create the User data object with the required user details.
            UserInfo User = new UserInfo("<user>", "<vendor>", "<partner>", "<password>");

            // Create the Payflow  Connection data object with the required connection details.
            // Values of connection details can also be passed in the constructor of
            // PayflowConnectionData. This will override the values passed in the App config file.
            // Example values passed below are as follows:
            // Payflow Pro Host address : pilot-payflowpro.paypal.com
            // Payflow Pro Host Port : 443
            // Timeout : 45 ( in seconds )
            PayflowConnectionData Connection = new PayflowConnectionData("pilot-payflowpro.paypal.com", 443, 45);

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

            // Set Amount.
            Currency Amt = new Currency(new decimal(25.1256));

            Inv.Amt = Amt;
            // Truncate the Amount value using the truncate feature of
            // the Currency Data Object.
            // Note: Currency Data Object also has the Round feature
            // which will round the amount value to desired number of decimal
            // digits ( default 2 ). However, round and truncate cannot be used
            // at the same time. You can set one of round or truncate true.
            Inv.Amt.Truncate = true;
            // Set the truncation decimal digit to 2.
            Inv.Amt.NoOfDecimalDigits = 2;

            Inv.PoNum  = "PO12345";
            Inv.InvNum = "INV12345";

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

            Bill.BillToStreet = "123 Main St.";
            Bill.BillToZip    = "12345";
            Inv.BillTo        = Bill;

            // Create a new Payment Device - Credit Card data object.
            // The input parameters are Credit Card Number and Expiration Date of the Credit Card.
            CreditCard CC = new CreditCard("5105105105105100", "0115");

            CC.Cvv2 = "123";

            // Create a new Tender - Card Tender data object.
            CardTender Card = new CardTender(CC);
            ///////////////////////////////////////////////////////////////////

            // Create a new Base Transaction.
            BaseTransaction Trans = new BaseTransaction("S",
                                                        User, Connection, Inv, Card, PayflowUtility.RequestId);

            // Submit the Transaction
            Response Resp = Trans.SubmitTransaction();

            // Display the transaction response parameters.
            if (Resp != null)
            {
                // Get the Transaction Response parameters.
                TransactionResponse TrxnResponse = Resp.TransactionResponse;

                if (TrxnResponse != null)
                {
                    Console.WriteLine("RESULT = " + TrxnResponse.Result);
                    Console.WriteLine("PNREF = " + TrxnResponse.Pnref);
                    Console.WriteLine("RESPMSG = " + TrxnResponse.RespMsg);
                    Console.WriteLine("AUTHCODE = " + TrxnResponse.AuthCode);
                    Console.WriteLine("AVSADDR = " + TrxnResponse.AVSAddr);
                    Console.WriteLine("AVSZIP = " + TrxnResponse.AVSZip);
                    Console.WriteLine("IAVS = " + TrxnResponse.IAVS);
                    Console.WriteLine("CVV2MATCH = " + TrxnResponse.CVV2Match);
                }

                // Get the Fraud Response parameters.
                FraudResponse FraudResp = Resp.FraudResponse;
                // Display Fraud Response parameter
                if (FraudResp != null)
                {
                    Console.WriteLine("PREFPSMSG = " + FraudResp.PreFpsMsg);
                    Console.WriteLine("POSTFPSMSG = " + FraudResp.PostFpsMsg);
                }

                // Display the response.
                Console.WriteLine(Environment.NewLine + PayflowUtility.GetStatus(Resp));


                // Get the Transaction Context and check for any contained SDK specific errors (optional code).
                Context TransCtx = Resp.TransactionContext;
                if (TransCtx != null && TransCtx.getErrorCount() > 0)
                {
                    Console.WriteLine(Environment.NewLine + "Transaction Errors = " + TransCtx.ToString());
                }
            }
            Console.WriteLine("Press Enter to Exit ...");
            Console.ReadLine();
        }
Пример #32
0
        public override void ProcessTransaction(Transaction t)
        {
            bool result = false;

            //'Get Configuration Settings
            string MerchantPartner = Settings.MerchantPartner;
            string MerchantLogin = Settings.MerchantLogin;
            string MerchantUser = Settings.MerchantUser;
            string MerchantPassword = Settings.MerchantPassword;
            string CurrencyCode = Settings.CurrencyCode;
            bool TestMode = Settings.TestMode;
            bool DebugMode = Settings.DeveloperMode;

            UserInfo User = new UserInfo(MerchantUser, MerchantLogin, MerchantPartner, MerchantPassword);
        

            //Set HostAddress URL
            string HostAddress = LiveUrl;
            if (TestMode) HostAddress = TestUrl;

            //Connection Info
            PayflowConnectionData Connection = new PayflowConnectionData(HostAddress, 443, 45); //', CertLocation)

            // *** Create a new Invoice data object ***
            // Set Invoice object with the Amount, Billing & Shipping Address, etc. ***
            Invoice Inv = new Invoice();

            // Set the amount object. A valid amount is a two decimal value.  An invalid amount will generate a result code                
            Currency Amt = new Currency(Decimal.Round(t.Amount, 2), CurrencyCode); //' 840 is US ISO currency code.  If no code passed, 840 is default.
            Inv.Amt = Amt;

            // Generate a unique transaction ID
            string strRequestID = PayflowUtility.RequestId + t.MerchantInvoiceNumber;

            //InvNum and CustRef are sent to the processors and could show up on a customers
            // or your bank statement. These fields are reportable but not searchable in PayPal Manager.

            Inv.InvNum = t.MerchantInvoiceNumber;
            Inv.CustRef = t.Customer.Email;

            //' Comment1 and Comment2 fields are searchable within PayPal Manager .
            Inv.Comment1 = "Order Number: " + Inv.InvNum;
            Inv.Comment2 = "Customer Email: " + t.Customer.Email;

            // Create the BillTo object.
            BillTo Bill = new BillTo();

            Bill.FirstName = t.Customer.FirstName;
            Bill.LastName = t.Customer.LastName;
            Bill.Street = t.Customer.Street;
            Bill.City = t.Customer.City;
            Bill.Zip = t.Customer.PostalCode;
            Bill.PhoneNum = t.Customer.Phone;
            Bill.Email = t.Customer.Email;
            Bill.State = t.Customer.Region;                        

            //' BillToCountry code is based on numeric ISO country codes. (e.g. 840 = USA)
            //Get Country Code
            string CountryCode = MerchantTribe.Web.Geography.Country.FindByName(t.Customer.Country).IsoNumeric;
            Bill.BillToCountry = CountryCode;
        
            // Set the BillTo object into invoice.
            Inv.BillTo = Bill;

            CustomerInfo CustInfo = new CustomerInfo();

            CustInfo.CustId = t.Customer.Email;
            CustInfo.CustIP = t.Customer.IpAddress;

            // *** Create a new Payment Device - Credit Card data object. ***
            // Note: Expiration date is in the format MMYY
            string CCExpDate = t.Card.ExpirationMonthPadded + t.Card.ExpirationYearTwoDigits;

            CreditCard CC = new CreditCard(t.Card.CardNumber, CCExpDate);

            //' *** Card Security Code ***
            //' This is the 3 or 4 digit code on either side of the Credit Card.
            if (t.Card.SecurityCode.Length > 0)
            {
                CC.Cvv2 = t.Card.SecurityCode;
            }

            // Name on Credit Card is optional.
            CC.Name = t.Card.CardHolderName;

            // *** Create a new Tender - Card Tender data object. ***
            CardTender Card = new CardTender(CC);

            // *** Create a new Transaction. ***
            // The Request Id is the unique id necessary for each transaction. 
            // If you pass a non-unique request id, you will receive the transaction details from the original request.

            //'DO TRANSACTION
            try
            {
                BaseTransaction Trans = null;

                switch(t.Action)
                {
                    case ActionType.CreditCardHold:
                        Trans = new AuthorizationTransaction(User,Connection, Inv, Card, strRequestID);
                        break;
                    case ActionType.CreditCardCharge:
                        Trans = new SaleTransaction(User,Connection, Inv, Card, strRequestID);
                        break;
                    case ActionType.CreditCardCapture:
                        Trans = new CaptureTransaction(t.PreviousTransactionNumber, User, Connection, Inv, strRequestID);
                        break;
                    case ActionType.CreditCardRefund:
                        Trans = new CreditTransaction(t.PreviousTransactionNumber, User, Connection, Inv, strRequestID);
                        break;
                    case ActionType.CreditCardVoid:
                       Trans = new VoidTransaction(t.PreviousTransactionNumber, User, Connection, strRequestID);
                        break;
                }

                int Result = 0;
                System.Globalization.CultureInfo currCulture = System.Threading.Thread.CurrentThread.CurrentCulture;
                Response Resp = null;

                try
                {
                    System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture;
                    //' Submit the Transaction
                    Resp = Trans.SubmitTransaction();
                }
                finally
                {
                    System.Threading.Thread.CurrentThread.CurrentCulture = currCulture;
                }

                if (Resp != null)
                {
            
                    // Get the Transaction Response parameters.
                    TransactionResponse TrxnResponse = Resp.TransactionResponse;
                                
                    // RESULT codes returns.
                    if (TrxnResponse != null)
                    {

                        //Check for Approval (0 = approved, all else = Decline or Error)
                        Result = TrxnResponse.Result;
                        string RespMsg = TrxnResponse.RespMsg;

                        //if success then save our reference number
                        if (Result == 0)
                        {
                            t.Result.ReferenceNumber = TrxnResponse.Pnref;
                        }

                        t.Result.ResponseCode = TrxnResponse.AuthCode;

                        //Custom Properties
                        t.Result.AvsCode = AvsResponseType.Unavailable;
                        t.Result.AvsCodeDescription = "AVSADDR: " + TrxnResponse.AVSAddr + " AVSZIP: " + TrxnResponse.AVSZip + " IAVS: " + TrxnResponse.IAVS;
                        t.Result.ResponseCode = TrxnResponse.Result.ToString();
                        t.Result.CvvCode = CvnResponseType.Unavailable;
                        t.Result.CvvCodeDescription = TrxnResponse.CVV2Match;
                        t.Result.ResponseCodeDescription = TrxnResponse.RespMsg;
                        
                    }
                    else
                    {
                        t.Result.Messages.Add(new Message("Payment Error: Transaction Response is Null", "BVP_PFP_1003", MessageType.Error));
                    }

                    //Show Complete Response if Debug Mode
                    if (DebugMode)
                    {
                        t.Result.Messages.Add(new Message("PayflowPro Request:" + Trans.Request, "REQ", MessageType.Information));
                        t.Result.Messages.Add(new Message("PayflowPro Request:" + Trans.Response.ResponseString, "RES", MessageType.Information));

                        // Get the Transaction Context
                        Context TransCtx = Resp.TransactionContext;

                        if ((TransCtx != null) && (TransCtx.getErrorCount() > 0))
                        {
                            t.Result.Messages.Add(new Message("PayflowPro Context:" + TransCtx.ToString(), "CTX", MessageType.Information));
                        }
                    }

                    if (Result == 0)
                    {
                        result = true;
                    }
                    else
                    {
                        result = false;
                    }
                }
                else
                {
                    t.Result.Messages.Add(new Message("Payment Error: Response is Null", "BVP_PFP_1002", MessageType.Error));
                }
            }
            catch(Exception ex)
            {
                result = false;
                t.Result.Messages.Add(new Message("Payment Error: " + ex.Message, "BVP_PFP_1001", MessageType.Error));
                t.Result.Messages.Add(new Message("Stack Trace " + ex.StackTrace, "STACKTRACE", MessageType.Error));
            }
            
            t.Result.Succeeded = result;                     
        }
Пример #33
0
        private Invoice GetInvoice( PaymentInfo paymentInfo )
        {
            var ppBillingInfo = new BillTo();

            ppBillingInfo.FirstName = paymentInfo.FirstName;
            ppBillingInfo.LastName = paymentInfo.LastName;
            ppBillingInfo.Email = paymentInfo.Email;
            ppBillingInfo.PhoneNum = paymentInfo.Phone;
            ppBillingInfo.Street = paymentInfo.Street1;
            ppBillingInfo.BillToStreet2 = paymentInfo.Street2;
            ppBillingInfo.State = paymentInfo.State;
            ppBillingInfo.Zip = paymentInfo.PostalCode;
            ppBillingInfo.BillToCountry = paymentInfo.Country;

            if ( paymentInfo is CreditCardPaymentInfo )
            {
                var cc = paymentInfo as CreditCardPaymentInfo;
                ppBillingInfo.Street = cc.BillingStreet1;
                ppBillingInfo.BillToStreet2 = cc.BillingStreet2;
                ppBillingInfo.City = cc.BillingCity;
                ppBillingInfo.State = cc.BillingState;
                ppBillingInfo.Zip = cc.BillingPostalCode;
                ppBillingInfo.BillToCountry = cc.BillingCountry;
            }

            var ppAmount = new Currency( paymentInfo.Amount );

            var ppInvoice = new Invoice();
            ppInvoice.Amt = ppAmount;
            ppInvoice.BillTo = ppBillingInfo;

            return ppInvoice;
        }
Пример #34
0
    public RequestMessage paymentNetworkTokenizationRequest()
    {
        RequestMessage request = new RequestMessage();

        // we will let the client pick up the merchantID
        // from the config file.  In multi-merchant scenarios,
        // you would set a merchantID in each request.

        // this sample requests

        // Credit Card Authorization
        request.ccAuthService     = new CCAuthService();
        request.ccAuthService.run = "true";
        request.ccAuthService.commerceIndicator = "vbv";
        request.ccAuthService.cavv = "EHuWW9PiBkWvqE5juRwDzAUFBAk=";
        request.ccAuthService.xid  = "EHuWW9PiBkWvqE5juRwDzAUFBAk=";

        request.merchantReferenceCode = "your_merchant_reference_code";

        UCAF ucaf = new UCAF();

        ucaf.authenticationData  = "EHuWW9PiBkWvqE5juRwDzAUFBAk=";
        ucaf.collectionIndicator = "2";
        request.ucaf             = ucaf;

        BillTo billTo = new BillTo();

        billTo.firstName  = "John";
        billTo.lastName   = "Doe";
        billTo.street1    = "1295 Charleston Road";
        billTo.city       = "Mountain View";
        billTo.state      = "CA";
        billTo.postalCode = "94043";
        billTo.country    = "US";
        billTo.email      = "*****@*****.**";
        billTo.ipAddress  = "10.7.111.111";
        request.billTo    = billTo;

        Card card = new Card();

        card.accountNumber   = "4650100000000839";
        card.expirationMonth = "12";
        card.expirationYear  = "2031";
        request.card         = card;

        PurchaseTotals purchaseTotals = new PurchaseTotals();

        purchaseTotals.currency = "USD";
        request.purchaseTotals  = purchaseTotals;

        // there are two items in this sample
        request.item = new Item[2];

        Item item = new Item();

        item.id         = "0";
        item.unitPrice  = "12.34";
        request.item[0] = item;

        item            = new Item();
        item.id         = "1";
        item.unitPrice  = "56.78";
        request.item[1] = item;

        PaymentNetworkToken paymentNetworkToken = new PaymentNetworkToken();

        paymentNetworkToken.transactionType = "1";

        request.paymentNetworkToken = paymentNetworkToken;

        return(request);
    }
Пример #35
0
        public static void Main(string[] Args)
        {
            Console.WriteLine("------------------------------------------------------");
            Console.WriteLine("Executing Sample from File: DOSaleComplete.cs");
            Console.WriteLine("------------------------------------------------------");

            //
            // PLEASE READ ALL COMMENTS BELOW:
            // All information regarding the available objects within payflow_dotNET.dll can be found in the API doc
            // found under the "Docs" directory of the installed SDK.  You will also need to refer to the
            // Payflow Gateway Developer Guide and Reference found at
            // https://developer.paypal.com/docs/classic/payflow/integration-guide/
            //
            // Regarding the Request ID:
            //
            // The request Id is a unique id that you send with your transaction data.  This Id if not changed
            // will help prevent duplicate transactions.  The idea is to set this Id outside the loop or if on a page,
            // prior to the final confirmation page.
            //
            // Once the transaction is sent and if you don't receive a response you can resend the transaction and the
            // server will respond with the response data of the original submission.  Also, the object,
            // Trans.Response.TransactionResponse.Duplicate will be set to "1" if the transaction is a duplicate.
            //
            // This allows you to resend transaction requests should there be a network or user issue without re-charging
            // a customers credit card.
            //
            // COMMON ISSUES:
            //
            // Result Code 1:
            // Is usually caused by one of the following:
            //		** Invalid login information, see result code 26 below.
            //		** IP Restrictions on the account. Verify there are no IP restrictions in Manager under Service Settings.
            //
            // Result Code 26:
            // Verify USER, VENDOR, PARTNER and PASSWORD. Remember, USER and VENDOR are both the merchant login
            // ID unless a Payflow Pro USER was created.  All fields are case-sensitive.
            //
            // Receiving Communication Exceptions or No Response:
            // Since this service is based on HTTPS it is possible that due to network issues either on PayPal's side or
            // yours that you can not process a transaction.  If this is the case, what is suggested is that you put some
            // type of loop in your code to try up to X times before "giving up".  This example will try to get a response
            // up to 3 times before it fails and by using the Request ID as described above, you can do these attempts without
            // the chance of causing duplicate charges on your customer's credit card.
            //
            // END COMMENTS

            // Begin Application
            //
            // Set the Request ID
            // Uncomment the line below and run two concurrent transactions to show how duplicate works.  You will notice on
            // the second transaction that the response returned is identical to the first, but the duplicate object will be set.
            // String strRequestID = "123456";
            // Comment out this line if testing duplicate response.
            String RequestID = PayflowUtility.RequestId;

            // *** Create the Data Objects. ***
            //
            // *** Create the User data object with the required user details. ***
            //
            // Should you choose to store the login information (Vendor, User, Partner and Password) in
            // app.config, you can retrieve the data using PayflowUtility.AppSettings.
            //
            // For Example:
            //
            //      App.Config Entry: <add key="PayflowPartner" value="PayPal"/>
            //
            //      String mUser = PayflowUtility.AppSettings("PayflowUser");
            //      String mVendor = PayflowUtility.AppSettings("PayflowVendor");
            //      String mPartner = PayflowUtility.AppSettings("PayflowPartner");
            //      String mPassword = PayflowUtility.AppSettings("PayflowPassword");
            //
            // UserInfo User = new UserInfo (mUser, mVendor, mPartner, mPassword);

            // Remember: <vendor> = your merchant (login id), <user> = <vendor> unless you created a separate <user> for Payflow Pro.
            // Result code 26 will be issued if you do not provide both the <vendor> and <user> fields.

            // The other most common error with authentication is result code 1, user authentication failed.  This is usually
            // due to invalid account information or IP restriction on the account.  You can verify IP restriction by logging
            // into Manager.
            UserInfo User = new UserInfo("<user>", "<vendor>", "<partner>", "<password>");

            // *** Create the Payflow Connection data object with the required connection details. ***
            //
            // To allow the ability to change easily between the live and test servers, the PFPRO_HOST
            // property is defined in the App.config (or web.config for a web site) file.  However,
            // you can also pass these fields and others directly from the PayflowConnectionData constructor.
            // This will override the values passed in the App.config file.
            //
            // For Example:
            //
            //      Example values passed below are as follows:
            //      Payflow Pro Host address : pilot-payflowpro.paypal.com
            //      Payflow Pro Host Port : 443
            //      Timeout : 45 ( in seconds )
            //
            //      PayflowConnectionData Connection = new PayflowConnectionData("pilot-payflowpro.paypal.com", 443, 45, "",0,"","");
            //
            // Obtain Host address from the app.config file and use default values for
            // timeout and proxy settings.

            PayflowConnectionData Connection = new PayflowConnectionData();

            // *** Create a new Invoice data object ***
            // Set Invoice object with the Amount, Billing & Shipping Address, etc. ***

            Invoice Inv = new Invoice();

            // Creates a CultureInfo for English in the U.S.
            // Not necessary, just here for example of using currency formatting.
            //CultureInfo us = new CultureInfo("en-US");
            //String usCurrency = "USD";

            // Set the amount object. For Partial Authorizations, refer to the DoPartialAuth example.
            // Currency Code 840 (USD) is US ISO currency code.  If no code passed, 840 is default.
            // See the Developer's Guide for the list of the three-digit currency codes.
            //Currency Amt = new Currency(new decimal(0.00), usCurrency);
            Currency Amt = new Currency(new decimal(25.00), "USD");

            // A valid amount has either no decimal value or only a two decimal value.
            // An invalid amount will generate a result code 4.
            //
            // For values which have more than two decimal places such as:
            // Currency Amt = new Currency(new Decimal(25.1214));
            // You will either need to truncate or round as needed using the following property: Amt.NoOfDecimalDigits
            //
            // If the NoOfDecimalDigits property is used then it is mandatory to set one of the following
            // properties to true.
            //
            //Amt.Round = true;
            //Amt.Truncate = true;
            //
            // For Currencies without a decimal, you'll need to set the NoOfDecimalDigits = 0.
            //Amt.NoOfDecimalDigits = 0;
            Inv.Amt = Amt;

            Currency TaxAmt = new Currency(new decimal(0.00), "USD");

            Inv.TaxAmt = TaxAmt;

            // PONum, InvNum and CustRef are sent to the processors and could show up on a customers
            // or your bank statement. These fields are reportable but not searchable in PayPal Manager.
            Inv.PoNum   = "PO12345";
            Inv.InvNum  = "INV12345";
            Inv.CustRef = "CustRef1";

            // Merchant information is detailed data about a merchant such as the merchant's name, business address, business location identifier,
            // and contact information and is used to change the merchant's information on a customer's credit card.
            // See the section, "Submitting Soft Merchant Information" in the Payflow Pro Developer's Guide for more information.
            //MerchantInfo Merchant = new MerchantInfo();
            //Merchant.MerchantName = "MerchantXXXXX";
            //Merchant.MerchantCity = "Somewhere";
            //Inv.MerchantInfo = Merchant;
            Inv.VatTaxAmt = new Currency(new decimal(25.00), "USD");

            // Comment1 and Comment2 fields are search-able within PayPal Manager .
            // You may want to populate these fields with any of the above three fields or any other data.
            // However, the search is a case-sensitive and is a non-wild card search, so plan accordingly.

            Inv.Comment1 = "Comment1";
            Inv.Comment2 = "Comment2";

            // There are additional Invoice parameters that could assist you in obtaining a better rate
            // from your merchant bank.  Refer to the Payflow Pro Developer’s Guide1
            // and consult your Internet Merchant Bank on what parameters (if any) you can use.
            // Some of the parameters could include:
            // Inv.Recurring = "Y";
            // Inv.TaxExempt = "Y";


            // *** Create Level 2/3 Data for Purchase Card ***
            // PayPal Payment Services supports passing Purchasing Card Level 2 information (such as
            // purchase order number, tax amount, and charge description) in the settlement file.
            // If additional required invoice information and line item details are included in the transaction,
            // PayPal formats Purchasing Card Level 3 information in an appropriate format, for example,
            // EDI (Electronic Data Interchange) 810 format as required by American Express during
            // settlement processing.
            //
            // Discuss with your merchant acquiring bank to determine if you should be passing this data and
            // refer to the Payflow Gateway Developer's Guide under your processor for all valid and required
            // parameters.
            //
            //Create a line item.
            //LineItem Item = new LineItem();
            //Add info to line item.
            //Item.Amt = new Currency(new Decimal(100.00));
            //Item.Cost = new Currency(new Decimal(49.99));
            //Add line item to invoice.
            //Inv.AddLineItem(Item);
            // To add additional line items, just repeat the same statements above changing the values.

            // *** Set the Billing Address details. ***
            //
            // The billing details below except for Street and Zip are for reporting purposes only.
            // It is suggested that you pass all the billing details for enhanced reporting and as data backup.

            // Create the BillTo object.
            BillTo Bill = new BillTo();

            // Set the customer name.
            Bill.BillToFirstName   = "Joe";
            Bill.BillToMiddleName  = "M";
            Bill.BillToLastName    = "Smith";
            Bill.BillToCompanyName = "Joe's Hardware";
            // It is highly suggested that you pass at minimum Street and Zip for AVS response.
            // However, AVS is only supported by US banks and some foreign banks.  See the Payflow
            // Developer's Guide for more information.  Sending these fields could help in obtaining
            // a lower discount rate from your Internet merchant Bank.  Consult your bank for more information.
            Bill.BillToStreet  = "123 Main St.";
            Bill.BillToStreet2 = "Suite A";
            Bill.BillToCity    = "San Jose";
            Bill.BillToState   = "CA";
            Bill.BillToZip     = "12345";
            // BillToCountry code is based on numeric ISO country codes. (e.g. 840 = USA)
            // For more information, refer to the Payflow Developer's Guide.
            Bill.BillToCountry = "840";
            Bill.BillToPhone   = "555-243-7689";
            // Secondary phone numbers (could be mobile number etc).
            Bill.BillToPhone2    = "222-222-2222";
            Bill.BillToHomePhone = "555-123-9867";
            Bill.BillToFax       = "555-343-5444";
            Bill.BillToEmail     = "*****@*****.**";

            // Set the BillTo object into invoice.
            Inv.BillTo = Bill;

            // Shipping details may not be necessary if providing a service or downloadable product such as software etc.
            //
            // Set the Shipping Address details.
            // The shipping details are for reporting purposes only.
            // It is suggested that you pass all the shipping details for enhanced reporting.
            //
            // Create the ShipTo object.
            ShipTo Ship = new ShipTo();

            // To prevent an 'Address Mismatch' fraud trigger, we are shipping to the billing address.  However,
            // shipping parameters are listed.
            // Comment line below if you want a separate Ship To address.
            //Ship = Bill.Copy();

            // Uncomment statements below to send to separate Ship To address.
            // Set the recipient's name.
            // Ship.ShipToFirstName = "Sam";
            // Ship.ShipToMiddleName = "J";
            // Ship.ShipToLastName = "Spade";
            // Ship.ShipToStreet = "456 Shipping St.";
            // Ship.ShipToStreet2 = "Apt A";
            // Ship.ShipToCity = "Las Vegas";
            // Ship.ShipToState = "NV";
            // Ship.ShipToZip = "99999";
            // ShipToCountry code is based on numeric ISO country codes. (e.g. 840 = USA)
            // For more information, refer to the Payflow Pro Developer's Guide.
            // Ship.ShipToCountry = "840";
            // Ship.ShipToPhone = "555-123-1233";
            // Secondary phone numbers (could be mobile number etc).
            // Ship.ShipToPhone2 = "555-333-1222";
            // Ship.ShipToEmail = "*****@*****.**";
            // Ship.ShipFromZip = Bill.BillToZip;
            // Following 2 items are just for reporting purposes and are not required.
            // Ship.ShipCarrier = "UPS";
            // Ship.ShipMethod = "Ground";
            //Inv.ShipTo = Ship;

            // ECHODATA allows you to trigger data sent in the request to be returned in the request.
            // "ADDRESS" will return both shipping and billing address data, if sent.
            // "USER" will return User Information, set below.
            // "CUSTDATA" returns miscellaneous fields.  Refer to the developer guide.
            //Inv.EchoData = "USER";

            // ***  Create Customer Data ***
            // There are additional CustomerInfo parameters that are used for Level 2 Purchase Cards.
            // Refer to the Payflow Pro Developer’s Guide and consult with your Internet
            // Merchant Bank regarding what parameters to send.
            // Some of the parameters could include:
            //
            //CustomerInfo CustInfo = new CustomerInfo();
            //CustInfo.CustCode = "CustCode123";    // Customer Code
            //CustInfo.CustId = "CustId123";
            //CustInfo.CustIP = "255.255.255.255";  // Customer's IP Address
            //Inv.CustomerInfo = CustInfo;

            // *** Send User fields ***
            // You can send up to ten string type parameters to store temporary data (for example, variables,
            // session IDs, order numbers, and so on). These fields will be echoed back either via API response
            // or as part of the Silent / Return post if using the hosted checkout page.
            //
            // Note: UserItem1 through UserItem10 are not displayed to the customer and are not stored in
            // the PayPal transaction database.
            //
            // For these fields to echoed back in the response, you need to set the ECHODATA object.
            //UserItem nUser = new UserItem();
            //nUser.UserItem1 = "TUSER1";
            //nUser.UserItem2 = "TUSER2";
            //Inv.UserItem = nUser;

            // *** Create Soft Descriptor Data ***
            // There are additional MerchantInfo parameters that are used for Level 2 Purchase Cards
            // to change the Merchant Name and other information that is shown on a card holders statement.
            // Refer to the Payflow Gateway Developer's Guide for more information.
            //
            //MerchantInfo MerchInfo = new MerchantInfo();
            //MerchInfo.MerchantName = "My Company Name";
            //MerchInfo.MerchantCity = "My Company City";
            //Inv.MerchantInfo = MerchInfo;

            // *** Create a new Payment Device - Credit Card data object. ***
            // The input parameters are Credit Card Number and Expiration Date of the Credit Card.
            // Note: Expiration date is in the format MMYY.
            CreditCard CC = new CreditCard("4111111111111111", "0125");

            // Example of Swipe Transaction.
            // See DOSwipe.cs example for more information.
            //SwipeCard Swipe = new SwipeCard(";5105105105105100=15121011000012345678?");

            // *** Card Security Code ***
            // This is the 3 or 4 digit code on either side of the Credit Card.
            // It is highly suggested that you obtain and pass this information to help prevent fraud.
            // Sending this fields could help in obtaining a lower discount rate from your Internet merchant Bank.
            // CVV2 is not required when performing a Swipe transaction as the card is present.
            CC.Cvv2 = "123";
            // Name on Credit Card is optional and not used as part of the authorization.
            // Also, this field populates the NAME field which is the same as FIRSTNAME, so if you
            // are already populating first name, do not use this field.
            //CC.Name = "Joe Smith";

            // Card on File: Stored Credential
            // A stored credential is information, including, but not limited to, an account number or a payment token.
            // It is stored by a merchant, its agent, a payment facilitator or a staged digital wallet operator to process future transactions for a cardholder.
            // Refer to the Payflow Gateway Developer Guide for more information.
            //
            // Example:
            // CITI (CIT Initial) - Signifies that the merchant is storing the cardholder credentials for the first time in anticipation of future
            // stored credential transactions. Example: A cardholder sets up a customer profile for future purchases.
            //CC.CardonFile = "CITI";

            // *** Create a new Tender - Card Tender data object. ***
            CardTender Card = new CardTender(CC);  // credit card
            // If you are doing card-present (retail)type transactions you will want to use the swipe object.  Before doing so, verify with
            // your merchant bank that you are setup to process card-present transactions and contact Payflow support to request your account
            // be setup to process these types of transactions.  You will need to request your market seqment be changed from e-commerce (default)
            // to retail.
            //CardTender Card = new CardTender(Swipe);

            // *** Create a new Sale Transaction. ***
            // The Request Id is the unique id necessary for each transaction.  If you are performing an authorization
            // - delayed capture transaction, make sure that you pass two different unique request ids for each of the
            // transaction.
            // If you pass a non-unique request id, you will receive the transaction details from the original request.
            // The only difference is you will also receive a parameter DUPLICATE indicating this request id has been used
            // before.
            // The Request Id can be any unique number such order id, invoice number from your implementation or a random
            // id can be generated using the PayflowUtility.RequestId.
            SaleTransaction Trans = new SaleTransaction(User, Connection, Inv, Card, RequestID);

            // Used to store client information; such as your cart name, version, etc.  Only informational.
            //ClientInfo cInfo = new ClientInfo();
            //cInfo.IntegrationProduct = "Shopping Cart";
            //cInfo.IntegrationVersion = "1.0";
            //Trans.ClientInfo = cInfo;

            // Transaction results (especially values for declines and error conditions) returned by each PayPal-supported
            // processor vary in detail level and in format. The Payflow Verbosity parameter enables you to control the kind
            // and level of information you want returned.
            //
            // By default, Verbosity is set to LOW. A LOW setting causes PayPal to normalize the transaction result values.
            // Normalizing the values limits them to a standardized set of values and simplifies the process of integrating
            // the Payflow SDK.
            //
            // By setting Verbosity to HIGH, you can view the processor's raw response values along with card information. This
            // setting is more verbose than the LOW or MEDIUM setting in that it returns more detailed, processor and card specific
            // information.
            //
            // Review the chapter in the Payflow Pro Developer's Guide regarding VERBOSITY and the INQUIRY function for more details.

            // Set the transaction verbosity to HIGH to display most details.
            Trans.Verbosity = "HIGH";

            // Try to submit the transaction up to 3 times with 5 second delay.  This can be used
            // in case of network issues.  The idea here is since you are posting via HTTPS behind the scenes there
            // could be general network issues, so try a few times before you tell customer there is an issue.
            int  trxCount = 1;
            bool RespRecd = false;

            while (trxCount <= 3 && !RespRecd)
            {
                // Notice we set the request id earlier in the application and outside our loop.  This way if a response was not received
                // but PayPal processed the original request, you'll receive the original response with DUPLICATE set.

                // Submit the Transaction
                Response Resp = Trans.SubmitTransaction();

                // Uncomment line below to simulate "No Response"
                //Resp = null;

                // Display the transaction response parameters.
                if (Resp != null)
                {
                    RespRecd = true;                      // Got a response.

                    // Get the Transaction Response parameters.
                    TransactionResponse TrxnResponse = Resp.TransactionResponse;

                    // Refer to the Payflow Pro .NET API Reference Guide and the Payflow Pro Developer's Guide
                    // for explanation of the items returned and for additional information and parameters available.
                    if (TrxnResponse != null)
                    {
                        Console.WriteLine("Transaction Response:");
                        Console.WriteLine("Result Code (RESULT) = " + TrxnResponse.Result);
                        Console.WriteLine("Transaction ID (PNREF) = " + TrxnResponse.Pnref);
                        Console.WriteLine("Response Message (RESPMSG) = " + TrxnResponse.RespMsg);
                        Console.WriteLine("Authorization (AUTHCODE) = " + TrxnResponse.AuthCode);
                        Console.WriteLine("Street Address Match (AVSADDR) = " + TrxnResponse.AVSAddr);
                        Console.WriteLine("Street Zip Match (AVSZIP) = " + TrxnResponse.AVSZip);
                        Console.WriteLine("International Card (IAVS) = " + TrxnResponse.IAVS);
                        Console.WriteLine("CVV2 Match (CVV2MATCH) = " + TrxnResponse.CVV2Match);
                        Console.WriteLine("------------------------------------------------------");
                        Console.WriteLine("Credit Card Information:");
                        Console.WriteLine("Last 4-digits Credit Card Number (ACCT) = " + TrxnResponse.Acct);
                        if (TrxnResponse.CardType != null)
                        {
                            Console.Write("Card Type (CARDTYPE) = ");
                            switch (TrxnResponse.CardType)
                            {
                            case "0":
                                Console.WriteLine("Visa");
                                break;

                            case "1":
                                Console.WriteLine("MasterCard");
                                break;

                            case "2":
                                Console.WriteLine("Discover");
                                break;

                            case "3":
                                Console.WriteLine("American Express");
                                break;

                            case "4":
                                Console.WriteLine("Diner's Club");
                                break;

                            case "5":
                                Console.WriteLine("JCB");
                                break;

                            case "6":
                                Console.WriteLine("Maestro");
                                break;

                            case "S":
                                Console.WriteLine("Solo");
                                break;
                            }
                        }
                        Console.WriteLine("Billing Name (FIRSTNAME, LASTNAME) = " + TrxnResponse.FirstName + " " + TrxnResponse.LastName);
                        Console.WriteLine("------------------------------------------------------");
                        Console.WriteLine("Verbosity Response:");
                        // Displays amount formatted as currency for the CurrentCulture.
                        // Due to operating system differences, you cannot be sure what currency
                        // symbol will be used.
                        //Console.WriteLine("Amount of Transaction (AMT) = " + Convert.ToDecimal(TrxnResponse.Amt).ToString("c", us));
                        Console.WriteLine("Amount of Transaction (AMT) = " + TrxnResponse.Amt);
                        Console.WriteLine("Processor AVS (PROCAVS) = " + TrxnResponse.ProcAVS);
                        Console.WriteLine("Processor CSC (PROCCVV2) = " + TrxnResponse.ProcCVV2);
                        Console.WriteLine("Processor Result (HOSTCODE) = " + TrxnResponse.HostCode);
                        Console.WriteLine("Transaction Date/Time (TRANSTIME) = " + TrxnResponse.TransTime);
                        Console.WriteLine("Expiration Date (EXPDATE) = " + TrxnResponse.ExpDate);
                        if (TrxnResponse.TxId != null)
                        {
                            // If card is flagged as Card on file (Stored Credential) a transaction ID will be returned that is used on future reference/recurring transactions.
                            Console.WriteLine("Transaction ID (TXID) = " + TrxnResponse.TxId);
                        }
                    }

                    // Get the Fraud Response parameters.
                    // All trial accounts come with basic Fraud Protection Services enabled.
                    // Review the PayPal Manager guide to set up your Fraud Filters prior to
                    // running this sample code.
                    // If Fraud Filters are not set, you will receive a RESULT code 126.
                    FraudResponse FraudResp = Resp.FraudResponse;
                    if (FraudResp != null)
                    {
                        Console.WriteLine("------------------------------------------------------");
                        Console.WriteLine("Fraud Response:");
                        Console.WriteLine("Pre-Filters (PREFPSMSG) = " + FraudResp.PreFpsMsg);
                        Console.WriteLine("Post-Filters (POSTFPSMSG) = " + FraudResp.PostFpsMsg);
                    }

                    // The details below describe what you'd see in the raw response which can be seen in the log file.
                    //
                    // Was this a duplicate transaction, i.e. the request ID was NOT changed.
                    // Remember, a duplicate response will return the results of the original transaction which
                    // could be misleading if you are debugging your software.
                    // For Example, let's say you got a result code 4, Invalid Amount from the original request because
                    // you were sending an amount like: 1,050.98.  Since the comma is invalid, you'd receive result code 4.
                    // RESULT=4&PNREF=V18A0C24920E&RESPMSG=Invalid amount&PREFPSMSG=No Rules Triggered
                    // Now, let's say you modified your code to fix this issue and ran another transaction but did not change
                    // the request ID.  Notice the PNREF below is the same as above, but DUPLICATE=1 is now appended.
                    // RESULT=4&PNREF=V18A0C24920E&RESPMSG=Invalid amount&DUPLICATE=1
                    // This would tell you that you are receiving the results from a previous transaction.  This goes for
                    // all transactions even a Sale transaction.  In this example, let's say a customer ordered something and got
                    // a valid response and now a different customer with different credit card information orders something, but again
                    // the request ID is NOT changed, notice the results of these two sales.  In this case, you would have not received
                    // funds for the second order.
                    // First order: RESULT=0&PNREF=V79A0BC5E9CC&RESPMSG=Approved&AUTHCODE=166PNI&AVSADDR=X&AVSZIP=X&CVV2MATCH=Y&IAVS=X
                    // Second order: RESULT=0&PNREF=V79A0BC5E9CC&RESPMSG=Approved&AUTHCODE=166PNI&AVSADDR=X&AVSZIP=X&CVV2MATCH=Y&IAVS=X&DUPLICATE=1
                    // Again, notice the PNREF is from the first transaction, this goes for all the other fields as well.
                    // It is suggested that your use this to your benefit to prevent duplicate transaction from the same customer, but you want
                    // to check for DUPLICATE=1 to ensure it is not the same results as a previous one.
                    //
                    // Since we are using objects instead of the raw name-value-pairs, you'd check the Duplicate parameter of the TrxnResponse object.
                    Console.WriteLine("------------------------------------------------------");
                    Console.WriteLine("Duplicate Response:");
                    string DupMsg;
                    if (TrxnResponse.Duplicate == "1")
                    {
                        DupMsg = "Duplicate Transaction";
                    }
                    else
                    {
                        DupMsg = "Not a Duplicate Transaction";
                    }
                    Console.WriteLine(("Duplicate Transaction (DUPLICATE) = " + DupMsg));

                    // Part of accepting credit cards or PayPal is to determine what your business rules are.  Basically, what risk are you
                    // willing to take, especially with credit cards.  The code below gives you an idea of how to check the results returned
                    // so you can determine how to handle the transaction.
                    //
                    // This is not an exhaustive list of failures or issues that could arise.  Review the list of Result Code's in the
                    // Developer Guide and add logic as you deem necessary.
                    // These responses are just an example of what you can do and how you handle the response received
                    // from the bank/PayPal is dependent on your own business rules and needs.

                    string RespMsg;
                    // Evaluate Result Code
                    if (TrxnResponse.Result < 0)
                    {
                        // Transaction failed.
                        RespMsg = "There was an error processing your transaction. Please contact Customer Service." +
                                  Environment.NewLine + "Error: " + TrxnResponse.Result.ToString();
                    }
                    else if (TrxnResponse.Result == 1 || TrxnResponse.Result == 26)
                    {
                        // This is just checking for invalid login credentials.  You normally would not display this type of message.
                        // Result code 26 will be issued if you do not provide both the <vendor> and <user> fields.
                        // Remember: <vendor> = your merchant (login id), <user> = <vendor> unless you created a seperate <user> for Payflow Pro.
                        //
                        // The other most common error with authentication is result code 1, user authentication failed.  This is usually
                        // due to invalid account information or ip restriction on the account.  You can verify ip restriction by logging
                        // into Manager.  See Service Settings >> Allowed IP Addresses.  Lastly it could be you forgot the path "/transaction"
                        // on the URL.
                        RespMsg = "Account configuration issue.  Please verify your login credentials.";
                    }
                    else if (TrxnResponse.Result == 0)
                    {
                        // Example of a message you might want to display with an approved transaction.
                        RespMsg = "Your transaction was approved. Will ship in 24 hours.";

                        // Even though the transaction was approved, you still might want to check for AVS or CVV2(CSC) prior to
                        // accepting the order.  Do realize that credit cards are approved (charged) regardless of the AVS/CVV2 results.
                        // Should you decline (void) the transaction, the card will still have a temporary charge (approval) on it.
                        //
                        // Check AVS - Street/Zip
                        // In the message below it shows what failed, ie street, zip or cvv2.  To prevent fraud, it is suggested
                        // you only give a generic billing error message and not tell the card-holder what is actually wrong.  However,
                        // that decision is yours.
                        //
                        // Also, it is totally up to you on if you accept only "Y" or allow "N" or "X".  You need to decide what
                        // business logic and liability you want to accept with cards that either don't pass the check or where
                        // the bank does not participate or return a result.  Remember, AVS is mostly used in the US but some foreign
                        // banks do participate.
                        //
                        // Remember, this just an example of what you might want to do.
                        if (TrxnResponse.AVSAddr != "Y")
                        {
                            // Display message that transaction was not accepted.  At this time, you
                            // could display message that information is incorrect and redirect user
                            // to re-enter STREET and ZIP information.  However, there should be some sort of
                            // 3 strikes your out check.
                            RespMsg = "Your billing (street) information does not match. Please re-enter.";
                            // Here you might want to put in code to flag or void the transaction depending on your needs.
                        }
                        if (TrxnResponse.AVSZip != "Y")
                        {
                            // Display message that transaction was not accepted.  At this time, you
                            // could display message that information is incorrect and redirect user
                            // to re-enter STREET and ZIP information.  However, there should be some sort of
                            // 3 strikes your out check.
                            RespMsg = "Your billing (zip) information does not match. Please re-enter.";
                            // Here you might want to put in code to flag or void the transaction depending on your needs.
                        }
                        if (TrxnResponse.CVV2Match != "Y")
                        {
                            // Display message that transaction was not accepted.  At this time, you
                            // could display message that information is incorrect.  Normally, to prevent
                            // fraud you would not want to tell a customer that the 3/4 digit number on
                            // the credit card was invalid.
                            RespMsg = "Your billing (cvv2) information does not match. Please re-enter.";
                            // Here you might want to put in code to flag or void the transaction depending on your needs.
                        }
                    }
                    else if (TrxnResponse.Result == 12)
                    {
                        // Hard decline from bank.  Customer will need to use another card or payment type.
                        RespMsg = "Your transaction was declined.";
                    }
                    else if (TrxnResponse.Result == 13)
                    {
                        // Voice authorization required.  You would need to contact your merchant bank to obtain a voice authorization.  If authorization is
                        // given, you can manually enter it via Virtual Terminal in PayPal Manager or via the VoiceAuthTransaction object.
                        RespMsg = "Your Transaction is pending. Contact Customer Service to complete your order.";
                    }
                    else if (TrxnResponse.Result == 23 || TrxnResponse.Result == 24)
                    {
                        // Issue with credit card number or expiration date.
                        RespMsg = "Invalid credit card information. Please re-enter.";
                    }
                    else if (TrxnResponse.Result == 125)
                    {
                        // Using the Fraud Protection Service.
                        // This portion of code would be is you are using the Fraud Protection Service, this is for US merchants only.
                        // 125, 126 and 127 are Fraud Responses.
                        // Refer to the Payflow Pro Fraud Protection Services User's Guide or Website Payments Pro Payflow Edition - Fraud Protection Services User's Guide.
                        RespMsg = "Your Transactions has been declined. Contact Customer Service.";
                    }
                    else if (TrxnResponse.Result == 126)
                    {
                        // One of more filters were triggered.  Here you would check the fraud message returned if you
                        // want to validate data.  For example, you might have 3 filters set, but you'll allow 2 out of the
                        // 3 to consider this a valid transaction.  You would then send the request to the server to modify the
                        // status of the transaction.  Performing this function is outside the scope of this sample, refer
                        // to the Fraud Developer's Guide.
                        //
                        // Decline transaction if AVS fails.
                        if (TrxnResponse.AVSAddr != "Y" || TrxnResponse.AVSZip != "Y")
                        {
                            // Display message that transaction was not accepted.  At this time, you
                            // could display message that information is incorrect and redirect user
                            // to re-enter STREET and ZIP information.  However, there should be some sort of
                            // strikes your out check.
                            RespMsg = "Your billing information does not match.  Please re-enter.";
                        }
                        else
                        {
                            RespMsg = "Your Transaction is Under Review. We will notify you via e-mail if accepted.";
                        }
                        RespMsg = "Your Transaction is Under Review. We will notify you via e-mail if accepted.";
                    }
                    else if (TrxnResponse.Result == 127)
                    {
                        // There is an issue with checking this transaction through the fraud service.
                        // You will need to manually approve.
                        RespMsg = "Your Transaction is Under Review. We will notify you via e-mail if accepted.";
                    }
                    else
                    {
                        // Error occurred, display normalized message returned.
                        RespMsg = TrxnResponse.RespMsg;
                    }

                    // Display Message
                    Console.WriteLine("------------------------------------------------------");
                    Console.WriteLine("User/System Response:");
                    Console.WriteLine("User Message (RESPMSG) = " + RespMsg);
                    Console.WriteLine("System Message (TRXNRESPONSE.RESPMSG) = " + TrxnResponse.RespMsg);

                    // Display the status response of the transaction.
                    // This is just additional information and normally would not be used in production.
                    // Your business logic should be built around the result code returned as shown above.
                    Console.WriteLine("------------------------------------------------------");
                    Console.WriteLine("Overall Transaction Status: " + PayflowUtility.GetStatus(Resp));

                    // Get the Transaction Context and check for any contained SDK specific errors (optional code).
                    // This is not normally used in production.
                    Context TransCtx = Resp.TransactionContext;
                    if (TransCtx != null && TransCtx.getErrorCount() > 0)
                    {
                        Console.WriteLine("------------------------------------------------------");
                        Console.WriteLine("Transaction Context Errors: " + TransCtx.ToString());
                    }
                    Console.WriteLine("------------------------------------------------------");
                    Console.WriteLine("Press Enter to Exit ...");
                    Console.ReadLine();
                }
                else
                {
                    Thread.Sleep(5000);                     // let's wait 5 seconds to see if this is a temporary network issue.
                    Console.WriteLine("Retry #: " + trxCount.ToString());
                    trxCount++;
                }
            }
            if (!RespRecd)
            {
                Console.WriteLine("There is a problem obtaining an authorization for your order.");
                Console.WriteLine("Please contact Customer Support.");
                Console.WriteLine("------------------------------------------------------");
                Console.WriteLine("Press Enter to Exit ...");
                Console.ReadLine();
            }
        }
Пример #36
0
        public virtual void PrepareBillToModel(AddressModel model,
                                               BillTo address, bool excludeProperties,
                                               AddressSettings addressSettings,
                                               Func <IList <Country> > loadCountries = null,
                                               bool prePopulateWithCustomerFields    = false,
                                               Customer customer            = null,
                                               string overrideAttributesXml = "")
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            if (addressSettings == null)
            {
                throw new ArgumentNullException(nameof(addressSettings));
            }

            if (!excludeProperties && address != null)
            {
                model.Id          = address.Id;
                model.FirstName   = address.FirstName;
                model.LastName    = address.LastName;
                model.Email       = address.Email;
                model.Company     = address.Company;
                model.CountryId   = address.CountryId;
                model.CountryName = address.Country != null?_localizationService.GetLocalized(address.Country, x => x.Name) : null;

                model.StateProvinceId   = address.StateProvinceId;
                model.StateProvinceName = address.StateProvince != null?_localizationService.GetLocalized(address.StateProvince, x => x.Name) : null;

                model.County        = address.County;
                model.City          = address.City;
                model.Address1      = address.Address1;
                model.Address2      = address.Address2;
                model.ZipPostalCode = address.ZipPostalCode;
                model.PhoneNumber   = address.PhoneNumber;
                model.FaxNumber     = address.FaxNumber;
            }

            if (address == null && prePopulateWithCustomerFields)
            {
                if (customer == null)
                {
                    throw new Exception("Customer cannot be null when prepopulating an address");
                }
                model.Email         = customer.Email;
                model.FirstName     = _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.FirstNameAttribute);
                model.LastName      = _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.LastNameAttribute);
                model.Company       = _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.CompanyAttribute);
                model.Address1      = _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.StreetAddressAttribute);
                model.Address2      = _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.StreetAddress2Attribute);
                model.ZipPostalCode = _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.ZipPostalCodeAttribute);
                model.City          = _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.CityAttribute);
                model.County        = _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.CountyAttribute);
                //ignore country and state for prepopulation. it can cause some issues when posting pack with errors, etc
                //model.CountryId = _genericAttributeService.GetAttribute<int>(SystemCustomerAttributeNames.CountryId);
                //model.StateProvinceId = _genericAttributeService.GetAttribute<int>(SystemCustomerAttributeNames.StateProvinceId);
                model.PhoneNumber = _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.PhoneAttribute);
                model.FaxNumber   = _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.FaxAttribute);
            }

            //countries and states
            if (addressSettings.CountryEnabled && loadCountries != null)
            {
                var countries = loadCountries();

                if (_addressSettings.PreselectCountryIfOnlyOne && countries.Count == 1)
                {
                    model.CountryId = countries[0].Id;
                }
                else
                {
                    model.AvailableCountries.Add(new SelectListItem {
                        Text = _localizationService.GetResource("Address.SelectCountry"), Value = "0"
                    });
                }

                foreach (var c in countries)
                {
                    model.AvailableCountries.Add(new SelectListItem
                    {
                        Text     = _localizationService.GetLocalized(c, x => x.Name),
                        Value    = c.Id.ToString(),
                        Selected = c.Id == model.CountryId
                    });
                }

                if (addressSettings.StateProvinceEnabled)
                {
                    var languageId = EngineContext.Current.Resolve <IWorkContext>().WorkingLanguage.Id;
                    var states     = _stateProvinceService
                                     .GetStateProvincesByCountryId(model.CountryId.HasValue ? model.CountryId.Value : 0, languageId)
                                     .ToList();
                    if (states.Any())
                    {
                        model.AvailableStates.Add(new SelectListItem {
                            Text = _localizationService.GetResource("Address.SelectState"), Value = "0"
                        });

                        foreach (var s in states)
                        {
                            model.AvailableStates.Add(new SelectListItem
                            {
                                Text     = _localizationService.GetLocalized(s, x => x.Name),
                                Value    = s.Id.ToString(),
                                Selected = (s.Id == model.StateProvinceId)
                            });
                        }
                    }
                    else
                    {
                        var anyCountrySelected = model.AvailableCountries.Any(x => x.Selected);
                        model.AvailableStates.Add(new SelectListItem
                        {
                            Text  = _localizationService.GetResource(anyCountrySelected ? "Address.OtherNonUS" : "Address.SelectState"),
                            Value = "0"
                        });
                    }
                }
            }

            //form fields
            model.CompanyEnabled         = addressSettings.CompanyEnabled;
            model.CompanyRequired        = addressSettings.CompanyRequired;
            model.StreetAddressEnabled   = addressSettings.StreetAddressEnabled;
            model.StreetAddressRequired  = addressSettings.StreetAddressRequired;
            model.StreetAddress2Enabled  = addressSettings.StreetAddress2Enabled;
            model.StreetAddress2Required = addressSettings.StreetAddress2Required;
            model.ZipPostalCodeEnabled   = addressSettings.ZipPostalCodeEnabled;
            model.ZipPostalCodeRequired  = addressSettings.ZipPostalCodeRequired;
            model.CityEnabled            = addressSettings.CityEnabled;
            model.CityRequired           = addressSettings.CityRequired;
            model.CountyEnabled          = addressSettings.CountyEnabled;
            model.CountyRequired         = addressSettings.CountyRequired;
            model.CountryEnabled         = addressSettings.CountryEnabled;
            model.StateProvinceEnabled   = addressSettings.StateProvinceEnabled;
            model.PhoneEnabled           = addressSettings.PhoneEnabled;
            model.PhoneRequired          = addressSettings.PhoneRequired;
            model.FaxEnabled             = addressSettings.FaxEnabled;
            model.FaxRequired            = addressSettings.FaxRequired;

            //customer attribute services
            if (_addressAttributeService != null && _addressAttributeParser != null)
            {
                PrepareCustomAddressAttributes(model, address, overrideAttributesXml);
            }
            if (_addressAttributeFormatter != null && address != null)
            {
                model.FormattedCustomAddressAttributes = _addressAttributeFormatter.FormatAttributes(address.CustomAttributes);
            }
        }
Пример #37
0
        public static void Main(string[] Args)
        {
            Console.WriteLine("------------------------------------------------------");
            Console.WriteLine("Executing Sample from File: DOCredit.cs");
            Console.WriteLine("------------------------------------------------------");

            // Create the Data Objects.
            // Create the User data object with the required user details.
            UserInfo User = new UserInfo("<user>", "<vendor>", "<partner>", "<password>");

            // Create the Payflow  Connection data object with the required connection details.
            // The PAYFLOW_HOST property is defined in the App config file.
            PayflowConnectionData Connection = new PayflowConnectionData();

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

            // Set Amount.
            Currency Amt = new Currency(new decimal(25.12));

            Inv.Amt    = Amt;
            Inv.PoNum  = "PO12345";
            Inv.InvNum = "INV12345";

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

            Bill.BillToStreet = "123 Main St.";
            Bill.BillToZip    = "12345";
            Inv.BillTo        = Bill;

            // Create a new Payment Device - Credit Card data object.
            // The input parameters are Credit Card Number and Expiration Date of the Credit Card.
            CreditCard CC = new CreditCard("5105105105105100", "0115");

            // Create a new Tender - Card Tender data object.
            CardTender Card = new CardTender(CC);
            ///////////////////////////////////////////////////////////////////

            // Create a new Credit Transaction.
            // Following is an example of a independent credit type of transaction.
            CreditTransaction Trans = new CreditTransaction(User, Connection, Inv, Card,
                                                            PayflowUtility.RequestId);

            // Submit the Transaction
            Response Resp = Trans.SubmitTransaction();

            // Display the transaction response parameters.
            if (Resp != null)
            {
                // Get the Transaction Response parameters.
                TransactionResponse TrxnResponse = Resp.TransactionResponse;

                if (TrxnResponse != null)
                {
                    Console.WriteLine("RESULT = " + TrxnResponse.Result);
                    Console.WriteLine("PNREF = " + TrxnResponse.Pnref);
                    Console.WriteLine("RESPMSG = " + TrxnResponse.RespMsg);
                    Console.WriteLine("AUTHCODE = " + TrxnResponse.AuthCode);
                    Console.WriteLine("AVSADDR = " + TrxnResponse.AVSAddr);
                    Console.WriteLine("AVSZIP = " + TrxnResponse.AVSZip);
                    Console.WriteLine("IAVS = " + TrxnResponse.IAVS);
                    Console.WriteLine("CVV2MATCH = " + TrxnResponse.CVV2Match);
                    // If value is true, then the Request ID has not been changed and the original response
                    // of the original transction is returned.
                    Console.WriteLine("DUPLICATE = " + TrxnResponse.Duplicate);
                }

                // Get the Fraud Response parameters.
                FraudResponse FraudResp = Resp.FraudResponse;
                // Display Fraud Response parameter
                if (FraudResp != null)
                {
                    Console.WriteLine("PREFPSMSG = " + FraudResp.PreFpsMsg);
                    Console.WriteLine("POSTFPSMSG = " + FraudResp.PostFpsMsg);
                }

                // Display the response.
                Console.WriteLine(Environment.NewLine + PayflowUtility.GetStatus(Resp));

                // Get the Transaction Context and check for any contained SDK specific errors (optional code).
                Context TransCtx = Resp.TransactionContext;
                if (TransCtx != null && TransCtx.getErrorCount() > 0)
                {
                    Console.WriteLine(Environment.NewLine + "Transaction Errors = " + TransCtx.ToString());
                }
            }
            Console.WriteLine("Press Enter to Exit ...");
            Console.ReadLine();
        }
Пример #38
0
        public eGatewayResponse SubmitTransaction(string username, TransactionDetails details,
                                                  string description)
        {
            string requestID = PayflowUtility.RequestId;

            string user = PayflowUtility.AppSettings("PayflowUser"); 
            string vendor = PayflowUtility.AppSettings("PayflowVendor");
            string partner = PayflowUtility.AppSettings("PayflowPartner");
            string password = PayflowUtility.AppSettings("PayflowPassword");

            UserInfo userInfo = new UserInfo(user, vendor, partner, password);
            
            bool testServer;
            if (!Boolean.TryParse(PayflowUtility.AppSettings("PayflowTestServer"), out testServer))
                return eGatewayResponse.Error;
            
            string certPath = AppDomain.CurrentDomain.BaseDirectory;
            certPath += testServer ? @"bin\testcerts" : @"bin\certs";

            string host = PayflowUtility.AppSettings("PAYFLOW_HOST");

            PayflowConnectionData connection = new PayflowConnectionData(host, certPath);

            Invoice inv = new Invoice();

            string currency = PayflowUtility.AppSettings("PayflowCurrency");
            Currency amt = new Currency(details.Amount, currency);
            amt.Round = true;
            
            inv.Amt = amt;
            inv.CustRef = username;
            inv.Comment1 = username;

            BillTo bill = new BillTo();

            bill.FirstName = details.FirstName;
            bill.LastName = details.LastName;
            bill.Zip = details.Zip;
            bill.City = details.City;
            bill.State = details.State;
            bill.Street = details.Address;
            bill.PhoneNum = details.Phone;
            bill.BillToCountry = details.Country;
            
            inv.BillTo = bill;

            string cardNumber = details.CardNumber.Replace("-", String.Empty);
            
            string expMonth = details.CardExpirationMonth.ToString();
            if (expMonth.Length == 1)
                expMonth = "0" + expMonth;
            
            string expYear = details.CardExpirationYear.ToString();
            expYear = expYear.Substring(expYear.Length - 2);
            
            CreditCard cc = new CreditCard(cardNumber, expMonth + expYear);
            CardTender card = new CardTender(cc);

            SaleTransaction trans = new SaleTransaction(userInfo, connection, inv, card, requestID);

            trans.Verbosity = "MEDIUM";

            Response resp = trans.SubmitTransaction();
            if (resp != null)
            {
                Global.Logger.LogInfo("PayflowPro_SubmitTransaction_Request", resp.RequestString);
                Global.Logger.LogInfo("PayflowPro_SubmitTransaction_Response", resp.ResponseString);
                Global.Logger.LogInfo("PayflowPro_SubmitTransaction_Response_Normalized", resp.TransactionResponse.RespMsg);
                
                if (resp.TransactionResponse.Result == 0)
                {
                    int paymentHistoryID = Payments.SavePaymentHistory(username, "PayflowPro", details.Amount, description, resp.TransactionResponse.RespMsg, 1);

                    AffiliateCommission.ApplyCommission(username, paymentHistoryID, details.Amount, resp.TransactionResponse.RespMsg);

                    return eGatewayResponse.Approved;
                }
                else
                {
                    Payments.SavePaymentHistory(username, "PayflowPro", details.Amount, description, resp.TransactionResponse.RespMsg, 2);
                    return eGatewayResponse.Error;
                }
            }
            
            return eGatewayResponse.Error;
        }
Пример #39
0
        static void Main(string[] args)
        {
            var request = new RequestMessage();

            // request.merchantID = "sqid_payments_sandbox";
            request.merchantReferenceCode = Guid.NewGuid().ToString();


            request.ccAuthService        = new CCAuthService();
            request.ccAuthService.run    = "true";
            request.ccCaptureService     = new CCCaptureService();
            request.ccCaptureService.run = "true";

            var billTo = new BillTo();

            billTo.firstName  = "Jane";
            billTo.lastName   = "Smith";
            billTo.email      = "*****@*****.**";
            billTo.country    = "US";
            billTo.city       = "Mountain View";
            billTo.street1    = "1295 Charleston Road";
            billTo.state      = "CA";
            billTo.postalCode = "94043";
            request.billTo    = billTo;

            var card = new Card();

            card.accountNumber   = "4111111111111111";
            card.expirationMonth = "12";
            card.expirationYear  = "2020";
            request.card         = card;

            var purchaseTotals = new PurchaseTotals();

            purchaseTotals.currency = "USD";
            request.purchaseTotals  = purchaseTotals;

            request.item = new Item[1];
            var item = new Item
            {
                id        = "0",
                unitPrice = "29.95"
            };

            request.item[0] = item;

            try
            {
                ReplyMessage reply = SoapClient.RunTransaction(request);
                SaveOrderState();
                ProcessReply(reply);
            }
            catch (CryptographicException ce)
            {
                SaveOrderState();
                Console.WriteLine(ce.ToString());
            }
            catch (WebException we)
            {
                SaveOrderState();

                Console.WriteLine(we.ToString());
            }

            Console.WriteLine("Press Return to end...");
            Console.ReadLine();
        }
Пример #40
0
        public static void Main(string[] Args)
        {
            Console.WriteLine("------------------------------------------------------");
            Console.WriteLine("Executing Sample from File: DOSecureTokenAuth.cs");
            Console.WriteLine("------------------------------------------------------");

            // Create the Data Objects.
            // Create the User data object with the required user details.
            // UserInfo User = new UserInfo("<user>", "<vendor>", "<partner>", "<password>");


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

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

            // Set Amount.  The amount cannot be changed once submitted.
            Currency Amt = new Currency(new decimal(25.00), "USD");

            Inv.Amt    = Amt;
            Inv.InvNum = "INV12345";

            // Set the Billing Address details.  You can also send the shipping information.  Both the Billing
            // and Shipping information can be changed if the functionality is allowed in the Configuration section
            // of Manager.  No other information submitted using a secure token call can be changed.
            BillTo Bill = new BillTo();

            Bill.BillToFirstName = "Sam";
            Bill.BillToLastName  = "Smith";
            Bill.BillToStreet    = "123 Main St.";
            Bill.BillToCity      = "Anytown";
            Bill.BillToState     = "CA";
            Bill.BillToZip       = "12345";
            Bill.BillToPhone     = "408-123-1234";
            Bill.BillToEmail     = "*****@*****.**";
            Bill.BillToCountry   = "124";
            Inv.BillTo           = Bill;

            // Create a new Payment Device - Credit Card data object.
            // The input parameters are Credit Card Number and Expiration Date of the Credit Card.
            //CreditCard CC = new CreditCard("5105105105105100", "0110");
            //CC.Cvv2 = "023";

            // Create a new Tender - Card Tender data object.
            //CardTender Card = new CardTender(CC);
            ///////////////////////////////////////////////////////////////////

            // Since we are using the hosted payment pages, you will not be sending the credit card data with the
            // Secure Token Request.  You just send all other 'sensitive' data within this request and when you
            // call the hosted payment pages, you'll only need to pass the SECURETOKEN; which is generated and returned
            // and the SECURETOKENID that was created and used in the request.
            //
            // Create a new Secure Token Authorization Transaction.  Even though this example is performing
            // an authorization, you can create a secure token using SaleTransaction too.  Only Authorization and Sale
            // type transactions are permitted.
            //
            // Remember, all data submitted as part of the Secure Token call cannot be modified at a later time.  The only exception
            // is the billing and shipping information if these items are selection in the Setup section in PayPal Manager.
            AuthorizationTransaction Trans = new AuthorizationTransaction(User, Connection, Inv, null, PayflowUtility.RequestId);

            // Set VERBOSITY to High
            Trans.Verbosity = "High";

            // Set the flag to create a Secure Token.
            Trans.CreateSecureToken = "Y";
            // The Secure Token Id must be a unique id up to 36 characters.  Using the RequestID object to
            // generate a random id, but any means to create an id can be used.
            Trans.SecureTokenId = PayflowUtility.RequestId;

            // Set the extended data value.
            ExtendData ExtData = new ExtendData("SILENTTRAN", "True");

            // Add extended data to transaction.
            Trans.AddToExtendData(ExtData);

            // IMPORTANT NOTE:
            //
            // Remember, the Secure Token can only be used once.  Once it is redeemed by a valid transaction it cannot be used again and you will
            // need to generate a new token.  Also, the token has a life time of 30 minutes.

            // Submit the Transaction
            Response Resp = Trans.SubmitTransaction();

            // Display the transaction response parameters.
            if (Resp != null)
            {
                // Get the Transaction Response parameters.
                TransactionResponse TrxnResponse = Resp.TransactionResponse;

                if (TrxnResponse != null)
                {
                    Console.WriteLine("RESULT = " + TrxnResponse.Result);
                    Console.WriteLine("RESPMSG = " + TrxnResponse.RespMsg);
                    Console.WriteLine("SECURETOKEN = " + TrxnResponse.SecureToken);
                    Console.WriteLine("SECURETOKENID = " + TrxnResponse.SecureTokenId);
                    // If value is true, then the Request ID has not been changed and the original response
                    // of the original transction is returned.
                    Console.WriteLine("DUPLICATE = " + TrxnResponse.Duplicate);
                }

                if (TrxnResponse.Result == 0)
                {
                    Console.WriteLine(Environment.NewLine + "Transaction was successful.");
                    Console.WriteLine(Environment.NewLine + "The next step would be to redirect to PayPal to display the hosted");
                    Console.WriteLine("checkout page to allow your customer to select and enter payment.");
                    Console.WriteLine(Environment.NewLine + "This is only a simple example, which does not take into account things like");
                    Console.WriteLine(Environment.NewLine + "RETURN or SILENT POST URL, etc.");
                    Console.WriteLine(Environment.NewLine + "Press <Enter> to redirect to PayPal.");
                    Console.ReadLine();
                    // Simple way to pass token data to Payflow Link Servers.
                    String PayPalUrl = "https://payflowlink.paypal.com?securetoken=" + TrxnResponse.SecureToken + "&securetokenid=" + TrxnResponse.SecureTokenId + "&MODE=test&USER1=testuser1&ACCT=5105105105105100&EXPDATE=1212&CVV2=123";
                    //Process.Start(PayPalUrl);  // Open default browser.
                    Process.Start("iexplore.exe", PayPalUrl);
                    //Process.Start("C:\\Program Files\\Mozilla Firefox\\firefox.exe", PayPalUrl);
                }

                // Display the response.
                Console.WriteLine(Environment.NewLine + PayflowUtility.GetStatus(Resp));

                // Get the Transaction Context and check for any contained SDK specific errors (optional code).
                Context TransCtx = Resp.TransactionContext;
                if (TransCtx != null && TransCtx.getErrorCount() > 0)
                {
                    Console.WriteLine(Environment.NewLine + "Transaction Errors = " + TransCtx.ToString());
                }
            }
            Console.WriteLine("Press Enter to Exit ...");
            Console.ReadLine();
        }