private DoDirectPaymentReq GetDoDirectPaymentRequest(ProcessPaymentEvaluationContext context)
        {
            var retVal = new DoDirectPaymentReq();

            retVal.DoDirectPaymentRequest         = new DoDirectPaymentRequestType();
            retVal.DoDirectPaymentRequest.Version = GetApiVersion();
            var details = new DoDirectPaymentRequestDetailsType();

            retVal.DoDirectPaymentRequest.DoDirectPaymentRequestDetails = details;
            details.PaymentAction = PaymentActionCodeType.SALE;

            //credit card
            details.CreditCard = GetCreditCardDetails(context);


            //order totals
            details.PaymentDetails                       = new PaymentDetailsType();
            details.PaymentDetails.OrderTotal            = new BasicAmountType();
            details.PaymentDetails.OrderTotal.value      = FormatMoney(context.Payment.Sum);
            details.PaymentDetails.OrderTotal.currencyID = (CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), context.Order.Currency.ToString());
            details.PaymentDetails.Custom                = context.Order.Id;
            details.PaymentDetails.ButtonSource          = "Virto_SP";

            return(retVal);
        }
        private DoDirectPaymentReq GetDoDirectPaymentRequest()
        {
            var retVal = new DoDirectPaymentReq();

            retVal.DoDirectPaymentRequest         = new DoDirectPaymentRequestType();
            retVal.DoDirectPaymentRequest.Version = "117";
            var details = new DoDirectPaymentRequestDetailsType();

            retVal.DoDirectPaymentRequest.DoDirectPaymentRequestDetails = details;
            details.PaymentAction = PaymentActionCodeType.SALE;

            //credit card
            details.CreditCard = GetCreditCardDetails();


            //order totals
            details.PaymentDetails                       = new PaymentDetailsType();
            details.PaymentDetails.OrderTotal            = new BasicAmountType();
            details.PaymentDetails.OrderTotal.value      = "845.24";
            details.PaymentDetails.OrderTotal.currencyID = (CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), "USD");
            details.PaymentDetails.Custom                = "context.Order.Id";
            details.PaymentDetails.ButtonSource          = "Virto_SP";

            return(retVal);
        }
Esempio n. 3
0
        /**
         *
         */
        public DoDirectPaymentResponseType DoDirectPayment(DoDirectPaymentReq DoDirectPaymentReq, string apiUsername)
        {
            setStandardParams(DoDirectPaymentReq.DoDirectPaymentRequest);
            string resp = call("DoDirectPayment", DoDirectPaymentReq.toXMLString(), apiUsername);

            return(new DoDirectPaymentResponseType(resp));
        }
        /**
         * AUTO_GENERATED
         */
        public DoDirectPaymentResponseType DoDirectPayment(DoDirectPaymentReq doDirectPaymentReq, string apiUserName)
        {
            setStandardParams(doDirectPaymentReq.DoDirectPaymentRequest);
            string      response    = Call("DoDirectPayment", doDirectPaymentReq.ToXMLString(), apiUserName);
            XmlDocument xmlDocument = new XmlDocument();

            xmlDocument.LoadXml(response);
            XmlNode xmlNode = xmlDocument.SelectSingleNode("*[local-name()='Envelope']/*[local-name()='Body']/*[local-name()='DoDirectPaymentResponse']");

            return(new DoDirectPaymentResponseType(xmlNode));
        }
Esempio n. 5
0
        private void DoDirectPayment(HttpContext context)
        {
            DoDirectPaymentReq req = new DoDirectPaymentReq();

            req.DoDirectPaymentRequest = new DoDirectPaymentRequestType();
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails                              = new DoDirectPaymentRequestDetailsType();
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard                   = new CreditCardDetailsType();
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.PaymentDetails               = new PaymentDetailsType();
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.PaymentDetails.OrderTotal    = new BasicAmountType();
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.PaymentDetails.ShipToAddress = new AddressType();
            req.DoDirectPaymentRequest.Version = "78.0";
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.CreditCardNumber = context.Request.Params["cardNum"];
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.CreditCardType   = (CreditCardTypeType)EnumUtils.getValue(context.Request.Params["creditcardType"], typeof(CreditCardTypeType));
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.CVV2             = context.Request.Params["cvv2Num"];
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.ExpMonth         = System.Convert.ToInt32(context.Request.Params["expDateMonth"]);
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.ExpYear          = System.Convert.ToInt32(context.Request.Params["expDateYear"]);
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.PaymentAction = (PaymentActionCodeType)EnumUtils.getValue(context.Request.Params["paymentType"], typeof(PaymentActionCodeType));
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.PaymentDetails.OrderTotal.currencyID         = (CurrencyCodeType)EnumUtils.getValue(context.Request.Params["currencyCode"], typeof(CurrencyCodeType));
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.PaymentDetails.OrderTotal.value              = context.Request.Params["amount"];
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.PaymentDetails.ShipToAddress.Street1         = context.Request.Params["addr1"];
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.PaymentDetails.ShipToAddress.Street2         = context.Request.Params["addr2"];
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.PaymentDetails.ShipToAddress.CityName        = context.Request.Params["city"];
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.PaymentDetails.ShipToAddress.StateOrProvince = context.Request.Params["state"];
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.PaymentDetails.ShipToAddress.PostalCode      = context.Request.Params["zipCode"];
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.PaymentDetails.ShipToAddress.Country         = (CountryCodeType)EnumUtils.getValue(context.Request.Params["countryCode"], typeof(CountryCodeType));
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.PaymentDetails.ShipToAddress.Name            = context.Request.Params["firstName"] + context.Request.Params["lastName"];
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.CardOwner                         = new PayerInfoType();
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.CardOwner.PayerName               = new PersonNameType();
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.CardOwner.PayerCountry            = (CountryCodeType)EnumUtils.getValue(context.Request.Params["countryCode"], typeof(CountryCodeType));
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.CardOwner.PayerName.FirstName     = context.Request.Params["firstName"];
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.CardOwner.PayerName.LastName      = context.Request.Params["lastName"];
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.CardOwner.Address                 = new AddressType();
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.CardOwner.Address.Street1         = context.Request.Params["addr1"];
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.CardOwner.Address.Street2         = context.Request.Params["addr2"];
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.CardOwner.Address.CityName        = context.Request.Params["city"];
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.CardOwner.Address.StateOrProvince = context.Request.Params["state"];
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.CardOwner.Address.PostalCode      = context.Request.Params["zipCode"];
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.CardOwner.Address.Country         = (CountryCodeType)EnumUtils.getValue(context.Request.Params["countryCode"], typeof(CountryCodeType));
            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.CardOwner.Address.Name            = context.Request.Params["firstName"] + context.Request.Params["lastName"];
            try
            {
                PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService();
                DoDirectPaymentResponseType      resp    = service.DoDirectPayment(req);
                context.Response.Write("<html><body><textarea rows=30 cols=80>");
                ObjectDumper.Write(resp, 5, context.Response.Output);
                context.Response.Write("</textarea></body></html>");
            }
            catch (System.Exception e)
            {
                context.Response.Write(e.Message);
            }
        }
        private static DoDirectPaymentResponseType MakePayment(PaymentModel paymentModel)
        {
            // Create request object
            var request        = new DoDirectPaymentRequestType();
            var requestDetails = new DoDirectPaymentRequestDetailsType();

            request.DoDirectPaymentRequestDetails = requestDetails;

            var creditCard = new CreditCardDetailsType();

            requestDetails.CreditCard = creditCard;
            var payer = new PayerInfoType();

            // (Optional) First and last name of buyer.
            PersonNameType name = new PersonNameType();

            name.FirstName  = string.Format("{0} {1}", SessionWrapper.LoggedUser.FirstName, SessionWrapper.LoggedUser.LastName);
            name.LastName   = SessionWrapper.LoggedUser.Email; //pass buyer email address.
            payer.PayerName = name;

            creditCard.CardOwner = payer;

            creditCard.CreditCardNumber = paymentModel.CreditCardModel.CardNumber;

            creditCard.CreditCardType = (CreditCardTypeType)
                                        Enum.Parse(typeof(CreditCardTypeType), paymentModel.CreditCardModel.CardType.ToUpper());
            creditCard.CVV2 = paymentModel.CreditCardModel.SecurityCode;

            creditCard.ExpMonth = Convert.ToInt32(paymentModel.CreditCardModel.ExpMonth);
            creditCard.ExpYear  = Convert.ToInt32(paymentModel.CreditCardModel.ExpYear);

            requestDetails.PaymentDetails = new PaymentDetailsType();


            CurrencyCodeType currency = (CurrencyCodeType)
                                        Enum.Parse(typeof(CurrencyCodeType), "USD");
            var paymentAmount = new BasicAmountType(currency, paymentModel.OrderDetailModel.TotalOrder.ToString());

            requestDetails.PaymentDetails.OrderTotal = paymentAmount;

            // Invoke the API
            var wrapper = new DoDirectPaymentReq();

            wrapper.DoDirectPaymentRequest = request;

            var service = new PayPalAPIInterfaceServiceService();

            // API call
            return(service.DoDirectPayment(wrapper));
        }
