private CreditCardDetailsType GetCreditCardDetails()
        {
            var retVal = new CreditCardDetailsType();

            retVal.CreditCardNumber = "4539715785713186";
            retVal.CreditCardType   = CreditCardTypeType.VISA;
            retVal.ExpMonth         = 11;
            retVal.ExpYear          = 2022;
            retVal.CVV2             = "111";
            retVal.CardOwner        = new PayerInfoType();

            var billingAddress = GetValidAddress();

            retVal.CardOwner.Address                 = new PayPal.PayPalAPIInterfaceService.Model.AddressType();
            retVal.CardOwner.Address.Street1         = billingAddress.Line1;
            retVal.CardOwner.Address.Street2         = billingAddress.Line2;
            retVal.CardOwner.Address.CityName        = billingAddress.City;
            retVal.CardOwner.Address.StateOrProvince = billingAddress.RegionName;

            retVal.CardOwner.Address.Country    = CountryCodeType.US;
            retVal.CardOwner.Address.PostalCode = billingAddress.Zip;
            retVal.CardOwner.Payer               = billingAddress.Email;
            retVal.CardOwner.PayerName           = new PersonNameType();
            retVal.CardOwner.PayerName.FirstName = billingAddress.FirstName;
            retVal.CardOwner.PayerName.LastName  = billingAddress.LastName;
            retVal.CardOwner.PayerCountry        = CountryCodeType.US;

            return(retVal);
        }
Esempio n. 2
0
        private CreditCardDetailsType MapCardDetails(string CCNumber, 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)
        {
            var details          = new CreditCardDetailsType();
            var payerInfo        = new PayerInfoType();
            var address          = new AddressType();
            var personalNameType = new PersonNameType();

            // var cardType = MapCardType(CardType);

            personalNameType.FirstName = FirstName;
            personalNameType.LastName  = LastName;

            payerInfo.Address      = address;
            payerInfo.ContactPhone = Telephone;
            payerInfo.PayerName    = personalNameType;

            details.CardOwner        = payerInfo;
            details.CreditCardNumber = CCNumber;
            //      details.CreditCardType = cardType;
            details.CVV2     = CVC2;
            details.ExpMonth = int.Parse(ExpiryMonth);
            details.ExpYear  = int.Parse(ExpiryYear);

            return(details);
        }
        protected void GetPaid(string itemType, string aditem, string amnt, CreditCardDetailsType cc)
        {
            HttpContext CurrContext = HttpContext.Current;

            //amnt = "1.00";
            try
            {
                DoDirectPaymentResponseType reply = DirectPayment.DoDirectPaymentAPIOperation(cc, amnt);
                Session["Reply"]       = reply;
                Session["PaymentInfo"] = cc;
                if (reply.Ack.ToString().Trim().ToUpper().Equals("SUCCESS"))
                {
                    switch (itemType)
                    {
                    case "car":
                        VehiclesBilling vb = Session["VehicleBilling"] as VehiclesBilling;
                        vb.PayPalId    = reply.TransactionID;
                        vb.PayPalState = reply.Ack.ToString();
                        vb.CreateTime  = Convert.ToDateTime(reply.Timestamp);
                        if (VehiclesBilling.PaidInFull(vb))
                        {
                            CustomerVehicleInfo.UpdateBillingId(Convert.ToInt32(Session["VehicleId"]), vb.Id);
                            NotifyCustomer(Convert.ToInt32(Session["VehicleId"]), itemType, vb.Payment, "0", reply.TransactionID);
                            NotifyAdmin(Request.QueryString["item"], vb.Payment, "0", reply.TransactionID);
                        }
                        break;

                    case "ad":
                        AdsBilling ad = new AdsBilling
                        {
                            CustomerId  = Convert.ToInt32(Session["CustomerId"]),
                            AdId        = Convert.ToInt32(Request.QueryString["id"]),
                            Payment     = Convert.ToDouble(amnt),
                            PayPalId    = reply.TransactionID,
                            PayPalState = reply.Ack.ToString(),
                            CreateTime  = Convert.ToDateTime(reply.Timestamp)
                        };
                        if (AdsBilling.InsertNewBilling(ad))
                        {
                            CustomerAd.PaidInFull(ad.AdId);
                            NotifyCustomer(ad.AdId, itemType, ad.Payment, "0", reply.TransactionID);
                            NotifyAdmin(Request.QueryString["item"], ad.Payment, "0", reply.TransactionID);
                        }
                        break;
                    }
                }
                else
                {
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Error", " alert('Transaction failed, please check your credit card information and try again.');", true);
                    //Server.Transfer("~/account/PaymentResponse.aspx");
                }
            }
            catch (WebException ex)
            {
                CurrContext.Items.Add("Error", ex.Message);
                ErrorHandler.writeExceptionToLogFile(ex);
            }
        }
        private CreditCardDetailsType GetCreditCardDetails(ProcessPaymentEvaluationContext context)
        {
            var retVal = new CreditCardDetailsType();

            retVal.CreditCardNumber = context.BankCardInfo.BankCardNumber;
            retVal.CreditCardType   = GetPaypalCreditCardType(context.BankCardInfo.BankCardType);
            retVal.ExpMonth         = context.BankCardInfo.BankCardMonth;
            retVal.ExpYear          = (context.BankCardInfo.BankCardYear < 100 ? 2000 : 0) + context.BankCardInfo.BankCardYear;
            retVal.CVV2             = context.BankCardInfo.BankCardCVV2;
            retVal.CardOwner        = new PayerInfoType();

            if (context.Order.Addresses.Any(x => x.AddressType == VirtoCommerce.Domain.Commerce.Model.AddressType.Billing))
            {
                var billingAddress = context.Order.Addresses.FirstOrDefault(x => x.AddressType == VirtoCommerce.Domain.Commerce.Model.AddressType.Billing);
                retVal.CardOwner.PayerCountry = GetPaypalCountryCodeType(billingAddress.CountryCode);

                retVal.CardOwner.Address                 = new PayPal.PayPalAPIInterfaceService.Model.AddressType();
                retVal.CardOwner.Address.Street1         = billingAddress.Line1;
                retVal.CardOwner.Address.Street2         = billingAddress.Line2;
                retVal.CardOwner.Address.CityName        = billingAddress.City;
                retVal.CardOwner.Address.StateOrProvince = billingAddress.RegionName;

                retVal.CardOwner.Address.Country    = GetPaypalCountryCodeType(billingAddress.CountryCode);
                retVal.CardOwner.Address.PostalCode = billingAddress.Zip;
                retVal.CardOwner.Payer               = billingAddress.Email;
                retVal.CardOwner.PayerName           = new PersonNameType();
                retVal.CardOwner.PayerName.FirstName = billingAddress.FirstName;
                retVal.CardOwner.PayerName.LastName  = billingAddress.LastName;
            }
            else if (context.Order.Addresses.Any())
            {
                var billingAddress = context.Order.Addresses.FirstOrDefault();
                retVal.CardOwner.PayerCountry = GetPaypalCountryCodeType(billingAddress.CountryCode);

                retVal.CardOwner.Address                 = new PayPal.PayPalAPIInterfaceService.Model.AddressType();
                retVal.CardOwner.Address.Street1         = billingAddress.Line1;
                retVal.CardOwner.Address.Street2         = billingAddress.Line2;
                retVal.CardOwner.Address.CityName        = billingAddress.City;
                retVal.CardOwner.Address.StateOrProvince = billingAddress.RegionName;

                retVal.CardOwner.Address.Country    = GetPaypalCountryCodeType(billingAddress.CountryCode);
                retVal.CardOwner.Address.PostalCode = billingAddress.Zip;
                retVal.CardOwner.Payer               = billingAddress.Email;
                retVal.CardOwner.PayerName           = new PersonNameType();
                retVal.CardOwner.PayerName.FirstName = billingAddress.FirstName;
                retVal.CardOwner.PayerName.LastName  = billingAddress.LastName;
            }
            else
            {
                throw new NullReferenceException("no billing address");
            }

            return(retVal);
        }
        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));
        }
        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 NotifyCustomer(int itemId, string item, double payment, string promo, string replyid)
        {
            Customer      c   = (Customer)Session["User"];
            StringBuilder msg = new StringBuilder();

            msg.Append(string.Concat("<p>Hi ", c.FirstName, ",</p>"));
            msg.Append("<p>Thanks for placing an ad with emonthlies.com. Just one more step to verify your ad. ");
            msg.Append(string.Concat("<a href='https://www.emonthlies.com/confirmad.aspx?item=", item, "&id=", itemId, "'>"));
            msg.Append("Confirm your ad</a>. We will approve your ad in 12 - 24 hours.</p>");
            if (promo != "1")
            {
                CreditCardDetailsType cc  = (CreditCardDetailsType)Session["PaymentInfo"] as CreditCardDetailsType;
                string credit_card_type   = cc.CreditCardType.Value.ToString();
                string credit_card_number = cc.CreditCardNumber;
                msg.Append(string.Concat("<p>Your ", credit_card_type, " ending with ", credit_card_number.Remove(0, credit_card_number.Length - 4), " will be charged the amount of "));
                msg.Append("<p>" + payment.ToString(@"$#,##0.00") + "</p>");
                msg.Append(string.Concat("<p>Pleaes keep the payment id <strong>", replyid, "</strong> for reference.</p>"));
            }
            else
            {
                msg.Append("<p>This ad is a free promotional ad.</p>");
            }
            if (item == "car")
            {
                msg.Append("<p>This posting is valid for 30 days and will automatically discontinue. ");
            }
            else
            {
                msg.Append("<p>This ad is valid for 30 days and will automatically discontinue. ");
            }
            msg.Append("<p>Thanks for your business,<br />Your emonthlies sales team</p>");

            if (Mailer.SendMail2Client(c.Email, msg.ToString(), "Confirm your ad") == false)
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "info", " alert('We could not send you an email to verify your ad at this time.');", true);
            }
        }