Esempio n. 7
0
        public ChargeResult DoPayment(string CCNumber, Int32 Amount, string FirstName, string LastName, string Address, string City, string Zip, string State, string Country, string Telephone, string DOB, string EmailAddress, string CardHolderName, string ExpiryMonth, string ExpiryYear, string CVC2, String Currency)
        {
            // CreditCardDetailsType cardDetails = MapCardDetails(CCNumber, FirstName, LastName, Address, City, Zip, State, Country, Telephone, DOB, EmailAddress, CardHolderName, ExpiryMonth, ExpiryYear, CVC2);
            DoDirectPaymentResponseType result;

            using (var _client = new PayPalAPIAAInterfaceClient())
            {
                DoDirectPaymentRequestType pp_Request = new DoDirectPaymentRequestType();
                pp_Request.Version = "TODO set Version";
                pp_Request.DoDirectPaymentRequestDetails           = new DoDirectPaymentRequestDetailsType();
                pp_Request.DoDirectPaymentRequestDetails.IPAddress = "115.187.229.184";
                //  pp_Request.DoDirectPaymentRequestDetails.CreditCard = cardDetails;

                // NOTE: The only currency supported by the Direct Payment API at this time is US dollars (USD)..
                pp_Request.DoDirectPaymentRequestDetails.PaymentDetails.OrderTotal.currencyID = CurrencyCodeType.USD;
                pp_Request.DoDirectPaymentRequestDetails.PaymentDetails.OrderTotal.Value      = Amount.ToString();

                var dp = new DoDirectPaymentReq
                {
                    DoDirectPaymentRequest = pp_Request
                };

                var credentials = new CustomSecurityHeaderType
                {
                    Credentials = new UserIdPasswordType
                    {
                        Username  = "******",
                        Password  = "******",
                        Signature = "signature",
                        AppId     = "ApiId"
                    }
                };

                result = _client.DoDirectPayment(ref credentials, dp);
            }
            var chargeResult = new ChargeResult();

            if (result != null && result.Errors.Count() > 0)
            {
                chargeResult.failure_code    = result.Errors[0].ErrorCode;
                chargeResult.failure_message = result.Errors[0].ShortMessage;
            }

            chargeResult.Id = result.TransactionID;

            return(chargeResult);
        }
        private static DoDirectPaymentResponseType MakePayment(PaymentWalletModal paymentModel)
        {
            // Create request object
            var request        = new DoDirectPaymentRequestType();
            var requestDetails = new DoDirectPaymentRequestDetailsType();

            request.DoDirectPaymentRequestDetails = requestDetails;

            var creditCard = new CreditCardDetailsType();

            requestDetails.CreditCard = creditCard;
            var payer = new PayerInfoType();

            creditCard.CardOwner = payer;

            creditCard.CreditCardNumber = paymentModel.CardNumber;

            creditCard.CreditCardType = (CreditCardTypeType)
                                        Enum.Parse(typeof(CreditCardTypeType), paymentModel.CardType.ToUpper());
            creditCard.CVV2 = paymentModel.SecurityCode;

            creditCard.ExpMonth = Convert.ToInt32(paymentModel.ExpMonth);
            creditCard.ExpYear  = Convert.ToInt32(paymentModel.ExpYear);

            requestDetails.PaymentDetails = new PaymentDetailsType();

            CurrencyCodeType currency = (CurrencyCodeType)
                                        Enum.Parse(typeof(CurrencyCodeType), "USD");
            var paymentAmount = new BasicAmountType(currency, paymentModel.Amount);

            requestDetails.PaymentDetails.OrderTotal = paymentAmount;

            // Invoke the API
            var wrapper = new DoDirectPaymentReq();

            wrapper.DoDirectPaymentRequest = request;

            var service = new PayPalAPIInterfaceServiceService();

            // API call
            return(service.DoDirectPayment(wrapper));
        }
        protected void Submit_Click(object sender, EventArgs e)
        {
            // Create request object
            DoDirectPaymentRequestType        request        = new DoDirectPaymentRequestType();
            DoDirectPaymentRequestDetailsType requestDetails = new DoDirectPaymentRequestDetailsType();

            request.DoDirectPaymentRequestDetails = requestDetails;

            // (Optional) How you want to obtain payment. It is one of the following values:
            // * Authorization – This payment is a basic authorization subject to settlement with PayPal Authorization and Capture.
            // * Sale – This is a final sale for which you are requesting payment (default).
            // Note: Order is not allowed for Direct Payment.
            requestDetails.PaymentAction = (PaymentActionCodeType)
                                           Enum.Parse(typeof(PaymentActionCodeType), paymentType.SelectedValue);

            // (Required) Information about the credit card to be charged.
            CreditCardDetailsType creditCard = new CreditCardDetailsType();

            requestDetails.CreditCard = creditCard;
            PayerInfoType payer = new PayerInfoType();
            // (Optional) First and last name of buyer.
            PersonNameType name = new PersonNameType();

            name.FirstName  = firstName.Value;
            name.LastName   = lastName.Value;
            payer.PayerName = name;
            // (Required) Details about the owner of the credit card.
            creditCard.CardOwner = payer;

            // (Required) Credit card number.
            creditCard.CreditCardNumber = creditCardNumber.Value;
            // (Optional) Type of credit card. For UK, only Maestro, MasterCard, Discover, and Visa are allowable. For Canada, only MasterCard and Visa are allowable and Interac debit cards are not supported. It is one of the following values:
            // * Visa
            // * MasterCard
            // * Discover
            // * Amex
            // * Maestro: See note.
            // Note: If the credit card type is Maestro, you must set currencyId to GBP. In addition, you must specify either StartMonth and StartYear or IssueNumber.
            creditCard.CreditCardType = (CreditCardTypeType)
                                        Enum.Parse(typeof(CreditCardTypeType), creditCardType.SelectedValue);
            // Card Verification Value, version 2. Your Merchant Account settings determine whether this field is required. To comply with credit card processing regulations, you must not store this value after a transaction has been completed.
            // Character length and limitations: For Visa, MasterCard, and Discover, the value is exactly 3 digits. For American Express, the value is exactly 4 digits.
            creditCard.CVV2 = cvv2Number.Value;
            string[] cardExpiryDetails = cardExpiryDate.Text.Split(new char[] { '/' });
            if (cardExpiryDetails.Length == 2)
            {
                // (Required) Credit card expiration month.
                creditCard.ExpMonth = Convert.ToInt32(cardExpiryDetails[0]);
                // (Required) Credit card expiration year.
                creditCard.ExpYear = Convert.ToInt32(cardExpiryDetails[1]);
            }

            requestDetails.PaymentDetails = new PaymentDetailsType();
            // (Optional) Your URL for receiving Instant Payment Notification (IPN) about this transaction. If you do not specify this value in the request, the notification URL from your Merchant Profile is used, if one exists.
            // Important: The notify URL applies only to DoExpressCheckoutPayment. This value is ignored when set in SetExpressCheckout or GetExpressCheckoutDetails.
            requestDetails.PaymentDetails.NotifyURL = ipnNotificationUrl.Value.Trim();

            // (Optional) Buyer's shipping address information.
            AddressType billingAddr = new AddressType();

            if (firstName.Value != string.Empty && lastName.Value != string.Empty &&
                street1.Value != string.Empty && country.Value != string.Empty)
            {
                billingAddr.Name = payerName.Value;
                // (Required) First street address.
                billingAddr.Street1 = street1.Value;
                // (Optional) Second street address.
                billingAddr.Street2 = street2.Value;
                // (Required) Name of city.
                billingAddr.CityName = city.Value;
                // (Required) State or province.
                billingAddr.StateOrProvince = state.Value;
                // (Required) Country code.
                billingAddr.Country = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), country.Value);
                // (Required) U.S. ZIP code or other country-specific postal code.
                billingAddr.PostalCode = postalCode.Value;

                // (Optional) Phone number.
                billingAddr.Phone = phone.Value;

                payer.Address = billingAddr;
            }

            // (Required) The total cost of the transaction to the buyer. If shipping cost and tax charges are known, include them in this value. If not, this value should be the current subtotal of the order. If the transaction includes one or more one-time purchases, this field must be equal to the sum of the purchases. This field must be set to a value greater than 0.
            // Note: You must set the currencyID attribute to one of the 3-character currency codes for any of the supported PayPal currencies.
            CurrencyCodeType currency = (CurrencyCodeType)
                                        Enum.Parse(typeof(CurrencyCodeType), currencyCode.SelectedValue);
            BasicAmountType paymentAmount = new BasicAmountType(currency, amount.Value);

            requestDetails.PaymentDetails.OrderTotal = paymentAmount;

            // Invoke the API
            DoDirectPaymentReq wrapper = new DoDirectPaymentReq();

            wrapper.DoDirectPaymentRequest = request;

            // Configuration map containing signature credentials and other required configuration.
            // For a full list of configuration parameters refer in wiki page
            // [https://github.com/paypal/sdk-core-dotnet/wiki/SDK-Configuration-Parameters]
            Dictionary <string, string> configurationMap = Configuration.GetAcctAndConfig();

            // Create the PayPalAPIInterfaceServiceService service object to make the API call
            PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(configurationMap);

            // # API call
            // Invoke the DoDirectPayment method in service wrapper object
            DoDirectPaymentResponseType response = service.DoDirectPayment(wrapper);

            // Check for API return status
            setKeyResponseObjects(service, response);
        }
        public Response PerformRequest(Request request)
        {
            // Create request object
            DoDirectPaymentRequestType paypalRequest = new DoDirectPaymentRequestType();

            DoDirectPaymentRequestDetailsType requestDetails = new DoDirectPaymentRequestDetailsType();

            paypalRequest.DoDirectPaymentRequestDetails = requestDetails;

            // (Optional) How you want to obtain payment. It is one of the following values:
            // * Authorization – This payment is a basic authorization subject to settlement with PayPal Authorization and Capture.
            // * Sale – This is a final sale for which you are requesting payment (default).
            // Note: Order is not allowed for Direct Payment.
            requestDetails.PaymentAction = (PaymentActionCodeType)
                                           Enum.Parse(typeof(PaymentActionCodeType), gatewaySettings.PaymentAction.ToUpper());

            // (Required) Information about the credit card to be charged.
            CreditCardDetailsType creditCard = new CreditCardDetailsType();

            requestDetails.CreditCard = creditCard;
            PayerInfoType payer = new PayerInfoType();
            // (Optional) First and last name of buyer.
            PersonNameType name = new PersonNameType();

            name.FirstName  = request.FirstName;
            name.LastName   = request.LastName;
            payer.PayerName = name;

            // (Required) Details about the owner of the credit card.
            creditCard.CardOwner = payer;

            // (Required) Credit card number.
            creditCard.CreditCardNumber = request.CardNumber;
            // (Optional) Type of credit card. For UK, only Maestro, MasterCard, Discover, and Visa are allowable. For Canada, only MasterCard and Visa are allowable and Interac debit cards are not supported. It is one of the following values:
            // * Visa
            // * MasterCard
            // * Discover
            // * Amex
            // * Maestro: See note.
            // Note: If the credit card type is Maestro, you must set currencyId to GBP. In addition, you must specify either StartMonth and StartYear or IssueNumber.
            creditCard.CreditCardType = (CreditCardTypeType)
                                        Enum.Parse(typeof(CreditCardTypeType), UpdateCreditCardType(request.CardType));
            // Card Verification Value, version 2. Your Merchant Account settings determine whether this field is required. To comply with credit card processing regulations, you must not store this value after a transaction has been completed.
            // Character length and limitations: For Visa, MasterCard, and Discover, the value is exactly 3 digits. For American Express, the value is exactly 4 digits.
            creditCard.CVV2 = request.CardCvv;
            // (Required) Credit card expiration month.
            creditCard.ExpMonth = request.ExpireDate.Month;
            // (Required) Credit card expiration year.
            creditCard.ExpYear = request.ExpireDate.Year;

            requestDetails.PaymentDetails = new PaymentDetailsType();
            // (Optional) Your URL for receiving Instant Payment Notification (IPN) about this transaction. If you do not specify this value in the request, the notification URL from your Merchant Profile is used, if one exists.
            // Important: The notify URL applies only to DoExpressCheckoutPayment. This value is ignored when set in SetExpressCheckout or GetExpressCheckoutDetails.
            //requestDetails.PaymentDetails.NotifyURL = "";

            // (Optional) Buyer's shipping address information.
            AddressType billingAddr = new AddressType();

            billingAddr.Name = request.FirstName + " " + request.LastName;
            // (Required) First street address.
            billingAddr.Street1 = request.Address1;
            // (Optional) Second street address.
            billingAddr.Street2 = request.Address2;
            // (Required) Name of city.
            billingAddr.CityName = request.City;
            // (Required) State or province.
            billingAddr.StateOrProvince = request.State;
            // (Required) Country code.
            billingAddr.Country = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), request.Country);
            // (Required) U.S. ZIP code or other country-specific postal code.
            billingAddr.PostalCode = request.ZipCode;

            // (Optional) Phone number.
            billingAddr.Phone = request.Phone;

            payer.Address = billingAddr;

            AddressType shippingAddr = new AddressType();

            shippingAddr.Name            = request.ShipToFirstName + " " + request.ShipToLastName;
            shippingAddr.Street1         = request.ShipToAddress;
            shippingAddr.CityName        = request.ShipToCity;
            shippingAddr.StateOrProvince = request.ShipToState;
            shippingAddr.PostalCode      = request.ShipToZipCode;
            shippingAddr.Country         = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), request.ShipToCountry);

            requestDetails.PaymentDetails.ShipToAddress = shippingAddr;

            // (Required) The total cost of the transaction to the buyer. If shipping cost and tax charges are known, include them in this value. If not, this value should be the current subtotal of the order. If the transaction includes one or more one-time purchases, this field must be equal to the sum of the purchases. This field must be set to a value greater than 0.
            // Note: You must set the currencyID attribute to one of the 3-character currency codes for any of the supported PayPal currencies.
            CurrencyCodeType currency = (CurrencyCodeType)
                                        Enum.Parse(typeof(CurrencyCodeType), gatewaySettings.CurrencyCode);

            BasicAmountType paymentAmount = new BasicAmountType(currency, request.Amount.ToString("N2"));

            requestDetails.PaymentDetails.OrderTotal    = paymentAmount;
            requestDetails.PaymentDetails.ItemTotal     = new BasicAmountType(currency, Convert.ToDouble(request.SubTotal ?? "0").ToString("N2"));
            requestDetails.PaymentDetails.ShippingTotal = new BasicAmountType(currency, Convert.ToDouble(request.ShippingTotal ?? "0").ToString("N2"));
            requestDetails.PaymentDetails.TaxTotal      = new BasicAmountType(currency, Convert.ToDouble(request.Tax ?? "0").ToString("N2"));

            // add skus
            List <PaymentDetailsItemType> items = new List <PaymentDetailsItemType>();

            foreach (PaymentSku sku in request.SkuItems)
            {
                PaymentDetailsItemType item = new PaymentDetailsItemType();

                item.Amount      = new BasicAmountType(currency, (sku.InitialPrice * sku.Quantity).ToString("N2"));
                item.Quantity    = sku.Quantity;
                item.Name        = sku.Title;
                item.Number      = sku.SkuCode;
                item.Description = sku.LongDescription;

                items.Add(item);
            }

            requestDetails.PaymentDetails.PaymentDetailsItem = items;

            // Invoke the API
            DoDirectPaymentReq wrapper = new DoDirectPaymentReq();

            wrapper.DoDirectPaymentRequest = paypalRequest;
            // Create the PayPalAPIInterfaceServiceService service object to make the API call

            Dictionary <string, string> config = new Dictionary <string, string>();

            // enforce 30000 minimum for timeout specification (30 secs)
            int timeout = 30000;

            timeout = Math.Max(timeout, Convert.ToInt32(gatewaySettings.Timeout ?? "0"));

            config.Add("account0.apiUsername", gatewaySettings.User);
            config.Add("account0.apiPassword", gatewaySettings.Password);
            config.Add("account0.apiSignature", gatewaySettings.Signature);
            config.Add("account0.applicationId", gatewaySettings.AppID);
            config.Add("connectionTimeout", timeout.ToString());
            config.Add("mode", gatewaySettings.Mode);

            PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(config);

            // # API call
            // Invoke the DoDirectPayment method in service wrapper object
            DoDirectPaymentResponseType paypalResponse = service.DoDirectPayment(wrapper);

            // Check for API return status
            return(ParseResponse(service, paypalResponse));
        }
Esempio n. 11
0
        /// <summary>
        /// Authorizes the 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>
        /// <param name="authorizeOnly">A value indicating whether to authorize only; true - authorize; false - sale</param>
        protected void AuthorizeOrSale(PaymentInfo paymentInfo, Customer customer,
                                       Guid orderGuid, ProcessPaymentResult processPaymentResult, bool authorizeOnly)
        {
            InitSettings();

            DoDirectPaymentReq req = new DoDirectPaymentReq();

            req.DoDirectPaymentRequest         = new DoDirectPaymentRequestType();
            req.DoDirectPaymentRequest.Version = this.APIVersion;
            DoDirectPaymentRequestDetailsType details = new DoDirectPaymentRequestDetailsType();

            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails = details;
            details.IPAddress = NopContext.Current.UserHostAddress;
            if (authorizeOnly)
            {
                details.PaymentAction = PaymentActionCodeType.Authorization;
            }
            else
            {
                details.PaymentAction = PaymentActionCodeType.Sale;
            }
            details.CreditCard = new CreditCardDetailsType();
            details.CreditCard.CreditCardNumber  = paymentInfo.CreditCardNumber;
            details.CreditCard.CreditCardType    = GetPaypalCreditCardType(paymentInfo.CreditCardType);
            details.CreditCard.ExpMonthSpecified = true;
            details.CreditCard.ExpMonth          = paymentInfo.CreditCardExpireMonth;
            details.CreditCard.ExpYearSpecified  = true;
            details.CreditCard.ExpYear           = paymentInfo.CreditCardExpireYear;
            details.CreditCard.CVV2      = paymentInfo.CreditCardCvv2;
            details.CreditCard.CardOwner = new PayerInfoType();
            details.CreditCard.CardOwner.PayerCountry  = GetPaypalCountryCodeType(paymentInfo.BillingAddress.Country);
            details.CreditCard.CreditCardTypeSpecified = true;

            details.CreditCard.CardOwner.Address = new AddressType();
            details.CreditCard.CardOwner.Address.CountrySpecified = true;
            details.CreditCard.CardOwner.Address.Street1          = paymentInfo.BillingAddress.Address1;
            details.CreditCard.CardOwner.Address.Street2          = paymentInfo.BillingAddress.Address2;
            details.CreditCard.CardOwner.Address.CityName         = paymentInfo.BillingAddress.City;
            if (paymentInfo.BillingAddress.StateProvince != null)
            {
                details.CreditCard.CardOwner.Address.StateOrProvince = paymentInfo.BillingAddress.StateProvince.Abbreviation;
            }
            else
            {
                details.CreditCard.CardOwner.Address.StateOrProvince = "CA";
            }
            details.CreditCard.CardOwner.Address.Country    = GetPaypalCountryCodeType(paymentInfo.BillingAddress.Country);
            details.CreditCard.CardOwner.Address.PostalCode = paymentInfo.BillingAddress.ZipPostalCode;
            details.CreditCard.CardOwner.Payer               = paymentInfo.BillingAddress.Email;
            details.CreditCard.CardOwner.PayerName           = new PersonNameType();
            details.CreditCard.CardOwner.PayerName.FirstName = paymentInfo.BillingAddress.FirstName;
            details.CreditCard.CardOwner.PayerName.LastName  = paymentInfo.BillingAddress.LastName;
            details.PaymentDetails                       = new PaymentDetailsType();
            details.PaymentDetails.OrderTotal            = new BasicAmountType();
            details.PaymentDetails.OrderTotal.Value      = paymentInfo.OrderTotal.ToString("N", new CultureInfo("en-us"));
            details.PaymentDetails.OrderTotal.currencyID = PaypalHelper.GetPaypalCurrency(IoC.Resolve <ICurrencyService>().PrimaryStoreCurrency);
            details.PaymentDetails.Custom                = orderGuid.ToString();
            details.PaymentDetails.ButtonSource          = "nopCommerceCart";


            //ShoppingCart cart = IoC.Resolve<IShoppingCartService>().GetShoppingCartByCustomerSessionGUID(ShoppingCartTypeEnum.ShoppingCart, NopContext.Current.Session.CustomerSessionGUID);
            //PaymentDetailsItemType[] cartItems = new PaymentDetailsItemType[cart.Count];
            //for (int i = 0; i < cart.Count; i++)
            //{
            //    ShoppingCartItem item = cart[i];
            //    cartItems[i] = new PaymentDetailsItemType()
            //    {
            //        Name = item.ProductVariant.FullProductName,
            //        Number = item.ProductVariant.ProductVariantID.ToString(),
            //        Quantity = item.Quantity.ToString(),
            //        Amount = new BasicAmountType()
            //        {
            //            currencyID = PaypalHelper.GetPaypalCurrency(IoC.Resolve<ICurrencyService>().PrimaryStoreCurrency),
            //            Value = (item.Quantity * item.ProductVariant.Price).ToString("N", new CultureInfo("en-us"))
            //        }
            //    };
            //};
            //details.PaymentDetails.PaymentDetailsItem = cartItems;

            //shipping
            if (paymentInfo.ShippingAddress != null)
            {
                if (paymentInfo.ShippingAddress.StateProvince != null && paymentInfo.ShippingAddress.Country != null)
                {
                    AddressType shippingAddress = new AddressType();
                    shippingAddress.Name                 = paymentInfo.ShippingAddress.FirstName + " " + paymentInfo.ShippingAddress.LastName;
                    shippingAddress.Street1              = paymentInfo.ShippingAddress.Address1;
                    shippingAddress.CityName             = paymentInfo.ShippingAddress.City;
                    shippingAddress.StateOrProvince      = paymentInfo.ShippingAddress.StateProvince.Abbreviation;
                    shippingAddress.PostalCode           = paymentInfo.ShippingAddress.ZipPostalCode;
                    shippingAddress.Country              = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), paymentInfo.ShippingAddress.Country.TwoLetterIsoCode, true);
                    shippingAddress.CountrySpecified     = true;
                    details.PaymentDetails.ShipToAddress = shippingAddress;
                }
            }

            DoDirectPaymentResponseType response = service2.DoDirectPayment(req);

            string error   = string.Empty;
            bool   Success = PaypalHelper.CheckSuccess(response, out error);

            if (Success)
            {
                processPaymentResult.AVSResult = response.AVSCode;
                processPaymentResult.AuthorizationTransactionCode = response.CVV2Code;
                if (authorizeOnly)
                {
                    processPaymentResult.AuthorizationTransactionId     = response.TransactionID;
                    processPaymentResult.AuthorizationTransactionResult = response.Ack.ToString();

                    processPaymentResult.PaymentStatus = PaymentStatusEnum.Authorized;
                }
                else
                {
                    processPaymentResult.CaptureTransactionId     = response.TransactionID;
                    processPaymentResult.CaptureTransactionResult = response.Ack.ToString();

                    processPaymentResult.PaymentStatus = PaymentStatusEnum.Paid;
                }
            }
            else
            {
                processPaymentResult.Error     = error;
                processPaymentResult.FullError = error;
            }
        }