Esempio n. 8
0
        protected void Submit_Click(object sender, EventArgs e)
        {
            // Create request object
            DoNonReferencedCreditRequestType request = new DoNonReferencedCreditRequestType();

            request.DoNonReferencedCreditRequestDetails = new DoNonReferencedCreditRequestDetailsType();

            CurrencyCodeType currency = (CurrencyCodeType)
                                        Enum.Parse(typeof(CurrencyCodeType), currencyId.Value);

            request.DoNonReferencedCreditRequestDetails.Amount = new BasicAmountType(currency, itemAmount.Value);

            CreditCardDetailsType creditCard = new CreditCardDetailsType();

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

            if (comment.Value != "")
            {
                request.DoNonReferencedCreditRequestDetails.Comment = comment.Value;
            }
            // Invoke the API
            DoNonReferencedCreditReq wrapper = new DoNonReferencedCreditReq();

            wrapper.DoNonReferencedCreditRequest = request;
            PayPalAPIInterfaceServiceService  service = new PayPalAPIInterfaceServiceService();
            DoNonReferencedCreditResponseType DoNonReferencedCreditResponse = service.DoNonReferencedCredit(wrapper);

            // Check for API return status
            setKeyResponseObjects(service, DoNonReferencedCreditResponse);
        }
        protected void Submit_Click(object sender, EventArgs e)
        {
            // Create request object
            DoNonReferencedCreditRequestType request = new DoNonReferencedCreditRequestType();

            request.DoNonReferencedCreditRequestDetails = new DoNonReferencedCreditRequestDetailsType();

            // (Required) Total of order, including shipping, handling, and tax. Amount = NetAmount + ShippingAmount + TaxAmount
            // Character length and limitations: Must not exceed $10,000 USD in any currency. No currency symbol. Must have 2 decimal places, decimal separator must be a period (.), and the optional thousands separator must be a comma (,).
            CurrencyCodeType currency = (CurrencyCodeType)
                                        Enum.Parse(typeof(CurrencyCodeType), currencyId.Value);

            request.DoNonReferencedCreditRequestDetails.Amount = new BasicAmountType(currency, itemAmount.Value);
            // (Required) Information about the credit card to be charged.
            CreditCardDetailsType creditCard = new CreditCardDetailsType();

            request.DoNonReferencedCreditRequestDetails.CreditCard = creditCard;
            // (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.
            creditCard.CVV2 = cvv.Value;
            string[] cardExpiryDetails = cardExpiryDate.Text.Split(new char[] { '/' });

            // (Required) Credit card expiration month.
            if (cardExpiryDetails.Length > 0 && !string.IsNullOrEmpty(cardExpiryDetails[0]))
            {
                int month = 0;
                Int32.TryParse(cardExpiryDetails[0], out month);
                creditCard.ExpMonth = month;
            }

            // (Required) Credit card expiration year.
            if (cardExpiryDetails.Length > 1 && !string.IsNullOrEmpty(cardExpiryDetails[1]))
            {
                int year = 0;
                Int32.TryParse(cardExpiryDetails[1], out year);
                creditCard.ExpYear = year;
            }

            // (Optional) Field used by merchant to record why this credit was issued to a buyer. It is similar to a "memo" field (freeform text or string field).
            if (comment.Value != string.Empty)
            {
                request.DoNonReferencedCreditRequestDetails.Comment = comment.Value;
            }
            // Invoke the API
            DoNonReferencedCreditReq wrapper = new DoNonReferencedCreditReq();

            wrapper.DoNonReferencedCreditRequest = 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 DoNonReferencedCredit method in service wrapper object
            DoNonReferencedCreditResponseType DoNonReferencedCreditResponse = service.DoNonReferencedCredit(wrapper);

            // Check for API return status
            setKeyResponseObjects(service, DoNonReferencedCreditResponse);
        }
Esempio n. 10
0
        private void populateRequest(CreateRecurringPaymentsProfileRequestType request)
        {
            CurrencyCodeType currency = (CurrencyCodeType)
                                        Enum.Parse(typeof(CurrencyCodeType), "USD");

            // Set EC-Token or Credit card requestDetails
            CreateRecurringPaymentsProfileRequestDetailsType profileDetails = new CreateRecurringPaymentsProfileRequestDetailsType();

            request.CreateRecurringPaymentsProfileRequestDetails = profileDetails;

            if (token.Value != "")
            {
                profileDetails.Token = token.Value;
            }
            else if (creditCardNumber.Value != "" && cvv.Value != "")
            {
                CreditCardDetailsType cc = new CreditCardDetailsType();
                cc.CreditCardNumber       = creditCardNumber.Value;
                cc.CVV2                   = cvv.Value;
                cc.ExpMonth               = Int32.Parse(expMonth.SelectedValue);
                cc.ExpYear                = Int32.Parse(expYear.SelectedValue);
                profileDetails.CreditCard = cc;
            }


            // Populate Recurring Payments Profile Details
            RecurringPaymentsProfileDetailsType rpProfileDetails =
                new RecurringPaymentsProfileDetailsType(billingStartDate.Text);

            profileDetails.RecurringPaymentsProfileDetails = rpProfileDetails;
            if (subscriberName.Value != "")
            {
                rpProfileDetails.SubscriberName = subscriberName.Value;
            }
            if (shippingName.Value != "" && shippingStreet1.Value != "" && shippingCity.Value != "" &&
                shippingState.Value != "" && shippingPostalCode.Value != "" && shippingCountry.Value != "")
            {
                AddressType shippingAddr = new AddressType();
                shippingAddr.Name            = shippingName.Value;
                shippingAddr.Street1         = shippingStreet1.Value;
                shippingAddr.CityName        = shippingCity.Value;
                shippingAddr.StateOrProvince = shippingCity.Value;
                shippingAddr.CountryName     = shippingCountry.Value;
                shippingAddr.PostalCode      = shippingPostalCode.Value;

                if (shippingStreet2.Value != "")
                {
                    shippingAddr.Street2 = shippingStreet2.Value;
                }
                if (shippingPhone.Value != "")
                {
                    shippingAddr.Phone = shippingPhone.Value;
                }
                rpProfileDetails.SubscriberShippingAddress = shippingAddr;
            }


            // Populate schedule requestDetails
            ScheduleDetailsType scheduleDetails = new ScheduleDetailsType();

            profileDetails.ScheduleDetails = scheduleDetails;
            if (profileDescription.Value != "")
            {
                scheduleDetails.Description = profileDescription.Value;
            }
            if (maxFailedPayments.Value != "")
            {
                scheduleDetails.MaxFailedPayments = Int32.Parse(maxFailedPayments.Value);
            }
            if (autoBillOutstandingAmount.SelectedIndex != 0)
            {
                scheduleDetails.AutoBillOutstandingAmount = (AutoBillType)
                                                            Enum.Parse(typeof(AutoBillType), autoBillOutstandingAmount.SelectedValue);
            }
            if (initialAmount.Value != "")
            {
                ActivationDetailsType activationDetails =
                    new ActivationDetailsType(new BasicAmountType(currency, initialAmount.Value));
                if (failedInitialAmountAction.SelectedIndex != 0)
                {
                    activationDetails.FailedInitialAmountAction = (FailedPaymentActionType)
                                                                  Enum.Parse(typeof(FailedPaymentActionType), failedInitialAmountAction.SelectedValue);
                }
                scheduleDetails.ActivationDetails = activationDetails;
            }
            if (trialBillingAmount.Value != "" && trialBillingFrequency.Value != "" &&
                trialBillingCycles.Value != "")
            {
                int               frequency     = Int32.Parse(trialBillingFrequency.Value);
                BasicAmountType   paymentAmount = new BasicAmountType(currency, trialBillingAmount.Value);
                BillingPeriodType period        = (BillingPeriodType)
                                                  Enum.Parse(typeof(BillingPeriodType), trialBillingPeriod.SelectedValue);
                int numCycles = Int32.Parse(trialBillingCycles.Value);

                BillingPeriodDetailsType trialPeriod = new BillingPeriodDetailsType(period, frequency, paymentAmount);
                trialPeriod.TotalBillingCycles = numCycles;
                if (trialShippingAmount.Value != "")
                {
                    trialPeriod.ShippingAmount = new BasicAmountType(currency, trialShippingAmount.Value);
                }
                if (trialTaxAmount.Value != "")
                {
                    trialPeriod.TaxAmount = new BasicAmountType(currency, trialTaxAmount.Value);
                }

                scheduleDetails.TrialPeriod = trialPeriod;
            }
            if (billingAmount.Value != "" && billingFrequency.Value != "" &&
                totalBillingCycles.Value != "")
            {
                int               frequency     = Int32.Parse(billingFrequency.Value);
                BasicAmountType   paymentAmount = new BasicAmountType(currency, billingAmount.Value);
                BillingPeriodType period        = (BillingPeriodType)
                                                  Enum.Parse(typeof(BillingPeriodType), billingPeriod.SelectedValue);
                int numCycles = Int32.Parse(totalBillingCycles.Value);

                BillingPeriodDetailsType paymentPeriod = new BillingPeriodDetailsType(period, frequency, paymentAmount);
                paymentPeriod.TotalBillingCycles = numCycles;
                if (trialShippingAmount.Value != "")
                {
                    paymentPeriod.ShippingAmount = new BasicAmountType(currency, shippingAmount.Value);
                }
                if (trialTaxAmount.Value != "")
                {
                    paymentPeriod.TaxAmount = new BasicAmountType(currency, taxAmount.Value);
                }
                scheduleDetails.PaymentPeriod = paymentPeriod;
            }
        }