Esempio n. 12
0
        public void ProcessDirectPayment(PayPalInformation paypalinformation)
        {
            DoDirectPaymentRequestType DoDirectPmtReqType = new DoDirectPaymentRequestType();

            DoDirectPmtReqType.DoDirectPaymentRequestDetails = new DoDirectPaymentRequestDetailsType();

            // Set payment action
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.PaymentAction = PaymentActionCodeType.Sale;

            // Set IP
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.IPAddress = HttpContext.Current.Request.UserHostAddress;

            // Set CreditCard info.
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.CreditCard = new CreditCardDetailsType();
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.CreditCard.CreditCardNumber = paypalinformation.Order.CreditCard.Number;
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.CreditCard.CreditCardType   = ( CreditCardTypeType )StringToEnum(typeof(CreditCardTypeType), paypalinformation.Order.CreditCard.CardType);

            DoDirectPmtReqType.DoDirectPaymentRequestDetails.CreditCard.CVV2     = paypalinformation.Order.CreditCard.SecurityCode;
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.CreditCard.ExpMonth = paypalinformation.Order.CreditCard.ExpMonth;
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.CreditCard.ExpYear  = paypalinformation.Order.CreditCard.ExpYear;

            // Set the billing address
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.CreditCard.CardOwner                          = new PayerInfoType();
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.CreditCard.CardOwner.PayerName                = new PersonNameType();
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.CreditCard.CardOwner.PayerName.FirstName      = paypalinformation.Order.EndUser.FirstName;
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.CreditCard.CardOwner.PayerName.LastName       = paypalinformation.Order.EndUser.LastName;
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.CreditCard.CardOwner.Address                  = new AddressType();
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.CreditCard.CardOwner.Address.Street1          = paypalinformation.Order.CreditCard.Address.AddressLine;
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.CreditCard.CardOwner.Address.Street2          = paypalinformation.Order.CreditCard.Address.AddressLine2;
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.CreditCard.CardOwner.Address.CityName         = paypalinformation.Order.CreditCard.Address.City;
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.CreditCard.CardOwner.Address.StateOrProvince  = paypalinformation.Order.CreditCard.Address.State;
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.CreditCard.CardOwner.Address.PostalCode       = paypalinformation.Order.CreditCard.Address.PostalCode;
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.CreditCard.CardOwner.Address.CountrySpecified = true;
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.CreditCard.CardOwner.Address.Country          = CountryCodeType.US;
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.CreditCard.CardOwner.Address.Phone            = paypalinformation.Order.EndUser.ContactInformation.Phone;

            PaymentDetailsItemType[] itemArray = new PaymentDetailsItemType[paypalinformation.Order.OrderDetails.Products.Length];
            PaymentDetailsItemType   items     = null;

            // Loop through all items that were added to the shopping cart.
            for (int i = 0; i < paypalinformation.Order.OrderDetails.Products.Length; i++)
            {
                items                   = new PaymentDetailsItemType();
                items.Amount            = new BasicAmountType();
                items.Amount.Value      = paypalinformation.Order.OrderDetails.Products[i].Price.ToString();
                items.Amount.currencyID = CurrencyCodeType.USD;
                items.Quantity          = paypalinformation.Order.OrderDetails.Products[i].Quantity.ToString();

                //items.Tax						= new BasicAmountType();
                //items.Tax.Value				= CalculationManager.CalcSalesTax( Convert.ToDecimal( items.Amount.Value ) ).ToString();
                //items.Tax.currencyID			= CurrencyCodeType.USD;

                items.Name   = paypalinformation.Order.OrderDetails.Products[i].Name;
                items.Number = paypalinformation.Order.OrderDetails.Products[i].ProductID.ToString();

                itemArray.SetValue(items, i);
            }

            // set payment Details
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.PaymentDetails                  = new PaymentDetailsType();
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.PaymentDetails.Custom           = System.DateTime.Now.ToLongTimeString();
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.PaymentDetails.OrderDescription = "";

            DoDirectPmtReqType.DoDirectPaymentRequestDetails.PaymentDetails.PaymentDetailsItem = new PaymentDetailsItemType[itemArray.Length];
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.PaymentDetails.PaymentDetailsItem = itemArray;

            for (int ii = 0; ii < itemArray.Length; ii++)
            {
                DoDirectPmtReqType.DoDirectPaymentRequestDetails.PaymentDetails.PaymentDetailsItem.SetValue(itemArray[ii], ii);
            }

            // Order summary.
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.PaymentDetails.OrderTotal               = new BasicAmountType();
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.PaymentDetails.OrderTotal.currencyID    = CurrencyCodeType.USD;
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.PaymentDetails.OrderTotal.Value         = paypalinformation.Order.OrderTotal.ToString();
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.PaymentDetails.ShippingTotal            = new BasicAmountType();
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.PaymentDetails.ShippingTotal.currencyID = CurrencyCodeType.USD;
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.PaymentDetails.ShippingTotal.Value      = paypalinformation.Order.ShippingTotal.ToString();
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.PaymentDetails.TaxTotal             = new BasicAmountType();
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.PaymentDetails.TaxTotal.currencyID  = CurrencyCodeType.USD;
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.PaymentDetails.TaxTotal.Value       = paypalinformation.Order.Tax.ToString();
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.PaymentDetails.ItemTotal            = new BasicAmountType();
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.PaymentDetails.ItemTotal.currencyID = CurrencyCodeType.USD;
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.PaymentDetails.ItemTotal.Value      = paypalinformation.Order.SubTotal.ToString();

            //set ship to address
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.PaymentDetails.ShipToAddress                  = new AddressType();
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.PaymentDetails.ShipToAddress.Name             = paypalinformation.Order.EndUser.FirstName + " " + paypalinformation.Order.EndUser.LastName;
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.PaymentDetails.ShipToAddress.Street1          = paypalinformation.Order.ShippingAddress.AddressLine;
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.PaymentDetails.ShipToAddress.CityName         = paypalinformation.Order.ShippingAddress.City;
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.PaymentDetails.ShipToAddress.StateOrProvince  = paypalinformation.Order.ShippingAddress.State;
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.PaymentDetails.ShipToAddress.PostalCode       = paypalinformation.Order.ShippingAddress.PostalCode;
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.PaymentDetails.ShipToAddress.CountrySpecified = true;
            DoDirectPmtReqType.DoDirectPaymentRequestDetails.PaymentDetails.ShipToAddress.Country          = CountryCodeType.US;

            // credentials
            DoDirectPaymentReq DoDPReq = new DoDirectPaymentReq();

            DoDPReq.DoDirectPaymentRequest         = DoDirectPmtReqType;
            DoDPReq.DoDirectPaymentRequest.Version = "2.20";

            try
            {
                //make call return response
                DoDirectPaymentResponseType DPRes = new DoDirectPaymentResponseType();
                DPRes = PPInterface.DoDirectPayment(DoDPReq);
                string errors = CheckForErrors(DPRes);

                if (errors == string.Empty)
                {
                    IsSubmissionSuccess = true;
                    paypalinformation.Order.TransactionID = DPRes.TransactionID;
                }
                else
                {
                    IsSubmissionSuccess = false;
                    SubmissionError     = errors;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Esempio n. 13
0
    // # DoDirectPaymentAPIOperation
    // The MassPay API operation makes a payment to one or more PayPal account holders.
    public DoDirectPaymentResponseType DoDirectPaymentAPIOperation()
    {
        // Create the DoDirectPaymentResponseType object
        DoDirectPaymentResponseType responseDoDirectPaymentResponseType = new DoDirectPaymentResponseType();

        try
        {
            // Create the DoDirectPaymentReq object
            DoDirectPaymentReq doDirectPayment = new DoDirectPaymentReq();
            DoDirectPaymentRequestDetailsType doDirectPaymentRequestDetails = new DoDirectPaymentRequestDetailsType();

            // Information about the credit card to be charged.
            CreditCardDetailsType creditCard = new CreditCardDetailsType();

            // Type of credit card. For UK, only Maestro, MasterCard, Discover, and
            // Visa are allowable. For Canada, only MasterCard and Visa are
            // allowable and Interac debit cards are not supported. It is one of the
            // following values:
            //
            // * Visa
            // * MasterCard
            // * Discover
            // * Amex
            // * Solo
            // * Switch
            // * Maestro: See note.
            // `Note:
            // If the credit card type is Maestro, you must set currencyId to GBP.
            // In addition, you must specify either StartMonth and StartYear or
            // IssueNumber.`
            creditCard.CreditCardType = CreditCardTypeType.VISA;

            // Credit Card number
            creditCard.CreditCardNumber = "4770461107194023";

            // ExpiryMonth of credit card
            creditCard.ExpMonth = Convert.ToInt32("12");

            // Expiry Year of credit card
            creditCard.ExpYear = Convert.ToInt32("2021");

            //Details about the owner of the credit card.
            PayerInfoType cardOwner = new PayerInfoType();

            // Email address of buyer.
            cardOwner.Payer      = "*****@*****.**";
            creditCard.CardOwner = cardOwner;

            doDirectPaymentRequestDetails.CreditCard = creditCard;

            // Information about the payment
            PaymentDetailsType paymentDetails = new PaymentDetailsType();

            // IPN URL
            // * PayPal Instant Payment Notification is a call back system that is initiated when a transaction is completed
            // * The transaction related IPN variables will be received on the call back URL specified in the request
            // * The IPN variables have to be sent back to the PayPal system for validation, upon validation PayPal will send a response string "VERIFIED" or "INVALID"
            // * PayPal would continuously resend IPN if a wrong IPN is sent
            paymentDetails.NotifyURL = "http://IPNhost";

            // Total cost of the transaction to the buyer. If shipping cost and tax
            // charges are known, include them in this value. If not, this value
            // should be the current sub-total of the order.
            //
            // If the transaction includes one or more one-time purchases, this field must be equal to
            // the sum of the purchases. Set this field to 0 if the transaction does
            // not include a one-time purchase such as when you set up a billing
            // agreement for a recurring payment that is not immediately charged.
            // When the field is set to 0, purchase-specific fields are ignored.
            //
            // * `Currency Code` - You must set the currencyID attribute to one of the
            // 3-character currency codes for any of the supported PayPal
            // currencies.
            // * `Amount`
            BasicAmountType orderTotal = new BasicAmountType(CurrencyCodeType.USD, "4.00");
            paymentDetails.OrderTotal = orderTotal;
            doDirectPaymentRequestDetails.PaymentDetails = paymentDetails;

            // IP address of the buyer's browser.
            // `Note:
            // PayPal records this IP addresses as a means to detect possible fraud.`
            doDirectPaymentRequestDetails.IPAddress = "127.0.0.1";

            DoDirectPaymentRequestType doDirectPaymentRequest = new DoDirectPaymentRequestType(doDirectPaymentRequestDetails);
            doDirectPayment.DoDirectPaymentRequest = doDirectPaymentRequest;

            // Create the service wrapper object to make the API call
            PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService();

            // # API call
            // Invoke the DoDirectPayment method in service wrapper object
            responseDoDirectPaymentResponseType = service.DoDirectPayment(doDirectPayment);

            if (responseDoDirectPaymentResponseType != null)
            {
                // Response envelope acknowledgement
                string acknowledgement = "DoDirectPayment API Operation - ";
                acknowledgement += responseDoDirectPaymentResponseType.Ack.ToString();
                logger.Info(acknowledgement + "\n");
                Console.WriteLine(acknowledgement + "\n");

                // # Success values
                if (responseDoDirectPaymentResponseType.Ack.ToString().Trim().ToUpper().Equals("SUCCESS"))
                {
                    // Unique identifier of the transaction
                    logger.Info("Transaction ID : " + responseDoDirectPaymentResponseType.TransactionID + "\n");
                    Console.WriteLine("Transaction ID : " + responseDoDirectPaymentResponseType.TransactionID + "\n");
                }
                // # Error Values
                else
                {
                    List <ErrorType> errorMessages = responseDoDirectPaymentResponseType.Errors;
                    foreach (ErrorType error in errorMessages)
                    {
                        logger.Debug("API Error Message : " + error.LongMessage);
                        Console.WriteLine("API Error Message : " + error.LongMessage + "\n");
                    }
                }
            }
        }
        // # Exception log
        catch (System.Exception ex)
        {
            // Log the exception message
            logger.Debug("Error Message : " + ex.Message);
            Console.WriteLine("Error Message : " + ex.Message);
        }
        return(responseDoDirectPaymentResponseType);
    }
Esempio n. 14
0
        static public OrderInfo Charge(string firstName, string lastName, string address1, string address2, string city, string state, string zip, string country, string ccType, string ccNumber, string ccAuthCode,
                                       int ccExpireYear, int ccExpireMonth, decimal priceFinal, decimal priceTax, decimal priceShipping)
        {
            System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
            CreditCardTypeType cardType = CreditCardTypeType.Visa;

            switch (ccType)
            {
            case "Visa":
            case "MasterCard":
            case "Discover":
                cardType = (CreditCardTypeType)Enum.Parse(typeof(CreditCardTypeType), ccType.ToString());
                break;

            case "AMEX":
                cardType = CreditCardTypeType.Amex;
                break;

            default:
                cardType = CreditCardTypeType.Visa;
                break;
            }
            CountryCodeType countryCode = CountryCodeType.US;

            try
            { countryCode = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), country); }
            catch
            { countryCode = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), Robo.Country.NameToCode(country)); }
            finally { countryCode = CountryCodeType.US; }

            using (var client = new PayPalAPIAAInterfaceClient(new BasicHttpsBinding(), new EndpointAddress(EndpointUrl)))
            {
                var credentials = new CustomSecurityHeaderType()
                {
                    Credentials = new UserIdPasswordType()
                    {
                        Username  = APIUserName,
                        Password  = APIPassword,
                        Signature = APISignature
                    }
                };
                DoDirectPaymentReq req = new DoDirectPaymentReq()
                {
                    DoDirectPaymentRequest = new DoDirectPaymentRequestType()
                    {
                        Version = "121.0",
                        DoDirectPaymentRequestDetails = new DoDirectPaymentRequestDetailsType()
                        {
                            CreditCard = new CreditCardDetailsType()
                            {
                                CardOwner = new PayerInfoType()
                                {
                                    PayerName = new PersonNameType()
                                    {
                                        FirstName = firstName,
                                        LastName  = lastName
                                    },
                                    Address = new AddressType()
                                    {
                                        CityName        = city,
                                        StateOrProvince = state,
                                        PostalCode      = zip,
                                        Country         = countryCode,
                                        Street1         = address1,
                                        Street2         = address2
                                    }
                                },
                                CreditCardNumber        = ccNumber,
                                CreditCardType          = cardType,
                                CreditCardTypeSpecified = true,
                                CVV2              = ccAuthCode,
                                ExpMonth          = ccExpireMonth,
                                ExpMonthSpecified = true,
                                ExpYear           = ccExpireYear,
                                ExpYearSpecified  = true
                            },
                            PaymentAction  = PaymentActionCodeType.Sale,
                            PaymentDetails = new PaymentDetailsType()
                            {
                                OrderTotal = new BasicAmountType()
                                {
                                    currencyID = CurrencyCodeType.USD,
                                    Value      = priceFinal.ToString("F2")
                                },
                                ShippingTotal = new BasicAmountType()
                                {
                                    currencyID = CurrencyCodeType.USD,
                                    Value      = priceShipping.ToString("F2")
                                },
                                TaxTotal = new BasicAmountType()
                                {
                                    currencyID = CurrencyCodeType.USD,
                                    Value      = priceTax.ToString("F2")
                                }
                            }
                        }
                    }
                };
                var response = client.DoDirectPayment(ref credentials, req);
                // check errors
                string    errors = CheckErrors(response);
                OrderInfo info   = new OrderInfo();
                if (errors == String.Empty)
                {
                    info.Ack           = response.Ack.ToString();
                    info.TransactionID = response.TransactionID;
                    info.CVV2Code      = response.CVV2Code;
                }
                else
                {
                    info.Ack = errors;
                }
                return(info);
            }
        }
Esempio n. 15
0
        /// <summary>
        /// Process a payment
        /// </summary>
        /// <param name="processPaymentRequest">Payment info required for an order processing</param>
        /// <returns>Process payment result</returns>
        public override ProcessPaymentResult ProcessPayment(ProcessPaymentRequest processPaymentRequest)
        {
            var result = new ProcessPaymentResult();

            var store    = Services.StoreService.GetStoreById(processPaymentRequest.StoreId);
            var customer = _customerService.GetCustomerById(processPaymentRequest.CustomerId);
            var settings = Services.Settings.LoadSetting <PayPalDirectPaymentSettings>(processPaymentRequest.StoreId);

            var req = new DoDirectPaymentReq();

            req.DoDirectPaymentRequest         = new DoDirectPaymentRequestType();
            req.DoDirectPaymentRequest.Version = ApiVersion;

            var details = new DoDirectPaymentRequestDetailsType();

            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails = details;
            details.IPAddress = Services.WebHelper.GetCurrentIpAddress();

            if (details.IPAddress.IsEmpty())
            {
                details.IPAddress = "127.0.0.1";
            }

            if (settings.TransactMode == TransactMode.Authorize)
            {
                details.PaymentAction = PaymentActionCodeType.Authorization;
            }
            else
            {
                details.PaymentAction = PaymentActionCodeType.Sale;
            }

            //credit card
            details.CreditCard = new CreditCardDetailsType();
            details.CreditCard.CreditCardNumber  = processPaymentRequest.CreditCardNumber;
            details.CreditCard.CreditCardType    = GetCreditCardType(processPaymentRequest.CreditCardType);
            details.CreditCard.ExpMonthSpecified = true;
            details.CreditCard.ExpMonth          = processPaymentRequest.CreditCardExpireMonth;
            details.CreditCard.ExpYearSpecified  = true;
            details.CreditCard.ExpYear           = processPaymentRequest.CreditCardExpireYear;
            details.CreditCard.CVV2      = processPaymentRequest.CreditCardCvv2;
            details.CreditCard.CardOwner = new PayerInfoType();
            details.CreditCard.CardOwner.PayerCountry  = GetCountryCodeType(customer.BillingAddress.Country);
            details.CreditCard.CreditCardTypeSpecified = true;
            //billing address
            details.CreditCard.CardOwner.Address = new AddressType();
            details.CreditCard.CardOwner.Address.CountrySpecified = true;
            details.CreditCard.CardOwner.Address.Street1          = customer.BillingAddress.Address1;
            details.CreditCard.CardOwner.Address.Street2          = customer.BillingAddress.Address2;
            details.CreditCard.CardOwner.Address.CityName         = customer.BillingAddress.City;
            if (customer.BillingAddress.StateProvince != null)
            {
                details.CreditCard.CardOwner.Address.StateOrProvince = customer.BillingAddress.StateProvince.Abbreviation;
            }
            else
            {
                details.CreditCard.CardOwner.Address.StateOrProvince = "CA";
            }
            details.CreditCard.CardOwner.Address.Country    = GetCountryCodeType(customer.BillingAddress.Country);
            details.CreditCard.CardOwner.Address.PostalCode = customer.BillingAddress.ZipPostalCode;
            details.CreditCard.CardOwner.Payer               = customer.BillingAddress.Email;
            details.CreditCard.CardOwner.PayerName           = new PersonNameType();
            details.CreditCard.CardOwner.PayerName.FirstName = customer.BillingAddress.FirstName;
            details.CreditCard.CardOwner.PayerName.LastName  = customer.BillingAddress.LastName;

            //order totals
            var payPalCurrency = GetApiCurrency(store.PrimaryStoreCurrency);

            details.PaymentDetails                       = new PaymentDetailsType();
            details.PaymentDetails.OrderTotal            = new BasicAmountType();
            details.PaymentDetails.OrderTotal.Value      = Math.Round(processPaymentRequest.OrderTotal, 2).ToString("N", new CultureInfo("en-us"));
            details.PaymentDetails.OrderTotal.currencyID = payPalCurrency;
            details.PaymentDetails.Custom                = processPaymentRequest.OrderGuid.ToString();
            details.PaymentDetails.ButtonSource          = SmartStoreVersion.CurrentFullVersion;
            //shipping
            if (customer.ShippingAddress != null)
            {
                if (customer.ShippingAddress.StateProvince != null && customer.ShippingAddress.Country != null)
                {
                    var shippingAddress = new AddressType();
                    shippingAddress.Name                 = customer.ShippingAddress.FirstName + " " + customer.ShippingAddress.LastName;
                    shippingAddress.Street1              = customer.ShippingAddress.Address1;
                    shippingAddress.CityName             = customer.ShippingAddress.City;
                    shippingAddress.StateOrProvince      = customer.ShippingAddress.StateProvince.Abbreviation;
                    shippingAddress.PostalCode           = customer.ShippingAddress.ZipPostalCode;
                    shippingAddress.Country              = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), customer.ShippingAddress.Country.TwoLetterIsoCode, true);
                    shippingAddress.CountrySpecified     = true;
                    details.PaymentDetails.ShipToAddress = shippingAddress;
                }
            }

            //send request
            using (var service = GetApiAaService(settings))
            {
                var response = service.DoDirectPayment(req);

                var error   = "";
                var success = IsSuccess(response, out error);

                if (success)
                {
                    result.AvsResult = response.AVSCode;
                    result.AuthorizationTransactionCode = response.CVV2Code;
                    if (settings.TransactMode == TransactMode.Authorize)
                    {
                        result.AuthorizationTransactionId     = response.TransactionID;
                        result.AuthorizationTransactionResult = response.Ack.ToString();

                        result.NewPaymentStatus = PaymentStatus.Authorized;
                    }
                    else
                    {
                        result.CaptureTransactionId     = response.TransactionID;
                        result.CaptureTransactionResult = response.Ack.ToString();

                        result.NewPaymentStatus = PaymentStatus.Paid;
                    }
                }
                else
                {
                    result.AddError(error);
                }
            }
            return(result);
        }
Esempio n. 16
0
 /// <remarks/>
 public void DoDirectPaymentAsync(DoDirectPaymentReq DoDirectPaymentReq, object userState) {
     if ((this.DoDirectPaymentOperationCompleted == null)) {
         this.DoDirectPaymentOperationCompleted = new System.Threading.SendOrPostCallback(this.OnDoDirectPaymentOperationCompleted);
     }
     this.InvokeAsync("DoDirectPayment", new object[] {
                 DoDirectPaymentReq}, this.DoDirectPaymentOperationCompleted, userState);
 }
        protected ProcessPaymentResult AuthorizeOrSale(ProcessPaymentRequest processPaymentRequest, bool authorizeOnly)
        {
            var result = new ProcessPaymentResult();



            var req = new DoDirectPaymentReq();

            req.DoDirectPaymentRequest         = new DoDirectPaymentRequestType();
            req.DoDirectPaymentRequest.Version = GetApiVersion();
            var details = new DoDirectPaymentRequestDetailsType();

            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails = details;
            details.IPAddress = _webHelper.GetCurrentIpAddress() ?? "";
            if (authorizeOnly)
            {
                details.PaymentAction = PaymentActionCodeType.AUTHORIZATION;
            }
            else
            {
                details.PaymentAction = PaymentActionCodeType.SALE;
            }
            //credit card
            details.CreditCard = new CreditCardDetailsType();
            details.CreditCard.CreditCardNumber = processPaymentRequest.CreditCardNumber;
            details.CreditCard.CreditCardType   = GetPaypalCreditCardType(processPaymentRequest.CreditCardType);
            details.CreditCard.ExpMonth         = processPaymentRequest.CreditCardExpireMonth;
            details.CreditCard.ExpYear          = processPaymentRequest.CreditCardExpireYear;
            details.CreditCard.CVV2             = processPaymentRequest.CreditCardCvv2;



            //order totals
            var payPalCurrency = PaypalHelper.GetPaypalCurrency("USD");

            details.PaymentDetails                       = new PaymentDetailsType();
            details.PaymentDetails.OrderTotal            = new BasicAmountType();
            details.PaymentDetails.OrderTotal.value      = Math.Round(processPaymentRequest.OrderTotal, 2).ToString("N", new CultureInfo("en-us"));
            details.PaymentDetails.OrderTotal.currencyID = payPalCurrency;
            details.PaymentDetails.Custom                = processPaymentRequest.OrderGuid.ToString();
            details.PaymentDetails.ButtonSource          = "GreenProPaymentButton";



            //send request
            var service = GetService();
            DoDirectPaymentResponseType response = service.DoDirectPayment(req);

            string error;
            bool   success = PaypalHelper.CheckSuccess(response, out error);

            if (success)
            {
                result.AvsResult = response.AVSCode;
                result.AuthorizationTransactionCode = response.CVV2Code;
                if (authorizeOnly)
                {
                    result.AuthorizationTransactionId     = response.TransactionID;
                    result.AuthorizationTransactionResult = response.Ack.ToString();

                    result.NewPaymentStatus = PaymentStatus.Authorized;
                }
                else
                {
                    result.CaptureTransactionId     = response.TransactionID;
                    result.CaptureTransactionResult = response.Ack.ToString();

                    result.NewPaymentStatus = PaymentStatus.Paid;
                }
            }
            else
            {
                result.AddError(error);
            }
            return(result);
        }
Esempio n. 18
0
        protected ProcessPaymentResult AuthorizeOrSale(ProcessPaymentRequest processPaymentRequest, bool authorizeOnly)
        {
            var result = new ProcessPaymentResult();

            var customer = _customerService.GetCustomerById(processPaymentRequest.CustomerId);

            if (customer == null)
            {
                throw new Exception("Customer cannot be loaded");
            }

            var req = new DoDirectPaymentReq();

            req.DoDirectPaymentRequest         = new DoDirectPaymentRequestType();
            req.DoDirectPaymentRequest.Version = GetApiVersion();
            var details = new DoDirectPaymentRequestDetailsType();

            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails = details;
            details.IPAddress = _webHelper.GetCurrentIpAddress();
            if (authorizeOnly)
            {
                details.PaymentAction = PaymentActionCodeType.Authorization;
            }
            else
            {
                details.PaymentAction = PaymentActionCodeType.Sale;
            }
            //credit card
            details.CreditCard = new CreditCardDetailsType();
            details.CreditCard.CreditCardNumber  = processPaymentRequest.CreditCardNumber;
            details.CreditCard.CreditCardType    = GetPaypalCreditCardType(processPaymentRequest.CreditCardType);
            details.CreditCard.ExpMonthSpecified = true;
            details.CreditCard.ExpMonth          = processPaymentRequest.CreditCardExpireMonth;
            details.CreditCard.ExpYearSpecified  = true;
            details.CreditCard.ExpYear           = processPaymentRequest.CreditCardExpireYear;
            details.CreditCard.CVV2      = processPaymentRequest.CreditCardCvv2;
            details.CreditCard.CardOwner = new PayerInfoType();
            details.CreditCard.CardOwner.PayerCountry  = GetPaypalCountryCodeType(customer.BillingAddress.Country);
            details.CreditCard.CreditCardTypeSpecified = true;
            //billing address
            details.CreditCard.CardOwner.Address = new AddressType();
            details.CreditCard.CardOwner.Address.CountrySpecified = true;
            details.CreditCard.CardOwner.Address.Street1          = customer.BillingAddress.Address1;
            details.CreditCard.CardOwner.Address.Street2          = customer.BillingAddress.Address2;
            details.CreditCard.CardOwner.Address.CityName         = customer.BillingAddress.City;
            if (customer.BillingAddress.StateProvince != null)
            {
                details.CreditCard.CardOwner.Address.StateOrProvince = customer.BillingAddress.StateProvince.Abbreviation;
            }
            else
            {
                details.CreditCard.CardOwner.Address.StateOrProvince = "CA";
            }
            details.CreditCard.CardOwner.Address.Country    = GetPaypalCountryCodeType(customer.BillingAddress.Country);
            details.CreditCard.CardOwner.Address.PostalCode = customer.BillingAddress.ZipPostalCode;
            details.CreditCard.CardOwner.Payer               = customer.BillingAddress.Email;
            details.CreditCard.CardOwner.PayerName           = new PersonNameType();
            details.CreditCard.CardOwner.PayerName.FirstName = customer.BillingAddress.FirstName;
            details.CreditCard.CardOwner.PayerName.LastName  = customer.BillingAddress.LastName;
            //order totals
            var payPalCurrency = PaypalHelper.GetPaypalCurrency(_currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId));

            details.PaymentDetails                       = new PaymentDetailsType();
            details.PaymentDetails.OrderTotal            = new BasicAmountType();
            details.PaymentDetails.OrderTotal.Value      = Math.Round(processPaymentRequest.OrderTotal, 2).ToString("N", new CultureInfo("en-us"));
            details.PaymentDetails.OrderTotal.currencyID = payPalCurrency;
            details.PaymentDetails.Custom                = processPaymentRequest.OrderGuid.ToString();
            details.PaymentDetails.ButtonSource          = "nopCommerceCart";
            //pass product names and totals to PayPal
            //if (_paypalDirectPaymentSettings.PassProductNamesAndTotals)
            //{
            //    //individual items
            //var cart = customer.ShoppingCartItems
            //    .Where(x=>x.ShoppingCartType == ShoppingCartType.ShoppingCart)
            //    .Where(x=>x.StoreId == processPaymentRequest.StoreId)
            //    .ToList();
            //    var cartItems = new PaymentDetailsItemType[cart.Count];
            //    for (int i = 0; i < cart.Count; i++)
            //    {
            //        var sc = cart[i];
            //        decimal taxRate = decimal.Zero;
            //        var customer = processPaymentRequest.Customer;
            //        decimal scUnitPrice = _priceCalculationService.GetUnitPrice(sc, true);
            //        decimal scSubTotal = _priceCalculationService.GetSubTotal(sc, true);
            //        decimal scUnitPriceInclTax = _taxService.GetProductPrice(sc.ProductVariant, scUnitPrice, true, customer, out taxRate);
            //        decimal scUnitPriceExclTax = _taxService.GetProductPrice(sc.ProductVariant, scUnitPrice, false, customer, out taxRate);
            //        //decimal scSubTotalInclTax = _taxService.GetProductPrice(sc.ProductVariant, scSubTotal, true, customer, out taxRate);
            //        //decimal scSubTotalExclTax = _taxService.GetProductPrice(sc.ProductVariant, scSubTotal, false, customer, out taxRate);
            //        cartItems[i] = new PaymentDetailsItemType()
            //        {
            //            Name = sc.ProductVariant.FullProductName,
            //            Number = sc.ProductVariant.Id.ToString(),
            //            Quantity = sc.Quantity.ToString(),
            //            Amount = new BasicAmountType()
            //            {
            //                currencyID = payPalCurrency,
            //                Value = scUnitPriceExclTax.ToString("N", new CultureInfo("en-us")),
            //            },
            //            Tax = new BasicAmountType()
            //            {
            //                currencyID = payPalCurrency,
            //                Value = (scUnitPriceInclTax - scUnitPriceExclTax).ToString("N", new CultureInfo("en-us")),
            //            },
            //        };
            //    };
            //    details.PaymentDetails.PaymentDetailsItem = cartItems;
            //    //other totals (undone)
            //    details.PaymentDetails.ItemTotal = null;
            //    details.PaymentDetails.ShippingTotal = null;
            //    details.PaymentDetails.TaxTotal = null;
            //    details.PaymentDetails.HandlingTotal = null;
            //}
            //shipping
            if (customer.ShippingAddress != null)
            {
                if (customer.ShippingAddress.StateProvince != null && customer.ShippingAddress.Country != null)
                {
                    var shippingAddress = new AddressType();
                    shippingAddress.Name                 = customer.ShippingAddress.FirstName + " " + customer.ShippingAddress.LastName;
                    shippingAddress.Street1              = customer.ShippingAddress.Address1;
                    shippingAddress.CityName             = customer.ShippingAddress.City;
                    shippingAddress.StateOrProvince      = customer.ShippingAddress.StateProvince.Abbreviation;
                    shippingAddress.PostalCode           = customer.ShippingAddress.ZipPostalCode;
                    shippingAddress.Country              = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), customer.ShippingAddress.Country.TwoLetterIsoCode, true);
                    shippingAddress.CountrySpecified     = true;
                    details.PaymentDetails.ShipToAddress = shippingAddress;
                }
            }

            //send request
            using (var service2 = new PayPalAPIAASoapBinding())
            {
                if (!_paypalDirectPaymentSettings.UseSandbox)
                {
                    service2.Url = "https://api-3t.paypal.com/2.0/";
                }
                else
                {
                    service2.Url = "https://api-3t.sandbox.paypal.com/2.0/";
                }

                service2.RequesterCredentials                       = new CustomSecurityHeaderType();
                service2.RequesterCredentials.Credentials           = new UserIdPasswordType();
                service2.RequesterCredentials.Credentials.Username  = _paypalDirectPaymentSettings.ApiAccountName;
                service2.RequesterCredentials.Credentials.Password  = _paypalDirectPaymentSettings.ApiAccountPassword;
                service2.RequesterCredentials.Credentials.Signature = _paypalDirectPaymentSettings.Signature;
                service2.RequesterCredentials.Credentials.Subject   = "";

                DoDirectPaymentResponseType response = service2.DoDirectPayment(req);

                string error   = "";
                bool   success = PaypalHelper.CheckSuccess(response, out error);
                if (success)
                {
                    result.AvsResult = response.AVSCode;
                    result.AuthorizationTransactionCode = response.CVV2Code;
                    if (authorizeOnly)
                    {
                        result.AuthorizationTransactionId     = response.TransactionID;
                        result.AuthorizationTransactionResult = response.Ack.ToString();

                        result.NewPaymentStatus = PaymentStatus.Authorized;
                    }
                    else
                    {
                        result.CaptureTransactionId     = response.TransactionID;
                        result.CaptureTransactionResult = response.Ack.ToString();

                        result.NewPaymentStatus = PaymentStatus.Paid;
                    }
                }
                else
                {
                    result.AddError(error);
                }
            }
            return(result);
        }