Esempio n. 11
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. 12
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. 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
        private void populateRequestObject(UpdateRecurringPaymentsProfileRequestType request)
        {
            CurrencyCodeType currency = (CurrencyCodeType)
                                        Enum.Parse(typeof(CurrencyCodeType), "USD");
            // Set EC-Token or Credit card requestDetails
            UpdateRecurringPaymentsProfileRequestDetailsType profileDetails = new UpdateRecurringPaymentsProfileRequestDetailsType();

            request.UpdateRecurringPaymentsProfileRequestDetails = profileDetails;

            // (Required) Recurring payments profile ID returned in the CreateRecurringPaymentsProfile response.
            profileDetails.ProfileID = profileId.Value;
            // (Optional) The reason for the update to the recurring payments profile. This message is included in the email notification to the buyer for the recurring payments profile update. This note can also be seen by both you and the buyer on the Status History page of the PayPal account.
            if (note.Value != string.Empty)
            {
                profileDetails.Note = note.Value;
            }
            // Populate Recurring Payments Profile Details
            // (Optional) Full name of the person receiving the product or service paid for by the recurring payment. If not present, the name in the buyer's PayPal account is used.
            if (subscriberName.Value != string.Empty)
            {
                profileDetails.SubscriberName = subscriberName.Value;
            }
            // (Optional) The subscriber's shipping address associated with this profile, if applicable. If you do not specify it, the ship-to address from buyer's PayPal account is used.
            // Note: Shipping Address is optional, but if you update any of the address fields, you must enter all of them. For example, if you want to update the subscriber's street address, you must specify all of the fields listed in ShipTo: AddressType, not just the field for the street address.
            if (shippingName.Value != string.Empty && shippingStreet1.Value != string.Empty && shippingCity.Value != string.Empty &&
                shippingState.Value != string.Empty && shippingPostalCode.Value != string.Empty && shippingCountry.Value != string.Empty)
            {
                AddressType shippingAddr = new AddressType();
                // Person's name associated with this shipping address. It is required if using a shipping address.
                shippingAddr.Name = shippingName.Value;
                // First street address. It is required if using a shipping address.
                shippingAddr.Street1 = shippingStreet1.Value;
                // Name of city. It is required if using a shipping address.
                shippingAddr.CityName = shippingCity.Value;
                // State or province. It is required if using a shipping address.
                shippingAddr.StateOrProvince = shippingState.Value;
                // Country code. It is required if using a shipping address.
                shippingAddr.CountryName = shippingCountry.Value;
                // U.S. ZIP code or other country-specific postal code. It is required if using a U.S. shipping address; may be required for other countries.
                shippingAddr.PostalCode = shippingPostalCode.Value;

                // (Optional) Second street address.
                if (shippingStreet2.Value != string.Empty)
                {
                    shippingAddr.Street2 = shippingStreet2.Value;
                }
                // (Optional) Phone number.
                if (shippingPhone.Value != string.Empty)
                {
                    shippingAddr.Phone = shippingPhone.Value;
                }
                profileDetails.SubscriberShippingAddress = shippingAddr;
            }
            // (Optional) The number of additional billing cycles to add to this profile.
            if (additionalBillingCycles.Value != string.Empty)
            {
                profileDetails.AdditionalBillingCycles = Convert.ToInt32(additionalBillingCycles.Value);
            }
            // (Optional) Billing amount for each cycle in the subscription period, not including shipping and tax amounts.
            // Note: For recurring payments with Express Checkout, the payment amount can be increased by no more than 20% every 180 days (starting when the profile is created).
            if (amount.Value != string.Empty)
            {
                profileDetails.Amount = new BasicAmountType(currency, amount.Value);
            }
            // (Optional) The current past due or outstanding amount for this profile. You can only decrease the outstanding amount. It cannot be increased.
            if (outstandingBalance.Value != string.Empty)
            {
                profileDetails.OutstandingBalance =
                    new BasicAmountType(currency, outstandingBalance.Value);
            }
            // (Optional) The number of failed payments allowed before the profile is automatically suspended. The specified value cannot be less than the current number of failed payments for this profile.
            if (maxFailedPayments.Value != string.Empty)
            {
                profileDetails.MaxFailedPayments = Convert.ToInt32(maxFailedPayments.Value);
            }
            // (Optional) This field indicates whether you would like PayPal to automatically bill the outstanding balance amount in the next billing cycle. It is one of the following values:
            // * NoAutoBill – PayPal does not automatically bill the outstanding balance.
            // * AddToNextBilling – PayPal automatically bills the outstanding balance
            if (autoBillOutstandingAmount.SelectedIndex != 0)
            {
                profileDetails.AutoBillOutstandingAmount = (AutoBillType)
                                                           Enum.Parse(typeof(AutoBillType), autoBillOutstandingAmount.SelectedValue);
            }
            // (Optional) The date when billing for this profile begins.
            // Note: The profile may take up to 24 hours for activation.
            if (billingStartDate.Text != string.Empty)
            {
                profileDetails.BillingStartDate = billingStartDate.Text;
            }
            // (Optional) Credit card information for this profile, if applicable. Credit card billing address is optional, but if you update any of the address fields, you must enter all of them. For example, if you want to update the street address, you must specify all of the address fields listed in CreditCardDetailsType, not just the field for the street address.
            // Note: Only enter credit card details for recurring payments with direct payments.
            if (creditCardNumber.Value != string.Empty && cvv.Value != string.Empty)
            {
                CreditCardDetailsType cc = new CreditCardDetailsType();
                // (Required) Credit card number.
                cc.CreditCardNumber = creditCardNumber.Value;
                // 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.
                cc.CVV2 = cvv.Value;
                // (Required) Credit card expiration month.
                cc.ExpMonth = Convert.ToInt32(expMonth.SelectedValue);
                // (Required) Credit card expiration year.
                cc.ExpYear = Convert.ToInt32(expYear.SelectedValue);
                profileDetails.CreditCard = cc;
            }

            // (Optional) The trial period for this schedule.
            if (trialBillingAmount.Value != string.Empty && trialBillingFrequency.Value != string.Empty &&
                trialBillingCycles.Value != string.Empty)
            {
                BillingPeriodDetailsType_Update trialPeriod = new BillingPeriodDetailsType_Update();
                //Unit for billing during this subscription period;
                //required if you specify an optional trial period.
                //It is one of the following values: [Day, Week, SemiMonth, Month, Year]
                //For SemiMonth, billing is done on the 1st and 15th of each month.
                //Note:
                //The combination of BillingPeriod and BillingFrequency cannot exceed one year.
                trialPeriod.BillingPeriod = (BillingPeriodType)
                                            Enum.Parse(typeof(BillingPeriodType), trialBillingPeriod.SelectedValue);
                // Number of billing periods that make up one billing cycle;
                // required if you specify an optional trial period.
                // The combination of billing frequency and billing period must be
                // less than or equal to one year. For example, if the billing cycle is Month,
                // the maximum value for billing frequency is 12. Similarly,
                // if the billing cycle is Week, the maximum value for billing frequency is 52.
                // Note:
                // If the billing period is SemiMonth, the billing frequency must be 1.
                trialPeriod.BillingFrequency = Convert.ToInt32(trialBillingFrequency.Value);
                //Billing amount for each billing cycle during this payment period;
                //required if you specify an optional trial period.
                //This amount does not include shipping and tax amounts.
                //Note:
                //All amounts in the CreateRecurringPaymentsProfile request must have
                //the same currency.
                //Character length and limitations:
                //Value is a positive number which cannot exceed $10,000 USD in any currency.
                //It includes no currency symbol.
                //It must have 2 decimal places, the decimal separator must be a period (.),
                //and the optional thousands separator must be a comma (,).
                trialPeriod.Amount = new BasicAmountType(currency, trialBillingAmount.Value);

                trialPeriod.TotalBillingCycles = Convert.ToInt32(trialBillingCycles.Value);
                //(Optional) Shipping amount for each billing cycle during this payment period.
                //Note:
                //All amounts in the request must have the same currency.
                if (trialShippingAmount.Value != string.Empty)
                {
                    trialPeriod.ShippingAmount = new BasicAmountType(currency, trialShippingAmount.Value);
                }
                //(Optional) Tax amount for each billing cycle during this payment period.
                //Note:
                //All amounts in the request must have the same currency.
                //Character length and limitations:
                //Value is a positive number which cannot exceed $10,000 USD in any currency.
                //It includes no currency symbol. It must have 2 decimal places,
                //the decimal separator must be a period (.), and the optional
                //thousands separator must be a comma (,).
                if (trialTaxAmount.Value != string.Empty)
                {
                    trialPeriod.TaxAmount = new BasicAmountType(currency, trialTaxAmount.Value);
                }
                profileDetails.TrialPeriod = trialPeriod;
            }
            // (Optional) The regular payment period for this schedule.
            if (billingAmount.Value != string.Empty && billingFrequency.Value != string.Empty &&
                totalBillingCycles.Value != string.Empty)
            {
                BillingPeriodDetailsType_Update paymentPeriod = new BillingPeriodDetailsType_Update();
                //Unit for billing during this subscription period;
                //required if you specify an optional trial period.
                //It is one of the following values: [Day, Week, SemiMonth, Month, Year]
                //For SemiMonth, billing is done on the 1st and 15th of each month.
                //Note:
                //The combination of BillingPeriod and BillingFrequency cannot exceed one year.
                paymentPeriod.BillingPeriod = (BillingPeriodType)
                                              Enum.Parse(typeof(BillingPeriodType), billingPeriod.SelectedValue);
                // Number of billing periods that make up one billing cycle;
                // required if you specify an optional trial period.
                // The combination of billing frequency and billing period must be
                // less than or equal to one year. For example, if the billing cycle is Month,
                // the maximum value for billing frequency is 12. Similarly,
                // if the billing cycle is Week, the maximum value for billing frequency is 52.
                // Note:
                // If the billing period is SemiMonth, the billing frequency must be 1.
                paymentPeriod.BillingFrequency = Convert.ToInt32(billingFrequency.Value);
                //Billing amount for each billing cycle during this payment period;
                //required if you specify an optional trial period.
                //This amount does not include shipping and tax amounts.
                //Note:
                //All amounts in the CreateRecurringPaymentsProfile request must have
                //the same currency.
                //Character length and limitations:
                //Value is a positive number which cannot exceed $10,000 USD in any currency.
                //It includes no currency symbol.
                //It must have 2 decimal places, the decimal separator must be a period (.),
                //and the optional thousands separator must be a comma (,).
                paymentPeriod.Amount = new BasicAmountType(currency, billingAmount.Value);

                paymentPeriod.TotalBillingCycles = Convert.ToInt32(totalBillingCycles.Value);
                //(Optional) Shipping amount for each billing cycle during this payment period.
                //Note:
                //All amounts in the request must have the same currency.
                if (trialShippingAmount.Value != string.Empty)
                {
                    paymentPeriod.ShippingAmount = new BasicAmountType(currency, shippingAmount.Value);
                }
                //(Optional) Tax amount for each billing cycle during this payment period.
                //Note:
                //All amounts in the request must have the same currency.
                //Character length and limitations:
                //Value is a positive number which cannot exceed $10,000 USD in any currency.
                //It includes no currency symbol. It must have 2 decimal places,
                //the decimal separator must be a period (.), and the optional
                //thousands separator must be a comma (,).
                if (trialTaxAmount.Value != string.Empty)
                {
                    paymentPeriod.TaxAmount = new BasicAmountType(currency, taxAmount.Value);
                }
                profileDetails.PaymentPeriod = paymentPeriod;
            }
        }
        protected void BtnPayNow_Click(object sender, EventArgs e)
        {
            Customer c = (Customer)Session["User"] as Customer;
            CreditCardDetailsType creditCard = new CreditCardDetailsType();

            switch (rblCardType.SelectedValue)
            {
            case "visa":
                creditCard.CreditCardType = CreditCardTypeType.VISA;
                break;

            case "mastercard":
                creditCard.CreditCardType = CreditCardTypeType.MASTERCARD;
                break;
                //case "discover":
                //    creditCard.CreditCardType = CreditCardTypeType.DISCOVER;
                //    break;
                //case "amex":
                //    creditCard.CreditCardType = CreditCardTypeType.AMEX;
                //    break;
            }
            creditCard.CreditCardNumber = txtCardNumber.Text;
            creditCard.ExpMonth         = Convert.ToInt16(ddlMonthExp.SelectedValue);
            creditCard.ExpYear          = Convert.ToInt16(ddlExpYear.SelectedValue);

            AddressType adrs = new AddressType
            {
                Street1         = txtAddress.Text,
                StateOrProvince = ddlState.SelectedValue,
                PostalCode      = txtPostalCode.Text,
                CityName        = txtCity.Text
            };

            PayerInfoType cardOwner = new PayerInfoType
            {
                Payer = c.Email
            };

            switch (ddlCountry.SelectedValue)
            {
            case "CA":
                cardOwner.PayerCountry = CountryCodeType.CA;
                adrs.Country           = CountryCodeType.CA;
                break;

            case "US":
                cardOwner.PayerCountry = CountryCodeType.US;
                adrs.Country           = CountryCodeType.US;
                break;
            }
            cardOwner.Address = adrs;

            PersonNameType payer = new PersonNameType
            {
                FirstName = txtFirstNameOnCard.Text.ToUpper(),
                LastName  = txtLastNameOnCard.Text.ToUpper()
            };

            cardOwner.PayerName  = payer;
            creditCard.CardOwner = cardOwner;

            switch (Request.QueryString["item"])
            {
            case "ad":
                switch (Request.QueryString["size"])
                {
                case "L":
                    Session["AdType"] = "Business Ad Large";
                    GetPaid("ad", "Large Ad (rotating banner)", "599", creditCard);
                    break;

                case "S":
                    Session["AdType"] = "Business Ad Small";
                    GetPaid("ad", "Small Ad (rotating images)", "299", creditCard);
                    break;
                }
                break;

            case "car":
                string amount = string.Empty;
                switch (Request.QueryString["adtype"])
                {
                case "Business":
                    Session["AdType"] = "Dealership item sales ad";
                    amount            = "19.99";
                    break;

                case "Private":
                    Session["AdType"] = "Private item sales ad";
                    amount            = "0.99";
                    break;
                }
                switch (Request.QueryString["size"])
                {
                case "1":
                    GetPaid("car", "1 vehicle", amount, creditCard);
                    break;

                case "8":
                    GetPaid("car", "8 vehicles", "89.99", creditCard);
                    break;

                case "20":
                    GetPaid("car", "20 vehicles", "199.99", creditCard);
                    break;
                }
                break;
            }
        }
        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));
        }
    // # CreateRecurringPaymentsProfile API Operation
    // The CreateRecurringPaymentsProfile API operation creates a recurring payments profile.
    // You must invoke the CreateRecurringPaymentsProfile API operation for each profile you want to create.
    // The API operation creates a profile and an associated billing agreement.
    // Note:
    // There is a one-to-one correspondence between billing agreements and recurring payments profiles.
    // To associate a recurring payments profile with its billing agreement,
    // you must ensure that the description in the recurring payments profile matches the description of a billing agreement.
    // For version 54.0 and later, use SetExpressCheckout to initiate creation of a billing agreement.
    public CreateRecurringPaymentsProfileResponseType CreateRecurringPaymentsProfileAPIOperation()
    {
        // Create the CreateRecurringPaymentsProfileResponseType object
        CreateRecurringPaymentsProfileResponseType responseCreateRecurringPaymentsProfileResponseType = new CreateRecurringPaymentsProfileResponseType();

        try
        {
            // Create the CreateRecurringPaymentsProfileReq object
            CreateRecurringPaymentsProfileReq createRecurringPaymentsProfile = new CreateRecurringPaymentsProfileReq();

            // Create the CreateRecurringPaymentsProfileRequestType object
            CreateRecurringPaymentsProfileRequestType createRecurringPaymentsProfileRequest = new CreateRecurringPaymentsProfileRequestType();

            // You can include up to 10 recurring payments profiles per request. The
            // order of the profile details must match the order of the billing
            // agreement details specified in the SetExpressCheckout request which
            // takes mandatory argument:
            //
            // * `billing start date` - The date when billing for this profile begins.
            // `Note:
            // The profile may take up to 24 hours for activation.`
            RecurringPaymentsProfileDetailsType recurringPaymentsProfileDetails
                = new RecurringPaymentsProfileDetailsType("2013-12-31T13:01:19+00:00");

            // Billing amount for each billing cycle during this payment period.
            // This amount does not include shipping and tax amounts.
            // `Note:
            // All amounts in the CreateRecurringPaymentsProfile request must have
            // the same currency.`
            BasicAmountType billingAmount = new BasicAmountType(CurrencyCodeType.USD, "3.00");

            // Regular payment period for this schedule which takes mandatory
            // params:
            //
            // * `Billing Period` - Unit for billing during this subscription period. It is one of the
            // following values:
            //  * Day
            //  * Week
            //  * SemiMonth
            //  * Month
            //  * Year
            //  For SemiMonth, billing is done on the 1st and 15th of each month.
            //  `Note:
            //  The combination of BillingPeriod and BillingFrequency cannot exceed
            //  one year.`
            // * `Billing Frequency` - Number of billing periods that make up one billing cycle.
            // The combination of billing frequency and billing period must be less
            // than or equal to one year. For example, if the billing cycle is
            // Month, the maximum value for billing frequency is 12. Similarly, if
            // the billing cycle is Week, the maximum value for billing frequency is
            // 52.
            // `Note:
            // If the billing period is SemiMonth, the billing frequency must be 1.`
            // * `Billing Amount`
            BillingPeriodDetailsType paymentPeriod = new BillingPeriodDetailsType(BillingPeriodType.DAY, Convert.ToInt32("5"), billingAmount);

            // Describes the recurring payments schedule, including the regular
            // payment period, whether there is a trial period, and the number of
            // payments that can fail before a profile is suspended which takes
            // mandatory params:
            //
            // * `Description` - Description of the recurring payment.
            // `Note:
            // You must ensure that this field matches the corresponding billing
            // agreement description included in the SetExpressCheckout request.`
            // * `Payment Period`
            ScheduleDetailsType scheduleDetails = new ScheduleDetailsType("description", paymentPeriod);

            // `CreateRecurringPaymentsProfileRequestDetailsType` which takes
            // mandatory params:
            //
            // * `Recurring Payments Profile Details`
            // * `Schedule Details`
            CreateRecurringPaymentsProfileRequestDetailsType createRecurringPaymentsProfileRequestDetails
                = new CreateRecurringPaymentsProfileRequestDetailsType(recurringPaymentsProfileDetails, scheduleDetails);

            // Either EC token or a credit card number is required.If you include
            // both token and credit card number, the token is used and credit card number is
            // ignored
            // In case of setting EC token,
            // `createRecurringPaymentsProfileRequestDetails.Token = "EC-5KH01765D1724703R";`
            // A timestamped token, the value of which was returned in the response
            // to the first call to SetExpressCheckout. Call
            // CreateRecurringPaymentsProfile once for each billing
            // agreement included in SetExpressCheckout request and use the same
            // token for each call. Each CreateRecurringPaymentsProfile request
            // creates a single recurring payments profile.
            // `Note:
            // Tokens expire after approximately 3 hours.`

            // Credit card information for recurring payments using direct payments.
            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 = "4442662639546634";

            // Credit Card Expiration Month
            creditCard.ExpMonth = Convert.ToInt32("12");

            // Credit Card Expiration Year
            creditCard.ExpYear = Convert.ToInt32("2016");
            createRecurringPaymentsProfileRequestDetails.CreditCard = creditCard;

            createRecurringPaymentsProfileRequest.CreateRecurringPaymentsProfileRequestDetails
                = createRecurringPaymentsProfileRequestDetails;

            createRecurringPaymentsProfile.CreateRecurringPaymentsProfileRequest = createRecurringPaymentsProfileRequest;

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


            // # API call
            // Invoke the CreateRecurringPaymentsProfile method
            responseCreateRecurringPaymentsProfileResponseType
                = service.CreateRecurringPaymentsProfile(createRecurringPaymentsProfile);

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

                // # Success values
                if (responseCreateRecurringPaymentsProfileResponseType.Ack.ToString().Trim().ToUpper().Equals("SUCCESS"))
                {
                    // A unique identifier for future reference to the details of this recurring payment
                    logger.Info("Profile ID : " + responseCreateRecurringPaymentsProfileResponseType.CreateRecurringPaymentsProfileResponseDetails.ProfileID + "\n");
                    Console.WriteLine("Profile ID : " + responseCreateRecurringPaymentsProfileResponseType.CreateRecurringPaymentsProfileResponseDetails.ProfileID + "\n");
                }
                // # Error Values
                else
                {
                    List <ErrorType> errorMessages = responseCreateRecurringPaymentsProfileResponseType.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(responseCreateRecurringPaymentsProfileResponseType);
    }
Esempio n. 18
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. 19
0
        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);
        }
        // # 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);
        }
        private void populateRequestObject(UpdateRecurringPaymentsProfileRequestType request)
        {
            CurrencyCodeType currency = (CurrencyCodeType)
                                        Enum.Parse(typeof(CurrencyCodeType), "USD");
            // Set EC-Token or Credit card requestDetails
            UpdateRecurringPaymentsProfileRequestDetailsType profileDetails = new UpdateRecurringPaymentsProfileRequestDetailsType();

            request.UpdateRecurringPaymentsProfileRequestDetails = profileDetails;


            profileDetails.ProfileID = profileId.Value;
            if (note.Value != "")
            {
                profileDetails.Note = note.Value;
            }
            // Populate Recurring Payments Profile Details
            if (subscriberName.Value != "")
            {
                profileDetails.SubscriberName = subscriberName.Value;
            }
            if (shippingName.Value != "" && shippingStreet1.Value != "" && shippingCity.Value != "" &&
                shippingState.Value != "" && shippingPostalCode.Value != "" && shippingCountry.Value != "")
            {
                AddressType shippingAddr = new AddressType();
                shippingAddr.Name            = shippingName.Value;
                shippingAddr.Street1         = shippingStreet1.Value;
                shippingAddr.CityName        = shippingCity.Value;
                shippingAddr.StateOrProvince = shippingCity.Value;
                shippingAddr.CountryName     = shippingCountry.Value;
                shippingAddr.PostalCode      = shippingPostalCode.Value;

                if (shippingStreet2.Value != "")
                {
                    shippingAddr.Street2 = shippingStreet2.Value;
                }
                if (shippingPhone.Value != "")
                {
                    shippingAddr.Phone = shippingPhone.Value;
                }
                profileDetails.SubscriberShippingAddress = shippingAddr;
            }
            if (additionalBillingCycles.Value != "")
            {
                profileDetails.AdditionalBillingCycles = Int32.Parse(additionalBillingCycles.Value);
            }
            if (amount.Value != "")
            {
                profileDetails.Amount = new BasicAmountType(currency, amount.Value);
            }
            if (outstandingBalance.Value != "")
            {
                profileDetails.OutstandingBalance =
                    new BasicAmountType(currency, outstandingBalance.Value);
            }
            if (maxFailedPayments.Value != "")
            {
                profileDetails.MaxFailedPayments = Int32.Parse(maxFailedPayments.Value);
            }
            if (autoBillOutstandingAmount.SelectedIndex != 0)
            {
                profileDetails.AutoBillOutstandingAmount = (AutoBillType)
                                                           Enum.Parse(typeof(AutoBillType), autoBillOutstandingAmount.SelectedValue);
            }
            if (billingStartDate.Text != "")
            {
                profileDetails.BillingStartDate = billingStartDate.Text;
            }
            if (creditCardNumber.Value != "" && cvv.Value != "")
            {
                CreditCardDetailsType cc = new CreditCardDetailsType();
                cc.CreditCardNumber       = creditCardNumber.Value;
                cc.CVV2                   = cvv.Value;
                cc.ExpMonth               = Int32.Parse(expMonth.SelectedValue);
                cc.ExpYear                = Int32.Parse(expYear.SelectedValue);
                profileDetails.CreditCard = cc;
            }

            // Populate trial payment details
            if (trialBillingAmount.Value != "" && trialBillingFrequency.Value != "" &&
                trialBillingCycles.Value != "")
            {
                BillingPeriodDetailsType_Update trialPeriod = new BillingPeriodDetailsType_Update();
                trialPeriod.BillingPeriod = (BillingPeriodType)
                                            Enum.Parse(typeof(BillingPeriodType), trialBillingPeriod.SelectedValue);
                trialPeriod.BillingFrequency = Int32.Parse(trialBillingFrequency.Value);
                trialPeriod.Amount           = new BasicAmountType(currency, trialBillingAmount.Value);

                trialPeriod.TotalBillingCycles = Int32.Parse(trialBillingCycles.Value);
                if (trialShippingAmount.Value != "")
                {
                    trialPeriod.ShippingAmount = new BasicAmountType(currency, trialShippingAmount.Value);
                }
                if (trialTaxAmount.Value != "")
                {
                    trialPeriod.TaxAmount = new BasicAmountType(currency, trialTaxAmount.Value);
                }
                profileDetails.TrialPeriod = trialPeriod;
            }
            // Populate regular payment details
            if (billingAmount.Value != "" && billingFrequency.Value != "" &&
                totalBillingCycles.Value != "")
            {
                BillingPeriodDetailsType_Update paymentPeriod = new BillingPeriodDetailsType_Update();
                paymentPeriod.BillingPeriod = (BillingPeriodType)
                                              Enum.Parse(typeof(BillingPeriodType), billingPeriod.SelectedValue);
                paymentPeriod.BillingFrequency = Int32.Parse(billingFrequency.Value);
                paymentPeriod.Amount           = new BasicAmountType(currency, billingAmount.Value);

                paymentPeriod.TotalBillingCycles = Int32.Parse(totalBillingCycles.Value);
                if (trialShippingAmount.Value != "")
                {
                    paymentPeriod.ShippingAmount = new BasicAmountType(currency, shippingAmount.Value);
                }
                if (trialTaxAmount.Value != "")
                {
                    paymentPeriod.TaxAmount = new BasicAmountType(currency, taxAmount.Value);
                }
                profileDetails.PaymentPeriod = paymentPeriod;
            }
        }
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 override string RecurringBillingCreateSubscription(String SubscriptionDescription, Customer ThisCustomer, Address UseBillingAddress, Address UseShippingAddress, Decimal RecurringAmount, DateTime StartDate, int RecurringInterval, DateIntervalTypeEnum RecurringIntervalType, int OriginalRecurringOrderNumber, string XID, IDictionary <string, string> TransactionContext, out String RecurringSubscriptionID, out String RecurringSubscriptionCommand, out String RecurringSubscriptionResult)
        {
            string result = string.Empty;

            try
            {
                //Re-Use the Internal Gateway Recurring Billing logic for calculating how much of the order is recurring
                ShoppingCart recurringCart = new ShoppingCart(ThisCustomer.SkinID, ThisCustomer, CartTypeEnum.RecurringCart, OriginalRecurringOrderNumber, false);

                CreditCardDetailsType creditCard = new CreditCardDetailsType();

                if (UseBillingAddress.CardNumber != null && UseBillingAddress.CardNumber.Length > 0)
                {
                    creditCard.CreditCardNumber  = UseBillingAddress.CardNumber;
                    creditCard.ExpMonth          = Localization.ParseUSInt(UseBillingAddress.CardExpirationMonth);
                    creditCard.ExpYear           = Localization.ParseUSInt(UseBillingAddress.CardExpirationYear);
                    creditCard.ExpMonthSpecified = true;
                    creditCard.ExpYearSpecified  = true;
                    creditCard.CVV2 = XID;

                    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;
                }
                else
                {
                    creditCard.CreditCardTypeSpecified = false;
                }

                BasicAmountType recurringAmount = new BasicAmountType();
                recurringAmount.currencyID = (CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), AppLogic.AppConfig("Localization.StoreCurrency"), true);
                recurringAmount.Value      = RecurringAmount.ToString();

                DateIntervalTypeEnum recurringIntervalType = recurringCart.CartItems[0].RecurringIntervalType;                 //We currently only support 1 interval per recurring order, so grabbing the first as a default should be safe
                int recurringInterval = recurringCart.CartItems[0].RecurringInterval;

                BillingPeriodDetailsType billingPeriodDetails = PayPalController.GetECRecurringPeriodDetails(recurringIntervalType, recurringInterval);
                billingPeriodDetails.Amount = recurringAmount;
                billingPeriodDetails.TotalBillingCyclesSpecified = false;

                ScheduleDetailsType scheduleDetails = new ScheduleDetailsType();
                scheduleDetails.Description                        = string.Format("Recurring order created on {0} from {1}", System.DateTime.Now.ToShortDateString(), AppLogic.AppConfig("StoreName"));
                scheduleDetails.MaxFailedPayments                  = 0;
                scheduleDetails.MaxFailedPaymentsSpecified         = true;
                scheduleDetails.AutoBillOutstandingAmount          = AutoBillType.NoAutoBill;
                scheduleDetails.AutoBillOutstandingAmountSpecified = true;
                scheduleDetails.PaymentPeriod                      = billingPeriodDetails;

                RecurringPaymentsProfileDetailsType profileDetails = new RecurringPaymentsProfileDetailsType();
                profileDetails.SubscriberName   = ThisCustomer.FirstName + " " + ThisCustomer.LastName;
                profileDetails.BillingStartDate = StartDate;

                CreateRecurringPaymentsProfileRequestDetailsType profileRequestDetails = new CreateRecurringPaymentsProfileRequestDetailsType();
                profileRequestDetails.ScheduleDetails = scheduleDetails;
                profileRequestDetails.RecurringPaymentsProfileDetails = profileDetails;
                profileRequestDetails.CreditCard = creditCard;

                if (!(UseBillingAddress.CardNumber != null && UseBillingAddress.CardNumber.Length > 0))
                {
                    profileRequestDetails.Token = XID;
                }

                if (recurringCart.IsAllDownloadComponents())
                {
                    PaymentDetailsItemType paymentDetailsItem = new PaymentDetailsItemType();
                    paymentDetailsItem.ItemCategory          = ItemCategoryType.Digital;
                    paymentDetailsItem.ItemCategorySpecified = true;

                    List <PaymentDetailsItemType> paymentDetailsList = new List <PaymentDetailsItemType>();
                    paymentDetailsList.Add(paymentDetailsItem);

                    profileRequestDetails.PaymentDetailsItem = paymentDetailsList.ToArray();
                }

                CreateRecurringPaymentsProfileRequestType profileRequest = new CreateRecurringPaymentsProfileRequestType();
                profileRequest.Version = API_VER;
                profileRequest.CreateRecurringPaymentsProfileRequestDetails = profileRequestDetails;

                CreateRecurringPaymentsProfileReq request = new CreateRecurringPaymentsProfileReq();
                request.CreateRecurringPaymentsProfileRequest = profileRequest;

                CreateRecurringPaymentsProfileResponseType profileResponse = new CreateRecurringPaymentsProfileResponseType();
                profileResponse = IPayPal.CreateRecurringPaymentsProfile(request);

                if (profileResponse != null && profileResponse.Ack.ToString().StartsWith("success", StringComparison.InvariantCultureIgnoreCase))
                {
                    result = AppLogic.ro_OK;
                }
                else
                {
                    if (profileResponse.Errors != null)
                    {
                        bool first = true;
                        for (int ix = 0; ix < profileResponse.Errors.Length; ix++)
                        {
                            if (!first)
                            {
                                result += ", ";
                            }
                            result += profileResponse.Errors[ix].LongMessage;
                            first   = false;
                        }
                    }
                }

                RecurringSubscriptionID      = (profileResponse.CreateRecurringPaymentsProfileResponseDetails.ProfileID == null ? "No ProfileID provided" : profileResponse.CreateRecurringPaymentsProfileResponseDetails.ProfileID);
                RecurringSubscriptionCommand = string.Empty;
                RecurringSubscriptionResult  = (profileResponse.CreateRecurringPaymentsProfileResponseDetails.DCCProcessorResponse == null ? "No response provided" : profileResponse.CreateRecurringPaymentsProfileResponseDetails.DCCProcessorResponse);

                //Log the transaction
                OrderTransactionCollection ecRecurringOrderTransaction = new OrderTransactionCollection(OriginalRecurringOrderNumber);
                ecRecurringOrderTransaction.AddTransaction("PayPal Express Checkout Recurring Profile Creation",
                                                           request.ToString(),
                                                           result,
                                                           string.Empty,
                                                           (profileResponse.CreateRecurringPaymentsProfileResponseDetails.ProfileID == null ? "No ProfileID provided" : profileResponse.CreateRecurringPaymentsProfileResponseDetails.ProfileID),
                                                           AppLogic.ro_PMPayPalExpress,
                                                           null,
                                                           RecurringAmount);
            }
            catch
            {
                result = "Recurring Profile Creation Failed.";
                RecurringSubscriptionID      = string.Empty;
                RecurringSubscriptionCommand = string.Empty;
                RecurringSubscriptionResult  = result;
            }
            return(result);
        }
        private void populateRequest(CreateRecurringPaymentsProfileRequestType request)
        {
            CurrencyCodeType currency = (CurrencyCodeType)
                                        Enum.Parse(typeof(CurrencyCodeType), "USD");

            // Set EC-Token or Credit card requestDetails
            CreateRecurringPaymentsProfileRequestDetailsType profileDetails = new CreateRecurringPaymentsProfileRequestDetailsType();

            request.CreateRecurringPaymentsProfileRequestDetails = profileDetails;
            // A timestamped token, the value of which was returned in the response to the first call to SetExpressCheckout. You can also use the token returned in the SetCustomerBillingAgreement response. Either this token or a credit card number is required. If you include both token and credit card number, the token is used and credit card number is ignored Call CreateRecurringPaymentsProfile once for each billing agreement included in SetExpressCheckout request and use the same token for each call. Each CreateRecurringPaymentsProfile request creates a single recurring payments profile.
            // Note: Tokens expire after approximately 3 hours.
            if (token.Value != string.Empty)
            {
                profileDetails.Token = token.Value;
            }
            // Credit card information for recurring payments using direct payments. Either a token or a credit card number is required. If you include both token and credit card number, the token is used and credit card number is ignored.
            else if (creditCardNumber.Value != string.Empty && cvv.Value != string.Empty)
            {
                CreditCardDetailsType cc = new CreditCardDetailsType();
                // (Required) Credit card number.
                cc.CreditCardNumber = creditCardNumber.Value;
                // 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.
                cc.CVV2 = cvv.Value;
                // (Required) Credit card expiration month.
                cc.ExpMonth = Convert.ToInt32(expMonth.SelectedValue);
                // (Required) Credit card expiration year.
                cc.ExpYear = Convert.ToInt32(expYear.SelectedValue);
                profileDetails.CreditCard = cc;
            }


            // Populate Recurring Payments Profile Details
            RecurringPaymentsProfileDetailsType rpProfileDetails =
                new RecurringPaymentsProfileDetailsType(billingStartDate.Text);

            profileDetails.RecurringPaymentsProfileDetails = rpProfileDetails;
            // (Optional) Full name of the person receiving the product or service paid for by the recurring payment. If not present, the name in the buyer's PayPal account is used.
            if (subscriberName.Value != string.Empty)
            {
                rpProfileDetails.SubscriberName = subscriberName.Value;
            }

            // (Optional) The subscriber's shipping address associated with this profile, if applicable. If not specified, the ship-to address from buyer's PayPal account is used.
            if (shippingName.Value != string.Empty && shippingStreet1.Value != string.Empty && shippingCity.Value != string.Empty &&
                shippingState.Value != string.Empty && shippingPostalCode.Value != string.Empty && shippingCountry.Value != string.Empty)
            {
                AddressType shippingAddr = new AddressType();
                // Person's name associated with this shipping address. It is required if using a shipping address.
                shippingAddr.Name = shippingName.Value;
                // First street address. It is required if using a shipping address.
                shippingAddr.Street1 = shippingStreet1.Value;
                // Name of city. It is required if using a shipping address.
                shippingAddr.CityName = shippingCity.Value;
                // State or province. It is required if using a shipping address.
                shippingAddr.StateOrProvince = shippingState.Value;
                // Country code. It is required if using a shipping address.
                shippingAddr.CountryName = shippingCountry.Value;
                // U.S. ZIP code or other country-specific postal code. It is required if using a U.S. shipping address; may be required for other countries.
                shippingAddr.PostalCode = shippingPostalCode.Value;

                // (Optional) Second street address.
                if (shippingStreet2.Value != string.Empty)
                {
                    shippingAddr.Street2 = shippingStreet2.Value;
                }
                // (Optional) Phone number.
                if (shippingPhone.Value != string.Empty)
                {
                    shippingAddr.Phone = shippingPhone.Value;
                }
                rpProfileDetails.SubscriberShippingAddress = shippingAddr;
            }


            // (Required) Describes the recurring payments schedule, including the regular payment period, whether there is a trial period, and the number of payments that can fail before a profile is suspended.
            ScheduleDetailsType scheduleDetails = new ScheduleDetailsType();

            // (Required) Description of the recurring payment.
            // Note: You must ensure that this field matches the corresponding billing agreement description included in the SetExpressCheckout request.
            if (profileDescription.Value != string.Empty)
            {
                scheduleDetails.Description = profileDescription.Value;
            }
            // (Optional) Number of scheduled payments that can fail before the profile is automatically suspended. An IPN message is sent to the merchant when the specified number of failed payments is reached.
            if (maxFailedPayments.Value != string.Empty)
            {
                scheduleDetails.MaxFailedPayments = Convert.ToInt32(maxFailedPayments.Value);
            }
            // (Optional) Indicates whether you would like PayPal to automatically bill the outstanding balance amount in the next billing cycle. The outstanding balance is the total amount of any previously failed scheduled payments that have yet to be successfully paid. It is one of the following values:
            // * NoAutoBill – PayPal does not automatically bill the outstanding balance.
            // * AddToNextBilling – PayPal automatically bills the outstanding balance.
            if (autoBillOutstandingAmount.SelectedIndex != 0)
            {
                scheduleDetails.AutoBillOutstandingAmount = (AutoBillType)
                                                            Enum.Parse(typeof(AutoBillType), autoBillOutstandingAmount.SelectedValue);
            }
            // (Optional) Information about activating a profile, such as whether there is an initial non-recurring payment amount immediately due upon profile creation and how to override a pending profile PayPal suspends when the initial payment amount fails.
            if (initialAmount.Value != string.Empty)
            {
                // (Optional) Initial non-recurring payment amount due immediately upon profile creation. Use an initial amount for enrolment or set-up fees.
                // Note: All amounts included in the request must have the same currency.
                ActivationDetailsType activationDetails =
                    new ActivationDetailsType(new BasicAmountType(currency, initialAmount.Value));
                // (Optional) Action you can specify when a payment fails. It is one of the following values:
                // * ContinueOnFailure – By default, PayPal suspends the pending profile in the event that the initial payment amount fails. You can override this default behavior by setting this field to ContinueOnFailure. Then, if the initial payment amount fails, PayPal adds the failed payment amount to the outstanding balance for this recurring payment profile.
                //   When you specify ContinueOnFailure, a success code is returned to you in the CreateRecurringPaymentsProfile response and the recurring payments profile is activated for scheduled billing immediately. You should check your IPN messages or PayPal account for updates of the payment status.
                // * CancelOnFailure – If this field is not set or you set it to CancelOnFailure, PayPal creates the recurring payment profile, but places it into a pending status until the initial payment completes. If the initial payment clears, PayPal notifies you by IPN that the pending profile has been activated. If the payment fails, PayPal notifies you by IPN that the pending profile has been canceled.
                if (failedInitialAmountAction.SelectedIndex != 0)
                {
                    activationDetails.FailedInitialAmountAction = (FailedPaymentActionType)
                                                                  Enum.Parse(typeof(FailedPaymentActionType), failedInitialAmountAction.SelectedValue);
                }
                scheduleDetails.ActivationDetails = activationDetails;
            }
            // (Optional) Trial period for this schedule.
            if (trialBillingAmount.Value != string.Empty && trialBillingFrequency.Value != string.Empty &&
                trialBillingCycles.Value != string.Empty)
            {
                // Number of billing periods that make up one billing cycle;
                // required if you specify an optional trial period.
                // The combination of billing frequency and billing period must be
                // less than or equal to one year. For example, if the billing cycle is Month,
                // the maximum value for billing frequency is 12. Similarly,
                // if the billing cycle is Week, the maximum value for billing frequency is 52.
                // Note:
                // If the billing period is SemiMonth, the billing frequency must be 1.
                int frequency = Convert.ToInt32(trialBillingFrequency.Value);

                //Billing amount for each billing cycle during this payment period;
                //required if you specify an optional trial period.
                //This amount does not include shipping and tax amounts.
                //Note:
                //All amounts in the CreateRecurringPaymentsProfile request must have
                //the same currency.
                //Character length and limitations:
                //Value is a positive number which cannot exceed $10,000 USD in any currency.
                //It includes no currency symbol.
                //It must have 2 decimal places, the decimal separator must be a period (.),
                //and the optional thousands separator must be a comma (,).
                BasicAmountType paymentAmount = new BasicAmountType(currency, trialBillingAmount.Value);

                //Unit for billing during this subscription period;
                //required if you specify an optional trial period.
                //It is one of the following values: [Day, Week, SemiMonth, Month, Year]
                //For SemiMonth, billing is done on the 1st and 15th of each month.
                //Note:
                //The combination of BillingPeriod and BillingFrequency cannot exceed one year.
                BillingPeriodType period = (BillingPeriodType)
                                           Enum.Parse(typeof(BillingPeriodType), trialBillingPeriod.SelectedValue);

                //Number of billing periods that make up one billing cycle;
                //required if you specify an optional trial period.
                //The combination of billing frequency and billing period must be
                //less than or equal to one year. For example, if the billing cycle is Month,
                //the maximum value for billing frequency is 12. Similarly,
                //if the billing cycle is Week, the maximum value for billing frequency is 52.
                //Note:
                //If the billing period is SemiMonth, the billing frequency must be 1.
                int numCycles = Convert.ToInt32(trialBillingCycles.Value);

                BillingPeriodDetailsType trialPeriod = new BillingPeriodDetailsType(period, frequency, paymentAmount);
                trialPeriod.TotalBillingCycles = numCycles;
                //(Optional) Shipping amount for each billing cycle during this payment period.
                //Note:
                //All amounts in the request must have the same currency.
                if (trialShippingAmount.Value != string.Empty)
                {
                    trialPeriod.ShippingAmount = new BasicAmountType(currency, trialShippingAmount.Value);
                }
                //(Optional) Tax amount for each billing cycle during this payment period.
                //Note:
                //All amounts in the request must have the same currency.
                //Character length and limitations:
                //Value is a positive number which cannot exceed $10,000 USD in any currency.
                //It includes no currency symbol. It must have 2 decimal places,
                //the decimal separator must be a period (.), and the optional
                //thousands separator must be a comma (,).
                if (trialTaxAmount.Value != string.Empty)
                {
                    trialPeriod.TaxAmount = new BasicAmountType(currency, trialTaxAmount.Value);
                }

                scheduleDetails.TrialPeriod = trialPeriod;
            }
            // (Required) Regular payment period for this schedule.
            if (billingAmount.Value != string.Empty && billingFrequency.Value != string.Empty &&
                totalBillingCycles.Value != string.Empty)
            {
                // Number of billing periods that make up one billing cycle;
                // required if you specify an optional trial period.
                // The combination of billing frequency and billing period must be
                // less than or equal to one year. For example, if the billing cycle is Month,
                // the maximum value for billing frequency is 12. Similarly,
                // if the billing cycle is Week, the maximum value for billing frequency is 52.
                // Note:
                // If the billing period is SemiMonth, the billing frequency must be 1.
                int frequency = Convert.ToInt32(billingFrequency.Value);
                //Billing amount for each billing cycle during this payment period;
                //required if you specify an optional trial period.
                //This amount does not include shipping and tax amounts.
                //Note:
                //All amounts in the CreateRecurringPaymentsProfile request must have
                //the same currency.
                //Character length and limitations:
                //Value is a positive number which cannot exceed $10,000 USD in any currency.
                //It includes no currency symbol.
                //It must have 2 decimal places, the decimal separator must be a period (.),
                //and the optional thousands separator must be a comma (,).
                BasicAmountType   paymentAmount = new BasicAmountType(currency, billingAmount.Value);
                BillingPeriodType period        = (BillingPeriodType)
                                                  Enum.Parse(typeof(BillingPeriodType), billingPeriod.SelectedValue);
                //Number of billing periods that make up one billing cycle;
                //required if you specify an optional trial period.
                //The combination of billing frequency and billing period must be
                //less than or equal to one year. For example, if the billing cycle is Month,
                //the maximum value for billing frequency is 12. Similarly,
                //if the billing cycle is Week, the maximum value for billing frequency is 52.
                //Note:
                //If the billing period is SemiMonth, the billing frequency must be 1.
                int numCycles = Convert.ToInt32(totalBillingCycles.Value);

                //Unit for billing during this subscription period;
                //required if you specify an optional trial period.
                //It is one of the following values: [Day, Week, SemiMonth, Month, Year]
                //For SemiMonth, billing is done on the 1st and 15th of each month.
                //Note:
                //The combination of BillingPeriod and BillingFrequency cannot exceed one year.
                BillingPeriodDetailsType paymentPeriod = new BillingPeriodDetailsType(period, frequency, paymentAmount);
                paymentPeriod.TotalBillingCycles = numCycles;
                //(Optional) Shipping amount for each billing cycle during this payment period.
                //Note:
                //All amounts in the request must have the same currency.
                if (trialShippingAmount.Value != string.Empty)
                {
                    paymentPeriod.ShippingAmount = new BasicAmountType(currency, shippingAmount.Value);
                }

                //(Optional) Tax amount for each billing cycle during this payment period.
                //Note:
                //All amounts in the request must have the same currency.
                //Character length and limitations:
                //Value is a positive number which cannot exceed $10,000 USD in any currency.
                //It includes no currency symbol. It must have 2 decimal places,
                //the decimal separator must be a period (.), and the optional
                //thousands separator must be a comma (,).
                if (trialTaxAmount.Value != string.Empty)
                {
                    paymentPeriod.TaxAmount = new BasicAmountType(currency, taxAmount.Value);
                }
                scheduleDetails.PaymentPeriod = paymentPeriod;
            }
            profileDetails.ScheduleDetails = scheduleDetails;
        }