Esempio n. 19
0
        /// <summary>
        /// Authorizes the 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>
        /// <param name="authorizeOnly">A value indicating whether to authorize only; true - authorize; false - sale</param>
        protected void AuthorizeOrSale(PaymentInfo paymentInfo, Customer customer, Guid OrderGuid, ProcessPaymentResult processPaymentResult, bool authorizeOnly)
        {
            InitSettings();

            DoDirectPaymentReq req = new DoDirectPaymentReq();

            req.DoDirectPaymentRequest         = new DoDirectPaymentRequestType();
            req.DoDirectPaymentRequest.Version = this.APIVersion;
            DoDirectPaymentRequestDetailsType details = new DoDirectPaymentRequestDetailsType();

            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails = details;
            details.IPAddress = HttpContext.Current.Request.UserHostAddress;
            if (authorizeOnly)
            {
                details.PaymentAction = PaymentActionCodeType.Authorization;
            }
            else
            {
                details.PaymentAction = PaymentActionCodeType.Sale;
            }
            details.CreditCard = new CreditCardDetailsType();
            details.CreditCard.CreditCardNumber  = paymentInfo.CreditCardNumber;
            details.CreditCard.CreditCardType    = GetPaypalCreditCardType(paymentInfo.CreditCardType);
            details.CreditCard.ExpMonthSpecified = true;
            details.CreditCard.ExpMonth          = paymentInfo.CreditCardExpireMonth;
            details.CreditCard.ExpYearSpecified  = true;
            details.CreditCard.ExpYear           = paymentInfo.CreditCardExpireYear;
            details.CreditCard.CVV2 = paymentInfo.CreditCardCVV2;

            details.CreditCard.CardOwner = new PayerInfoType();
            details.CreditCard.CardOwner.PayerCountry = GetPaypalCountryCodeType(paymentInfo.BillingAddress.Country);

            details.CreditCard.CardOwner.Address = new AddressType();
            details.CreditCard.CardOwner.Address.CountrySpecified = true;
            details.CreditCard.CardOwner.Address.Street1          = paymentInfo.BillingAddress.Address1;
            details.CreditCard.CardOwner.Address.Street2          = paymentInfo.BillingAddress.Address2;
            details.CreditCard.CardOwner.Address.CityName         = paymentInfo.BillingAddress.City;
            if (paymentInfo.BillingAddress.StateProvince != null)
            {
                details.CreditCard.CardOwner.Address.StateOrProvince = paymentInfo.BillingAddress.StateProvince.Abbreviation;
            }
            details.CreditCard.CardOwner.Address.Country     = GetPaypalCountryCodeType(paymentInfo.BillingAddress.Country);
            details.CreditCard.CardOwner.Address.PostalCode  = paymentInfo.BillingAddress.ZipPostalCode;
            details.CreditCard.CardOwner.PayerName           = new PersonNameType();
            details.CreditCard.CardOwner.PayerName.FirstName = paymentInfo.BillingAddress.FirstName;
            details.CreditCard.CardOwner.PayerName.LastName  = paymentInfo.BillingAddress.LastName;
            details.PaymentDetails                       = new PaymentDetailsType();
            details.PaymentDetails.OrderTotal            = new BasicAmountType();
            details.PaymentDetails.OrderTotal.Value      = paymentInfo.OrderTotal.ToString("N", new CultureInfo("en-us"));
            details.PaymentDetails.OrderTotal.currencyID = PaypalHelper.GetPaypalCurrency(CurrencyManager.PrimaryStoreCurrency);
            details.PaymentDetails.Custom                = OrderGuid.ToString();
            details.PaymentDetails.ButtonSource          = "nopCommerceCart";

            DoDirectPaymentResponseType response = service2.DoDirectPayment(req);

            string error   = string.Empty;
            bool   Success = PaypalHelper.CheckSuccess(response, out error);

            if (Success)
            {
                processPaymentResult.AuthorizationTransactionID     = response.TransactionID;
                processPaymentResult.AuthorizationTransactionResult = response.Ack.ToString();

                //TODO save AVSCode and CVVCode in datatabase
                processPaymentResult.AVSResult = response.AVSCode;
                processPaymentResult.AuthorizationTransactionCode = response.CVV2Code;
                if (authorizeOnly)
                {
                    processPaymentResult.PaymentStatus = PaymentStatusEnum.Authorized;
                }
                else
                {
                    processPaymentResult.PaymentStatus = PaymentStatusEnum.Paid;
                }
                //processPaymentResult.AuthorizationDate = response.Timestamp;
                //processPaymentResult.AuthorizationDate = DateTime.Now;
            }
            else
            {
                processPaymentResult.Error     = error;
                processPaymentResult.FullError = error;
            }
        }
Esempio n. 20
0
 public DoDirectPaymentResponseType DoDirectPayment(DoDirectPaymentReq DoDirectPaymentReq)
 {
     return(DoDirectPayment(DoDirectPaymentReq, null));
 }
Esempio n. 21
0
        public ITransactionProcessResult Process(ITransactionProcessRequest request, bool authorizeOnly = false)
        {
            var user = _userService.Get(request.UserId);

            if (user == null)
            {
                throw new mobSocialException($"Can't find the user with Id {request.UserId}");
            }
            var creditCard = new CreditCardDetailsType()
            {
                CreditCardNumber = request.GetParameterAs <string>(PaymentParameterNames.CardNumber),
                CVV2             = request.GetParameterAs <string>(PaymentParameterNames.SecurityCode),
                ExpMonth         = request.GetParameterAs <int>(PaymentParameterNames.ExpireMonth),
                ExpYear          = request.GetParameterAs <int>(PaymentParameterNames.ExpireYear),
                CreditCardType   = PayPalHelper.GeCreditCardTypeType(request.GetParameterAs <string>(PaymentParameterNames.CardIssuerType)),
                CardOwner        = new PayerInfoType()
            };


            var paypalCurrency = PayPalHelper.GetPaypalCurrency(request.CurrencyIsoCode);
            var doDirectPaymentRequestDetails = new DoDirectPaymentRequestDetailsType()
            {
                IPAddress      = WebHelper.GetClientIpAddress(),
                PaymentAction  = authorizeOnly ? PaymentActionCodeType.AUTHORIZATION : PaymentActionCodeType.SALE,
                CreditCard     = creditCard,
                PaymentDetails = new PaymentDetailsType()
                {
                    OrderTotal = new BasicAmountType()
                    {
                        value      = Math.Round(request.Amount, 2).ToString("N", new CultureInfo("en-US")),
                        currencyID = paypalCurrency
                    },
                    Custom       = request.TransactionUniqueId,
                    ButtonSource = "mobSocial"
                }
            };

            var doDirectPaymentRequest = new DoDirectPaymentRequestType {
                Version = ApiVersion,
                DoDirectPaymentRequestDetails = doDirectPaymentRequestDetails
            };

            var paymentRequest = new DoDirectPaymentReq {
                DoDirectPaymentRequest = doDirectPaymentRequest
            };

            var service        = GetPayPalApiInterfaceServiceService();
            var paypalResponse = service.DoDirectPayment(paymentRequest);

            var result = new TransactionResult();

            string error;
            var    success = PayPalHelper.ParseResponseSuccess(paypalResponse, out error);

            if (success)
            {
                result.Success = true;
                result.SetParameter(PaymentParameterNames.AvsCode, paypalResponse.AVSCode);
                result.SetParameter(PaymentParameterNames.Cvv2Code, paypalResponse.CVV2Code);

                if (authorizeOnly)
                {
                    result.SetParameter(PaymentParameterNames.AuthorizationId, paypalResponse.TransactionID);
                    result.SetParameter(PaymentParameterNames.AuthorizationResult, paypalResponse.Ack);
                }
                else
                {
                    result.SetParameter(PaymentParameterNames.CaptureId, paypalResponse.TransactionID);
                    result.SetParameter(PaymentParameterNames.CaptureResult, paypalResponse.Ack);
                }
            }
            else
            {
                result.SetParameter(PaymentParameterNames.ErrorMessage, error);
            }

            return(result);
        }
Esempio n. 22
0
        protected void Submit_Click(object sender, EventArgs e)
        {
            // Create request object
            DoDirectPaymentRequestType        request        = new DoDirectPaymentRequestType();
            DoDirectPaymentRequestDetailsType requestDetails = new DoDirectPaymentRequestDetailsType();

            request.DoDirectPaymentRequestDetails = requestDetails;

            requestDetails.PaymentAction = (PaymentActionCodeType)
                                           Enum.Parse(typeof(PaymentActionCodeType), paymentType.SelectedValue);

            // Populate card requestDetails
            CreditCardDetailsType creditCard = new CreditCardDetailsType();

            requestDetails.CreditCard = creditCard;
            PayerInfoType  payer = new PayerInfoType();
            PersonNameType name  = new PersonNameType();

            name.FirstName       = firstName.Value;
            name.LastName        = lastName.Value;
            payer.PayerName      = name;
            creditCard.CardOwner = payer;

            creditCard.CreditCardNumber = creditCardNumber.Value;
            creditCard.CreditCardType   = (CreditCardTypeType)
                                          Enum.Parse(typeof(CreditCardTypeType), creditCardType.SelectedValue);
            creditCard.CVV2 = cvv2Number.Value;
            string[] cardExpiryDetails = cardExpiryDate.Text.Split(new char[] { '/' });
            if (cardExpiryDetails.Length == 2)
            {
                creditCard.ExpMonth = Int32.Parse(cardExpiryDetails[0]);
                creditCard.ExpYear  = Int32.Parse(cardExpiryDetails[1]);
            }

            requestDetails.PaymentDetails = new PaymentDetailsType();
            AddressType billingAddr = new AddressType();

            if (firstName.Value != "" && lastName.Value != "" &&
                street1.Value != "" && country.Value != "")
            {
                billingAddr.Name            = payerName.Value;
                billingAddr.Street1         = street1.Value;
                billingAddr.Street2         = street2.Value;
                billingAddr.CityName        = city.Value;
                billingAddr.StateOrProvince = state.Value;
                billingAddr.Country         = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), country.Value);
                billingAddr.PostalCode      = postalCode.Value;

                //Fix for release
                billingAddr.Phone = phone.Value;

                payer.Address = billingAddr;
            }

            // Populate payment requestDetails
            CurrencyCodeType currency = (CurrencyCodeType)
                                        Enum.Parse(typeof(CurrencyCodeType), currencyCode.SelectedValue);
            BasicAmountType paymentAmount = new BasicAmountType(currency, amount.Value);

            requestDetails.PaymentDetails.OrderTotal = paymentAmount;


            // Invoke the API
            DoDirectPaymentReq wrapper = new DoDirectPaymentReq();

            wrapper.DoDirectPaymentRequest = request;
            PayPalAPIInterfaceServiceService service  = new PayPalAPIInterfaceServiceService();
            DoDirectPaymentResponseType      response = service.DoDirectPayment(wrapper);

            // Check for API return status
            setKeyResponseObjects(service, response);
        }
Esempio n. 23
0
        public TransactionResult SubmitPaymentTransaction(CheckoutDetails details)
        {
            //init result structure
            TransactionResult ret = new TransactionResult();

            //set up Request
            //instantiate DoDirectPaymentRequestType and RequestDetails objects
            DoDirectPaymentRequestType request = new DoDirectPaymentRequestType();

            request.Version = PROCESSOR_VERSION;
            DoDirectPaymentRequestDetailsType requestDetails = new DoDirectPaymentRequestDetailsType();

            request.DoDirectPaymentRequestDetails = requestDetails;

            //set payment action
            requestDetails.PaymentAction = PaymentActionCodeType.Sale;

            //set IP
            //requestDetails.IPAddress = Request.UserHostAddress;
            requestDetails.IPAddress = details[CheckoutKeys.IPAddress];

            //set CreditCard info
            CreditCardDetailsType creditCardDetails = new CreditCardDetailsType();

            requestDetails.CreditCard          = creditCardDetails;
            creditCardDetails.CreditCardNumber = details[CheckoutKeys.CardNumber];
            creditCardDetails.CreditCardType   = (CreditCardTypeType)Enum.Parse(typeof(CreditCardTypeType), details[CheckoutKeys.CardType], true);
            creditCardDetails.CVV2             = details[CheckoutKeys.VerificationCode];
            creditCardDetails.ExpMonth         = Int32.Parse(details[CheckoutKeys.ExpireMonth]);
            creditCardDetails.ExpYear          = Int32.Parse(details[CheckoutKeys.ExpireYear]);
            // Switch/Solo
            if (creditCardDetails.CreditCardType == CreditCardTypeType.Solo ||
                creditCardDetails.CreditCardType == CreditCardTypeType.Switch)
            {
                creditCardDetails.StartMonth  = Int32.Parse(details[CheckoutKeys.StartMonth]);
                creditCardDetails.StartYear   = Int32.Parse(details[CheckoutKeys.StartYear]);
                creditCardDetails.IssueNumber = details[CheckoutKeys.IssueNumber];
            }

            //set billing address
            PayerInfoType cardOwner = new PayerInfoType();

            creditCardDetails.CardOwner   = cardOwner;
            cardOwner.PayerName           = new PersonNameType();
            cardOwner.PayerName.FirstName = details[CheckoutKeys.FirstName];
            cardOwner.PayerName.LastName  = details[CheckoutKeys.LastName];

            cardOwner.Address         = new AddressType();
            cardOwner.Address.Street1 = details[CheckoutKeys.Address];
            //??? cardOwner.Address.Street2 = "";
            cardOwner.Address.CityName         = details[CheckoutKeys.City];
            cardOwner.Address.StateOrProvince  = details[CheckoutKeys.State];
            cardOwner.Address.PostalCode       = details[CheckoutKeys.Zip];
            cardOwner.Address.CountrySpecified = true;
            cardOwner.Address.Country          = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), details[CheckoutKeys.Country], true);

            //set payment Details
            PaymentDetailsType paymentDetails = new PaymentDetailsType();

            requestDetails.PaymentDetails = paymentDetails;
            paymentDetails.OrderTotal     = new BasicAmountType();
            //TODO: Add currency support
            paymentDetails.OrderTotal.currencyID = (CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), details[CheckoutKeys.Currency]);
            //paymentDetails.OrderTotal.currencyID = CurrencyCodeType.USD;
            //No currency symbol. Decimal separator must be a period (.), and the thousands separator must be a comma (,)
            paymentDetails.OrderTotal.Value = details[CheckoutKeys.Amount];

            DoDirectPaymentReq paymentRequest = new DoDirectPaymentReq();

            paymentRequest.DoDirectPaymentRequest = request;

            //FINISH set up req
            //setup request Header, API credentials
            PayPalAPIAASoapBinding paypalInterface = new PayPalAPIAASoapBinding();
            UserIdPasswordType     user            = new UserIdPasswordType();

            //set api credentials - username, password, signature
            user.Username  = Username;
            user.Password  = Password;
            user.Signature = Signature;
            // setup service url
            paypalInterface.Url = ServiceUrl;
            paypalInterface.RequesterCredentials             = new CustomSecurityHeaderType();
            paypalInterface.RequesterCredentials.Credentials = user;

            //make call return response
            DoDirectPaymentResponseType paymentResponse = new DoDirectPaymentResponseType();

            paymentResponse = paypalInterface.DoDirectPayment(paymentRequest);
            //write response xml to the ret object
            ret.RawResponse = SerializeObject(paymentResponse);

            switch (paymentResponse.Ack)
            {
            case AckCodeType.Success:
            case AckCodeType.SuccessWithWarning:
                ret.Succeed           = true;
                ret.TransactionId     = paymentResponse.TransactionID;
                ret.TransactionStatus = TransactionStatus.Approved;
                break;

            default:                     // show errors if Ack is NOT Success
                ret.Succeed           = false;
                ret.TransactionStatus = TransactionStatus.Declined;
                if (paymentResponse.Errors != null &&
                    paymentResponse.Errors.Length > 0)
                {
                    ret.StatusCode = PayPalProKeys.ErrorPrefix + paymentResponse.Errors[0].ErrorCode;
                }
                break;
            }
            return(ret);
        }
Esempio n. 24
0
        protected ProcessPaymentResult AuthorizeOrSale(ProcessPaymentRequest processPaymentRequest, bool authorizeOnly)
        {
            var result = new ProcessPaymentResult();

            var customer = _customerService.GetCustomerById(processPaymentRequest.CustomerId);

            if (customer == null)
            {
                throw new Exception("Customer cannot be loaded");
            }

            var req = new DoDirectPaymentReq();

            req.DoDirectPaymentRequest         = new DoDirectPaymentRequestType();
            req.DoDirectPaymentRequest.Version = GetApiVersion();
            var details = new DoDirectPaymentRequestDetailsType();

            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails = details;
            details.IPAddress = _webHelper.GetCurrentIpAddress() ?? "";
            if (authorizeOnly)
            {
                details.PaymentAction = PaymentActionCodeType.AUTHORIZATION;
            }
            else
            {
                details.PaymentAction = PaymentActionCodeType.SALE;
            }
            //credit card
            details.CreditCard = new CreditCardDetailsType();
            details.CreditCard.CreditCardNumber       = processPaymentRequest.CreditCardNumber;
            details.CreditCard.CreditCardType         = GetPaypalCreditCardType(processPaymentRequest.CreditCardType);
            details.CreditCard.ExpMonth               = processPaymentRequest.CreditCardExpireMonth;
            details.CreditCard.ExpYear                = processPaymentRequest.CreditCardExpireYear;
            details.CreditCard.CVV2                   = processPaymentRequest.CreditCardCvv2;
            details.CreditCard.CardOwner              = new PayerInfoType();
            details.CreditCard.CardOwner.PayerCountry = GetPaypalCountryCodeType(customer.BillingAddress.Country);
            //billing address
            details.CreditCard.CardOwner.Address          = new AddressType();
            details.CreditCard.CardOwner.Address.Street1  = customer.BillingAddress.Address1;
            details.CreditCard.CardOwner.Address.Street2  = customer.BillingAddress.Address2;
            details.CreditCard.CardOwner.Address.CityName = customer.BillingAddress.City;
            if (customer.BillingAddress.StateProvince != null)
            {
                details.CreditCard.CardOwner.Address.StateOrProvince = customer.BillingAddress.StateProvince.Abbreviation;
            }
            else
            {
                details.CreditCard.CardOwner.Address.StateOrProvince = "CA";
            }
            details.CreditCard.CardOwner.Address.Country    = GetPaypalCountryCodeType(customer.BillingAddress.Country);
            details.CreditCard.CardOwner.Address.PostalCode = customer.BillingAddress.ZipPostalCode;
            details.CreditCard.CardOwner.Payer               = customer.BillingAddress.Email;
            details.CreditCard.CardOwner.PayerName           = new PersonNameType();
            details.CreditCard.CardOwner.PayerName.FirstName = customer.BillingAddress.FirstName;
            details.CreditCard.CardOwner.PayerName.LastName  = customer.BillingAddress.LastName;
            //order totals
            var payPalCurrency = PaypalHelper.GetPaypalCurrency(_currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId));

            details.PaymentDetails                       = new PaymentDetailsType();
            details.PaymentDetails.OrderTotal            = new BasicAmountType();
            details.PaymentDetails.OrderTotal.value      = Math.Round(processPaymentRequest.OrderTotal, 2).ToString("N", new CultureInfo("en-us"));
            details.PaymentDetails.OrderTotal.currencyID = payPalCurrency;
            details.PaymentDetails.Custom                = processPaymentRequest.OrderGuid.ToString();
            details.PaymentDetails.ButtonSource          = "nopCommerceCart";
            //shipping
            if (customer.ShippingAddress != null)
            {
                if (customer.ShippingAddress.StateProvince != null && customer.ShippingAddress.Country != null)
                {
                    var shippingAddress = new AddressType();
                    shippingAddress.Name                 = customer.ShippingAddress.FirstName + " " + customer.ShippingAddress.LastName;
                    shippingAddress.Street1              = customer.ShippingAddress.Address1;
                    shippingAddress.Street2              = customer.ShippingAddress.Address2;
                    shippingAddress.CityName             = customer.ShippingAddress.City;
                    shippingAddress.StateOrProvince      = customer.ShippingAddress.StateProvince.Abbreviation;
                    shippingAddress.PostalCode           = customer.ShippingAddress.ZipPostalCode;
                    shippingAddress.Country              = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), customer.ShippingAddress.Country.TwoLetterIsoCode, true);
                    details.PaymentDetails.ShipToAddress = shippingAddress;
                }
            }

            //send request
            var service = GetService();
            DoDirectPaymentResponseType response = service.DoDirectPayment(req);

            string error;
            bool   success = PaypalHelper.CheckSuccess(response, out error);

            if (success)
            {
                result.AvsResult = response.AVSCode;
                result.AuthorizationTransactionCode = response.CVV2Code;
                if (authorizeOnly)
                {
                    result.AuthorizationTransactionId     = response.TransactionID;
                    result.AuthorizationTransactionResult = response.Ack.ToString();

                    result.NewPaymentStatus = PaymentStatus.Authorized;
                }
                else
                {
                    result.CaptureTransactionId     = response.TransactionID;
                    result.CaptureTransactionResult = response.Ack.ToString();

                    result.NewPaymentStatus = PaymentStatus.Paid;
                }
            }
            else
            {
                result.AddError(error);
            }
            return(result);
        }
Esempio n. 25
0
    public PayPalReturn Pay(string orderNumber, string paymentAmount, string buyerLastName, string buyerFirstName, string buyerAddress, string buyerCity, string buyerStateOrProvince, string buyerCountryCode, string buyerCountryName, string buyerZipCode, string creditCardType, string creditCardNumber, string CVV2, string expMonth, string expYear)
    {
        //PayPal Return Structure
        PayPalReturn rv = new PayPalReturn();

        rv.IsSucess = false;

        DoDirectPaymentRequestDetailsType requestDetails = new DoDirectPaymentRequestDetailsType();

        requestDetails.CreditCard                     = new CreditCardDetailsType();
        requestDetails.CreditCard.CardOwner           = new PayerInfoType();
        requestDetails.CreditCard.CardOwner.Address   = new AddressType();
        requestDetails.PaymentDetails                 = new PaymentDetailsType();
        requestDetails.PaymentDetails.OrderTotal      = new BasicAmountType();
        requestDetails.CreditCard.CardOwner.PayerName = new PersonNameType();

        //Request
        requestDetails.PaymentAction = PaymentActionCodeType.Sale;
        requestDetails.IPAddress     = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

        //Payment
        requestDetails.PaymentDetails.OrderTotal.currencyID = CurrencyCodeType.USD;
        requestDetails.PaymentDetails.OrderTotal.Value      = paymentAmount;

        //Credit card
        requestDetails.CreditCard.CreditCardNumber        = creditCardNumber;
        requestDetails.CreditCard.CreditCardType          = (CreditCardTypeType)Enum.Parse(typeof(CreditCardTypeType), creditCardType, true);
        requestDetails.CreditCard.ExpMonth                = Convert.ToInt32(expMonth);
        requestDetails.CreditCard.ExpYear                 = Convert.ToInt32(expYear);
        requestDetails.CreditCard.CVV2                    = CVV2;
        requestDetails.CreditCard.CreditCardTypeSpecified = true;
        requestDetails.CreditCard.ExpMonthSpecified       = true;
        requestDetails.CreditCard.ExpYearSpecified        = true;

        //Card Owner
        requestDetails.CreditCard.CardOwner.PayerName.FirstName      = buyerFirstName;
        requestDetails.CreditCard.CardOwner.PayerName.LastName       = buyerLastName;
        requestDetails.CreditCard.CardOwner.Address.Street1          = buyerAddress;
        requestDetails.CreditCard.CardOwner.Address.CityName         = buyerCity;
        requestDetails.CreditCard.CardOwner.Address.StateOrProvince  = buyerStateOrProvince;
        requestDetails.CreditCard.CardOwner.Address.CountryName      = buyerCountryName;
        requestDetails.CreditCard.CardOwner.Address.Country          = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), buyerCountryCode, true);
        requestDetails.CreditCard.CardOwner.Address.PostalCode       = buyerZipCode;
        requestDetails.CreditCard.CardOwner.Address.CountrySpecified = true;
        requestDetails.CreditCard.CardOwner.PayerCountry             = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), buyerCountryCode, true);
        requestDetails.CreditCard.CardOwner.PayerCountrySpecified    = true;

        DoDirectPaymentReq request = new DoDirectPaymentReq();

        request.DoDirectPaymentRequest = new DoDirectPaymentRequestType();
        request.DoDirectPaymentRequest.DoDirectPaymentRequestDetails = requestDetails;
        request.DoDirectPaymentRequest.Version = "51.0";

        //Headers
        CustomSecurityHeaderType headers = new CustomSecurityHeaderType();

        headers.Credentials           = new UserIdPasswordType();
        headers.Credentials.Username  = ConfigurationManager.AppSettings["PayPalAPIUsername"];
        headers.Credentials.Password  = ConfigurationManager.AppSettings["PayPalAPIPassword"];
        headers.Credentials.Signature = ConfigurationManager.AppSettings["PayPalAPISignature"];

        //Client
        PayPalAPIAASoapBinding client = new PayPalAPIAASoapBinding();

        client.RequesterCredentials = headers;
        client.Timeout = 15000;
        DoDirectPaymentResponseType response = client.DoDirectPayment(request);

        if (response.Ack == AckCodeType.Success || response.Ack == AckCodeType.SuccessWithWarning)
        {
            rv.IsSucess      = true;
            rv.TransactionID = response.TransactionID;
        }
        else
        {
            rv.ErrorMessage = response.Errors[0].LongMessage;
        }
        return(rv);
    }
Esempio n. 26
0
 /// <remarks/>
 public void DoDirectPaymentAsync(DoDirectPaymentReq DoDirectPaymentReq) {
     this.DoDirectPaymentAsync(DoDirectPaymentReq, null);
 }
        // # DoDirectPaymentAPIOperation
        // The MassPay API operation makes a payment to one or more PayPal account holders.
        public static DoDirectPaymentResponseType DoDirectPaymentAPIOperation(CreditCardDetailsType creditCard, string amount)
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            // Create the DoDirectPaymentResponseType object
            DoDirectPaymentResponseType responseDoDirectPaymentResponseType = new DoDirectPaymentResponseType();

            try
            {
                // Create the DoDirectPaymentReq object
                DoDirectPaymentReq doDirectPayment = new DoDirectPaymentReq();
                DoDirectPaymentRequestDetailsType doDirectPaymentRequestDetails = new DoDirectPaymentRequestDetailsType();

                // Information about the credit card to be charged.

                doDirectPaymentRequestDetails.CreditCard = creditCard;

                // Information about the payment
                PaymentDetailsType paymentDetails = new PaymentDetailsType();

                //paymentDetails.NotifyURL = "http://IPNhost";
                BasicAmountType orderTotal = new BasicAmountType(CurrencyCodeType.CAD, amount);
                paymentDetails.OrderTotal = orderTotal;
                doDirectPaymentRequestDetails.PaymentDetails = paymentDetails;

                // IP address of the buyer's browser.
                // `Note:
                // PayPal records this IP addresses as a means to detect possible fraud.`
                doDirectPaymentRequestDetails.IPAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; //127.0.0.1";

                DoDirectPaymentRequestType doDirectPaymentRequest = new DoDirectPaymentRequestType(doDirectPaymentRequestDetails);
                doDirectPayment.DoDirectPaymentRequest = doDirectPaymentRequest;

                // Create the service wrapper object to make the API call
                PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService();

                // # API call
                // Invoke the DoDirectPayment method in service wrapper object
                responseDoDirectPaymentResponseType = service.DoDirectPayment(doDirectPayment);

                if (responseDoDirectPaymentResponseType != null)
                {
                    // Response envelope acknowledgement
                    string acknowledgement = "DoDirectPayment API Operation - ";
                    acknowledgement += responseDoDirectPaymentResponseType.Ack.ToString();
                    logger.Info(acknowledgement + "\n");
                    HttpContext.Current.Session["acknowledgement"] = acknowledgement;

                    // # Success values
                    if (responseDoDirectPaymentResponseType.Ack.ToString().Trim().ToUpper().Equals("SUCCESS"))
                    {
                        // Unique identifier of the transaction
                        logger.Info("Transaction ID : " + responseDoDirectPaymentResponseType.TransactionID + "\n");
                        HttpContext.Current.Session["acknowledgement"] = string.Concat("Transaction ID : ", responseDoDirectPaymentResponseType.TransactionID, "<br />");
                    }
                    // # Error Values
                    else
                    {
                        List <ErrorType> errorMessages = responseDoDirectPaymentResponseType.Errors;
                        foreach (ErrorType error in errorMessages)
                        {
                            logger.Debug("API Error Message : " + error.LongMessage);
                            HttpContext.Current.Session["acknowledgement"] = string.Concat("API Error Message : ", error.LongMessage, "<br />");
                        }
                    }
                }
            }
            // # Exception log
            catch (System.Exception ex)
            {
                // Log the exception message
                logger.Debug("Error Message : " + ex.Message);
                // Console.WriteLine("Error Message : " + ex.Message);
            }
            return(responseDoDirectPaymentResponseType);
        }
Esempio n. 28
0
        // ProcessCard() is used for Credit Card processing via Website Payments Pro,
        // just like other credit card gateways.
        // ProcessPaypal() is used for Express Checkout and PayPal payments.
        public override string ProcessCard(int OrderNumber, int CustomerID, decimal OrderTotal, bool useLiveTransactions, TransactionModeEnum TransactionMode, Address UseBillingAddress, string CardExtraCode, 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)
        {
            String result = AppLogic.ro_OK;

            AuthorizationCode     = String.Empty;
            AuthorizationResult   = String.Empty;
            AuthorizationTransID  = String.Empty;
            AVSResult             = String.Empty;
            TransactionCommandOut = String.Empty;
            TransactionResponse   = String.Empty;
            try
            {
                // the request details object contains all payment details
                DoDirectPaymentRequestDetailsType RequestDetails = new DoDirectPaymentRequestDetailsType();

                // define the payment action to 'Sale'
                // (another option is 'Authorization', which would be followed later with a DoCapture API call)
                RequestDetails.PaymentAction = (PaymentActionCodeType)CommonLogic.IIF(AppLogic.TransactionModeIsAuthOnly(), (int)PaymentActionCodeType.Authorization, (int)PaymentActionCodeType.Sale);

                // define the total amount and currency for the transaction
                PaymentDetailsType PaymentDetails = new PaymentDetailsType();

                BasicAmountType totalAmount = new BasicAmountType();
                totalAmount.Value               = Localization.CurrencyStringForGatewayWithoutExchangeRate(OrderTotal);
                totalAmount.currencyID          = (CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), AppLogic.AppConfig("Localization.StoreCurrency"), true);
                PaymentDetails.OrderTotal       = totalAmount;
                PaymentDetails.InvoiceID        = OrderNumber.ToString();
                PaymentDetails.ButtonSource     = PayPal.BN + "_DP_US";
                PaymentDetails.OrderDescription = AppLogic.AppConfig("StoreName");

                // define the credit card to be used

                CreditCardDetailsType creditCard = new CreditCardDetailsType();
                creditCard.CreditCardNumber  = UseBillingAddress.CardNumber;
                creditCard.ExpMonth          = Localization.ParseUSInt(UseBillingAddress.CardExpirationMonth);
                creditCard.ExpYear           = Localization.ParseUSInt(UseBillingAddress.CardExpirationYear);
                creditCard.ExpMonthSpecified = true;
                creditCard.ExpYearSpecified  = true;
                creditCard.CVV2 = CardExtraCode;

                if (UseBillingAddress.CardType == "AmericanExpress")
                {
                    creditCard.CreditCardType = (CreditCardTypeType)Enum.Parse(typeof(CreditCardTypeType), "Amex", true);
                }
                else
                {
                    creditCard.CreditCardType = (CreditCardTypeType)Enum.Parse(typeof(CreditCardTypeType), UseBillingAddress.CardType, true);
                }
                creditCard.CreditCardTypeSpecified = true;

                PayerInfoType  cardHolder      = new PayerInfoType();
                PersonNameType oPersonNameType = new PersonNameType();
                oPersonNameType.FirstName  = UseBillingAddress.FirstName;
                oPersonNameType.LastName   = UseBillingAddress.LastName;
                oPersonNameType.MiddleName = String.Empty;
                oPersonNameType.Salutation = String.Empty;
                oPersonNameType.Suffix     = String.Empty;
                cardHolder.PayerName       = oPersonNameType;

                AddressType PayerAddress = new AddressType();
                PayerAddress.Street1          = UseBillingAddress.Address1;
                PayerAddress.CityName         = UseBillingAddress.City;
                PayerAddress.StateOrProvince  = UseBillingAddress.State;
                PayerAddress.PostalCode       = UseBillingAddress.Zip;
                PayerAddress.Country          = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), AppLogic.GetCountryTwoLetterISOCode(UseBillingAddress.Country), true);
                PayerAddress.CountrySpecified = true;

                if (UseShippingAddress != null)
                {
                    AddressType shippingAddress = new AddressType();
                    shippingAddress.Name             = (UseShippingAddress.FirstName + " " + UseShippingAddress.LastName).Trim();
                    shippingAddress.Street1          = UseShippingAddress.Address1;
                    shippingAddress.Street2          = UseShippingAddress.Address2 + CommonLogic.IIF(UseShippingAddress.Suite != "", " Ste " + UseShippingAddress.Suite, "");
                    shippingAddress.CityName         = UseShippingAddress.City;
                    shippingAddress.StateOrProvince  = UseShippingAddress.State;
                    shippingAddress.PostalCode       = UseShippingAddress.Zip;
                    shippingAddress.Country          = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), AppLogic.GetCountryTwoLetterISOCode(UseShippingAddress.Country), true);
                    shippingAddress.CountrySpecified = true;
                    PaymentDetails.ShipToAddress     = shippingAddress;
                }

                cardHolder.Address   = PayerAddress;
                creditCard.CardOwner = cardHolder;

                RequestDetails.CreditCard     = creditCard;
                RequestDetails.PaymentDetails = PaymentDetails;
                RequestDetails.IPAddress      = CommonLogic.CustomerIpAddress();            // cart.ThisCustomer.LastIPAddress;

                if (RequestDetails.IPAddress == "::1")
                {
                    RequestDetails.IPAddress = "127.0.0.1";
                }

                // instantiate the actual request object
                PaymentRequest         = new DoDirectPaymentRequestType();
                PaymentRequest.Version = API_VER;
                PaymentRequest.DoDirectPaymentRequestDetails = RequestDetails;
                DDPReq = new DoDirectPaymentReq();
                DDPReq.DoDirectPaymentRequest = PaymentRequest;

                DoDirectPaymentResponseType responseDetails = (DoDirectPaymentResponseType)IPayPal.DoDirectPayment(DDPReq);

                //if (LogToErrorTable)
                //{
                //    PayPalController.Log(XmlCommon.SerializeObject(DDPReq, DDPReq.GetType()), "DoDirectPayment Request");
                //    PayPalController.Log(XmlCommon.SerializeObject(responseDetails, responseDetails.GetType()), "DoDirectPayment Response");
                //}

                if (responseDetails != null && responseDetails.Ack.ToString().StartsWith("success", StringComparison.InvariantCultureIgnoreCase))
                {
                    AuthorizationTransID = CommonLogic.IIF(TransactionMode.ToString().ToLower() == AppLogic.ro_TXModeAuthOnly.ToLower(), "AUTH=", "CAPTURE=") + responseDetails.TransactionID.ToString();
                    AuthorizationCode    = responseDetails.CorrelationID;
                    AVSResult            = responseDetails.AVSCode;
                    result = AppLogic.ro_OK;
                    AuthorizationResult = responseDetails.Ack.ToString() + "|AVSCode=" + responseDetails.AVSCode.ToString() + "|CVV2Code=" + responseDetails.CVV2Code.ToString();
                }
                else
                {
                    if (responseDetails.Errors != null)
                    {
                        String Separator = String.Empty;
                        for (int ix = 0; ix < responseDetails.Errors.Length; ix++)
                        {
                            AuthorizationResult += Separator;
                            AuthorizationResult += responseDetails.Errors[ix].LongMessage;                            // record failed TX
                            TransactionResponse += Separator;
                            try
                            {
                                TransactionResponse += String.Format("|{0},{1},{2}|", responseDetails.Errors[ix].ShortMessage, responseDetails.Errors[ix].ErrorCode, responseDetails.Errors[ix].LongMessage);                                 // record failed TX
                            }
                            catch { }
                            Separator = ", ";
                        }
                    }
                    result = AuthorizationResult;
                    // just store something here, as there is no other way to get data out of this gateway about the failure for logging in failed transaction table
                }
            }
            catch
            {
                result = "Transaction Failed";
            }
            return(result);
        }
Esempio n. 29
0
        public Commerce.Common.Transaction DoDirectCheckout(Commerce.Common.Order order, bool AuthOnly)
        {
            PayPalSvc.DoDirectPaymentReq req = new DoDirectPaymentReq();
            req.DoDirectPaymentRequest         = new DoDirectPaymentRequestType();
            req.DoDirectPaymentRequest.Version = PayPalServiceUtility.PayPalAPIVersionNumber;

            DoDirectPaymentRequestDetailsType details = new DoDirectPaymentRequestDetailsType();

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

            CountryCodeType payerCountry = CountryCodeType.US;

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

            details.CreditCard.CardOwner.Address.Country = payerCountry;
            details.CreditCard.CardOwner.PayerCountry    = payerCountry;

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

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


            //the basics
            int     roundTo = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalDigits;
            decimal dTotal  = Math.Round(order.CalculateSubTotal(), roundTo) + Math.Round(order.TaxAmount, roundTo) + Math.Round(order.ShippingAmount, roundTo);

            details.PaymentDetails.OrderTotal    = GetBasicAmount(dTotal);
            details.PaymentDetails.ShippingTotal = this.GetBasicAmount(Math.Round(order.ShippingAmount, roundTo));
            details.PaymentDetails.TaxTotal      = this.GetBasicAmount(Math.Round(order.TaxAmount, roundTo));
            details.PaymentDetails.Custom        = order.OrderNumber;
            details.PaymentDetails.ItemTotal     = GetBasicAmount(Math.Round(order.CalculateSubTotal(), roundTo));
            details.PaymentDetails.ButtonSource  = DP_BN_ID;



            //credit card
            details.CreditCard.CreditCardNumber = order.CreditCardNumber;
            CreditCardTypeType ccType = CreditCardTypeType.Visa;

            switch (order.CreditCardType)
            {
            case Commerce.Common.CreditCardType.MasterCard:
                ccType = CreditCardTypeType.MasterCard;
                break;

            case Commerce.Common.CreditCardType.Amex:
                ccType = CreditCardTypeType.Amex;
                break;
            }

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

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

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

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

            //send the request
            DoDirectPaymentResponseType response = service2.DoDirectPayment(req);

            string errors = this.CheckErrors(response);

            Commerce.Common.Transaction trans = new Commerce.Common.Transaction();
            trans.OrderID = order.OrderID;

            string sOut = "";

            if (errors == string.Empty)
            {
                trans.GatewayResponse   = response.Ack.ToString();
                trans.AuthorizationCode = response.TransactionID;
                trans.CVV2Code          = response.CVV2Code;
            }
            else
            {
                trans.GatewayResponse = errors;
                throw new Exception(errors);
            }
            return(trans);
        }