Esempio n. 1
0
        public void RefundTransaction(string TransactionID)
        {
            RefundTransactionRequestType refundRequest = new RefundTransactionRequestType();
            BasicAmountType amount = new BasicAmountType();

            amount.currencyID           = CurrencyCodeType.USD;
            refundRequest.Memo          = "Transaction ID: " + TransactionID;
            refundRequest.RefundType    = RefundPurposeTypeCodeType.Full;
            refundRequest.TransactionID = TransactionID;
            refundRequest.Version       = "2.0";

            RefundTransactionReq request = new RefundTransactionReq();

            request.RefundTransactionRequest = refundRequest;

            try
            {
                RefundTransactionResponseType response = service.RefundTransaction(request);
                string errors = CheckForErrors(response);

                if (errors == string.Empty)
                {
                    IsSubmissionSuccess = true;
                }
                else
                {
                    IsSubmissionSuccess = false;
                    SubmissionError     = errors;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        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 AmountInfo ConvertToAmountInfo(BasicAmountType data)
        {
            if (data == null)
            {
                return(null);
            }
            double val;

            double.TryParse(data.Value, out val);
            return(new AmountInfo {
                CurrencyCode = data.currencyID.ToString(),
                Value = val
            });
        }
Esempio n. 4
0
        BasicAmountType GetBasicAmount(decimal amount)
        {
            BasicAmountType bAmount = new BasicAmountType();

            bAmount.Value = amount.ToString();

            //this is lame....
            //why you have to specify a currency for each amount
            //is beyond me... oh well...
            //says alot for duck-typing...
            //if you have a better way to do this, it's about 2 am here
            //and I'll send you $10
            bAmount.currencyID = ppCurrencyType;
            return(bAmount);
        }
Esempio n. 5
0
        string GetAmountValue(BasicAmountType amount)
        {
            //coerce it to a decimal
            decimal dAmount = decimal.Parse(amount.ToString());

            string sOut = "";

            try {
                sOut = dAmount.ToString("c");
            }
            catch {
                sOut = "--";
            }
            return(sOut);
        }
Esempio n. 6
0
        private decimal GetAmountValue(BasicAmountType amount)
        {
            decimal sOut;

            try
            {
                sOut = Convert.ToDecimal(amount.Value);
                amount.currencyID = CurrencyCodeType.USD;
            }
            catch
            {
                sOut = 0;
            }

            return(sOut);
        }
Esempio n. 7
0
        public string RefundTransaction(string TransactionID, bool DoFullRefund)
        {
            string sReturn = "";

            // Create the Refund Request
            RefundTransactionRequestType refundRequest = new RefundTransactionRequestType();
            BasicAmountType amount = new BasicAmountType();

            CurrencyCodeType currType = (CurrencyCodeType)this._currencyCode;

            amount.currencyID = currType;

            if (DoFullRefund)
            {
                refundRequest.RefundType = RefundType.Full;
            }
            else
            {
                refundRequest.RefundType = RefundType.Partial;
            }
            refundRequest.TransactionID = TransactionID;
            refundRequest.Version       = PayPalServiceUtility.PayPalAPIVersionNumber;

            RefundTransactionReq request = new RefundTransactionReq();

            request.RefundTransactionRequest = refundRequest;

            try {
                RefundTransactionResponseType response = service.RefundTransaction(request);
                string ErrorCheck = CheckErrors(response);
                if (ErrorCheck != "")
                {
                    sReturn = ErrorCheck;
                }
                else
                {
                    sReturn = "Success";
                }
            }
            catch (Exception x) {
                sReturn = "SSL Failure, the transaction did not go through. Error: " + x.Message;
            }
            return(sReturn);
        }
Esempio n. 8
0
        public string RefundTransaction(string TransactionID, decimal RefundAmount, string Memo, string currencyCode)
        {
            string           sReturn  = "";
            CurrencyCodeType currType = (CurrencyCodeType)StringToEnum(typeof(CurrencyCodeType), currencyCode);
            // Create the Refund Request
            RefundTransactionRequestType refundRequest = new RefundTransactionRequestType();
            BasicAmountType amount = new BasicAmountType();

            amount.currencyID = currType;

            amount.Value         = RefundAmount.ToString();
            refundRequest.Memo   = Memo;
            refundRequest.Amount = amount;


            refundRequest.RefundType    = RefundType.Partial;
            refundRequest.TransactionID = TransactionID;
            refundRequest.Version       = PayPalServiceUtility.PayPalAPIVersionNumber;

            RefundTransactionReq request = new RefundTransactionReq();

            request.RefundTransactionRequest = refundRequest;


            try {
                RefundTransactionResponseType response = service.RefundTransaction(request);

                string ErrorCheck = CheckErrors(response);
                if (ErrorCheck != "")
                {
                    sReturn = ("The transaction was not successful: " + ErrorCheck);
                }
                else
                {
                    sReturn = ("Success");
                }
            }
            catch (Exception x) {
                sReturn = "SSL Failure, the transaction did not go through. Error: " + x.Message;
            }
            return(sReturn);
        }
        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));
        }
Esempio n. 10
0
    //#DoReferenceTransaction API Operation
    //The DoReferenceTransaction API operation processes a payment from a buyer’s account, which is identified by a previous transaction.
    public DoReferenceTransactionResponseType DoReferenceTransactionAPIOperation()
    {
        DoReferenceTransactionResponseType responseDoReferenceTransactionResponseType = new DoReferenceTransactionResponseType();

        try
        {
            // Create the DoReferenceTransactionReq object
            DoReferenceTransactionReq doReferenceTransaction = new DoReferenceTransactionReq();

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

            // 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. 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 ID` - 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, "3.00");
            paymentDetails.OrderTotal = orderTotal;

            // 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";

            // `DoReferenceTransactionRequestDetails` takes mandatory params:
            //
            // * `Reference Id` - A transaction ID from a previous purchase, such as a
            // credit card charge using the DoDirectPayment API, or a billing
            // agreement ID.
            // * `Payment Action Code` - How you want to obtain payment. It is one of
            // the following values:
            // * Authorization
            // * Sale
            // * Order
            // * None
            // * `Payment Details`
            DoReferenceTransactionRequestDetailsType doReferenceTransactionRequestDetails
                = new DoReferenceTransactionRequestDetailsType("97U72738FY126561H", PaymentActionCodeType.SALE, paymentDetails);
            DoReferenceTransactionRequestType doReferenceTransactionRequest = new DoReferenceTransactionRequestType(doReferenceTransactionRequestDetails);
            doReferenceTransaction.DoReferenceTransactionRequest = doReferenceTransactionRequest;

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

            // # API call
            // Invoke the DoReferenceTransaction method in service wrapper object
            responseDoReferenceTransactionResponseType = service.DoReferenceTransaction(doReferenceTransaction);

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

                // # Success values
                if (responseDoReferenceTransactionResponseType.Ack.ToString().Trim().ToUpper().Equals("SUCCESS"))
                {
                    // The final amount charged, including any shipping and taxes from your Merchant Profile
                    logger.Info("Amount : " + responseDoReferenceTransactionResponseType.DoReferenceTransactionResponseDetails.Amount.currencyID
                                + " " + responseDoReferenceTransactionResponseType.DoReferenceTransactionResponseDetails.Amount.value + "\n");
                    Console.WriteLine("Amount : " + responseDoReferenceTransactionResponseType.DoReferenceTransactionResponseDetails.Amount.currencyID
                                      + " " + responseDoReferenceTransactionResponseType.DoReferenceTransactionResponseDetails.Amount.value + "\n");
                }
                // # Error Values
                else
                {
                    List <ErrorType> errorMessages = responseDoReferenceTransactionResponseType.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(responseDoReferenceTransactionResponseType);
    }
Esempio n. 11
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);
        }
Esempio n. 12
0
        protected void btnPPCont_Click(object sender, EventArgs e)
        {
            try
            {
                var Surcharge   = Math.Round((Convert.ToDouble(amount.Value) * 3) / 100, 2);
                var orderAmount = (Convert.ToDouble(amount.Value) + Surcharge).ToString();

                Dictionary <string, string> PPPayment = new Dictionary <string, string>();
                PPPayment.Add("AccNum", accountNum.Value);
                // PPPayment.Add("Amount", amount.Value);

                PPPayment.Add("Amount", orderAmount);

                Session["PPPaymentDetails"] = PPPayment;
                CustomSecurityHeaderType _credentials = new CustomSecurityHeaderType
                {
                    Credentials = new UserIdPasswordType()
                    {
                        Username  = System.Configuration.ConfigurationManager.AppSettings["UserName"].ToString(),
                        Password  = System.Configuration.ConfigurationManager.AppSettings["Password"].ToString(),
                        Signature = System.Configuration.ConfigurationManager.AppSettings["Signature"].ToString(),
                    }
                };


                var expressCheckoutRequestDetails = new SetExpressCheckoutRequestDetailsType();
                // expressCheckoutRequestDetails.ReturnURL = "http://payment.trumans.blendev.com/PayPalPayment.aspx";
                //expressCheckoutRequestDetails.CancelURL = "http://payment.trumans.blendev.com/PayPalCancel.aspx";
                expressCheckoutRequestDetails.CancelURL  = System.Configuration.ConfigurationManager.AppSettings["CancelURL"].ToString();
                expressCheckoutRequestDetails.ReturnURL  = System.Configuration.ConfigurationManager.AppSettings["SuccessURL"].ToString();
                expressCheckoutRequestDetails.NoShipping = "1";
                var paymentDetailsArray = new PaymentDetailsType[1];
                paymentDetailsArray[0] = new PaymentDetailsType
                {
                    PaymentAction = PaymentActionCodeType.Sale,
                    OrderTotal    = new BasicAmountType
                    {
                        currencyID = CurrencyCodeType.AUD,
                        Value      = orderAmount.ToString(),
                    }
                };

                BasicAmountType OTotal = new BasicAmountType();
                OTotal.Value      = orderAmount.ToString();
                OTotal.currencyID = CurrencyCodeType.AUD;
                expressCheckoutRequestDetails.OrderTotal = OTotal;

                var ExpressCheck = new SetExpressCheckoutRequestType
                {
                    SetExpressCheckoutRequestDetails = expressCheckoutRequestDetails,
                    Version = "98",
                };

                SetExpressCheckoutReq obj = new SetExpressCheckoutReq();
                obj.SetExpressCheckoutRequest = ExpressCheck;

                PayPalAPI.PayPalAPIAAInterfaceClient objPayPalAPI = new PayPalAPIAAInterfaceClient();

                var setExpressCheckoutResponse = objPayPalAPI.SetExpressCheckout(ref _credentials, obj);
                if (setExpressCheckoutResponse.Ack == AckCodeType.Success)
                {
                    Response.Redirect("https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=" + setExpressCheckoutResponse.Token, false);
                    Session["Token"] = setExpressCheckoutResponse.Token;
                }
                else
                {
                    StreamWriter File2 = File.AppendText(HttpContext.Current.Server.MapPath("~/Logs/file.txt"));
                    File2.WriteLine("Error : " + setExpressCheckoutResponse.Errors[0].LongMessage);
                    File2.Close();


                    string script = "<script type=\"text/javascript\">alert('Unexpected Error Occured , Please try Later!!');</script>";
                    ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", script);
                }
            }
            catch (Exception ex)
            {
                StreamWriter File2 = File.AppendText(HttpContext.Current.Server.MapPath("~/Logs/file.txt"));
                File2.WriteLine("Error : " + ex.Message);
                File2.Close();


                string script = "<script type=\"text/javascript\">alert('Unexpected Error Occured , Please try Later!!');</script>";
                ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", script);
            }
        }
Esempio n. 13
0
        public static string StartEC(ShoppingCart cart, bool boolBypassOrderReview, IDictionary <string, string> checkoutOptions)
        {
            var payPalRefund   = new PayPalAPISoapBinding();
            var payPalBinding  = new PayPalAPIAASoapBinding();
            var redirectUrl    = new StringBuilder();
            var ecOrderTotal   = new BasicAmountType();
            var request        = new SetExpressCheckoutReq();
            var requestType    = new SetExpressCheckoutRequestType();
            var requestDetails = new SetExpressCheckoutRequestDetailsType();
            var response       = new SetExpressCheckoutResponseType();
            var result         = string.Empty;
            var urlHelper      = DependencyResolver.Current.GetService <UrlHelper>();

            //Express checkout
            GetPaypalRequirements(out payPalRefund, out payPalBinding);

            ecOrderTotal.Value = Localization.CurrencyStringForGatewayWithoutExchangeRate(cart.Total(true));

            if (cart.HasRecurringComponents() && AppLogic.AppConfigBool("Recurring.UseGatewayInternalBilling"))
            {
                //Have to send extra details on the SetExpressCheckoutReq or the token will be invalid for creating a recurring profile later
                var recurringAgreement     = new BillingAgreementDetailsType();
                var recurringAgreementList = new List <BillingAgreementDetailsType>();

                recurringAgreement.BillingType = BillingCodeType.RecurringPayments;
                recurringAgreement.BillingAgreementDescription = "Recurring order created on " + System.DateTime.Now.ToShortDateString() + " from " + AppLogic.AppConfig("StoreName");
                recurringAgreementList.Add(recurringAgreement);
                requestDetails.BillingAgreementDetails = recurringAgreementList.ToArray();
            }

            request.SetExpressCheckoutRequest            = requestType;
            requestType.SetExpressCheckoutRequestDetails = requestDetails;

            ecOrderTotal.currencyID   = (CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), AppLogic.AppConfig("Localization.StoreCurrency"), true);
            requestDetails.OrderTotal = ecOrderTotal;

            if (AppLogic.AppConfigBool("PayPal.RequireConfirmedAddress"))
            {
                requestDetails.ReqConfirmShipping = "1";
            }
            else
            {
                requestDetails.ReqConfirmShipping = "0";
            }

            requestDetails.ReturnURL = string.Format("{0}{1}",
                                                     AppLogic.GetStoreHTTPLocation(
                                                         useSsl: true,
                                                         includeScriptLocation: true,
                                                         noVirtualNoSlash: true),
                                                     urlHelper.Action(
                                                         actionName: ActionNames.PayPalExpressReturn,
                                                         controllerName: ControllerNames.PayPalExpress));
            if (boolBypassOrderReview)
            {
                requestDetails.ReturnURL = string.Format("{0}?BypassOrderReview=true", requestDetails.ReturnURL);
            }

            requestDetails.CancelURL = string.Format("{0}{1}",
                                                     AppLogic.GetStoreHTTPLocation(
                                                         useSsl: true,
                                                         includeScriptLocation: true,
                                                         noVirtualNoSlash: true),
                                                     urlHelper.Action(
                                                         actionName: ActionNames.Index,
                                                         controllerName: ControllerNames.Checkout));
            requestDetails.LocaleCode    = AppLogic.AppConfig("PayPal.DefaultLocaleCode");
            requestDetails.PaymentAction = PaymentActionCodeType.Authorization;

            if (AppLogic.TransactionModeIsAuthCapture() || AppLogic.AppConfigBool("PayPal.ForceCapture") || PayPalController.GetAppropriateExpressType() == ExpressAPIType.PayPalAcceleratedBording)
            {
                requestDetails.PaymentAction = PaymentActionCodeType.Sale;
            }

            requestDetails.SolutionType           = SolutionTypeType.Sole;
            requestDetails.PaymentActionSpecified = true;
            requestType.Version = API_VER;

            if (!string.IsNullOrWhiteSpace(AppLogic.AppConfig("PayPal.Express.PageStyle")))
            {
                requestDetails.PageStyle = AppLogic.AppConfig("PayPal.Express.PageStyle").Trim();
            }

            if (!string.IsNullOrWhiteSpace(AppLogic.AppConfig("PayPal.Express.HeaderImage")))
            {
                requestDetails.cppheaderimage = AppLogic.AppConfig("PayPal.Express.HeaderImage").Trim();
            }

            if (!string.IsNullOrWhiteSpace(AppLogic.AppConfig("PayPal.Express.HeaderBackColor")))
            {
                requestDetails.cppheaderbackcolor = AppLogic.AppConfig("PayPal.Express.HeaderBackColor").Trim();
            }

            if (!string.IsNullOrWhiteSpace(AppLogic.AppConfig("PayPal.Express.HeaderBorderColor")))
            {
                requestDetails.cppheaderbordercolor = AppLogic.AppConfig("PayPal.Express.HeaderBorderColor").Trim();
            }

            if (!string.IsNullOrWhiteSpace(AppLogic.AppConfig("PayPal.Express.PayFlowColor")))
            {
                requestDetails.cpppayflowcolor = AppLogic.AppConfig("PayPal.Express.PayFlowColor").Trim();
            }

            if (checkoutOptions != null && checkoutOptions.ContainsKey("UserSelectedFundingSource") && checkoutOptions["UserSelectedFundingSource"] == "BML")
            {
                var fundingSourceDetails = new FundingSourceDetailsType();

                fundingSourceDetails.AllowPushFunding                   = "0";
                fundingSourceDetails.UserSelectedFundingSource          = UserSelectedFundingSourceType.BML;
                fundingSourceDetails.UserSelectedFundingSourceSpecified = true;
                requestDetails.FundingSourceDetails = fundingSourceDetails;
            }

            try
            {
                response = payPalBinding.SetExpressCheckout(request);

                if (response.Ack.ToString().StartsWith("success", StringComparison.InvariantCultureIgnoreCase))
                {
                    result = AppLogic.ro_OK;
                }
                else
                {
                    if (response.Errors != null)
                    {
                        bool first = true;
                        for (int ix = 0; ix < response.Errors.Length; ix++)
                        {
                            if (!first)
                            {
                                result += ", ";
                            }
                            result += "Error: [" + response.Errors[ix].ErrorCode + "] " + response.Errors[ix].LongMessage;
                            first   = false;
                        }
                    }
                }
            }
            catch (Exception)
            {
                result = "Failed to start PayPal Express Checkout! Please try another payment method.";
            }

            if (result == AppLogic.ro_OK)
            {
                var useIntegratedCheckout = AppLogic.AppConfigBool("PayPal.Express.UseIntegratedCheckout");

                if (AppLogic.AppConfigBool("UseLiveTransactions") == true)
                {
                    redirectUrl.Append(useIntegratedCheckout
                                                ? AppLogic.AppConfig("PayPal.Express.IntegratedCheckout.LiveURL")
                                                : AppLogic.AppConfig("PayPal.Express.LiveURL"));
                }
                else
                {
                    redirectUrl.Append(useIntegratedCheckout
                                                ? AppLogic.AppConfig("PayPal.Express.IntegratedCheckout.SandboxURL")
                                                : AppLogic.AppConfig("PayPal.Express.SandboxURL"));
                }

                redirectUrl.Append(useIntegratedCheckout
                                        ? "?token="
                                        : "?cmd=_express-checkout&token=");

                redirectUrl.Append(response.Token);

                if (boolBypassOrderReview)
                {
                    redirectUrl.Append("&useraction=commit");
                }

                // Set active payment method to PayPalExpress
                DB.ExecuteSQL(string.Format("UPDATE Address SET PaymentMethodLastUsed={0} WHERE AddressID={1}",
                                            DB.SQuote(AppLogic.ro_PMPayPalExpress),
                                            cart.ThisCustomer.PrimaryBillingAddressID));

                SetECFaultRedirect(cart.ThisCustomer, redirectUrl.ToString());
            }
            else
            {
                var error = new ErrorMessage(HttpUtility.HtmlEncode(result));
                redirectUrl.Append(urlHelper.BuildCheckoutLink(error.MessageId));
            }

            return(redirectUrl.ToString());
        }
Esempio n. 14
0
        public static String ProcessEC(ShoppingCart cart, decimal OrderTotal, int OrderNumber, String PayPalToken, String PayerID, String TransactionMode, out String AuthorizationResult, out String AuthorizationTransID)
        {
            PayPalAPISoapBinding   IPayPalRefund;
            PayPalAPIAASoapBinding IPayPal;

            PayPalController.GetPaypalRequirements(out IPayPalRefund, out IPayPal);
            String result = String.Empty;

            AuthorizationResult  = String.Empty;
            AuthorizationTransID = String.Empty;

            DoExpressCheckoutPaymentReq                 ECRequest           = new DoExpressCheckoutPaymentReq();
            DoExpressCheckoutPaymentRequestType         varECRequest        = new DoExpressCheckoutPaymentRequestType();
            DoExpressCheckoutPaymentRequestDetailsType  varECRequestDetails = new DoExpressCheckoutPaymentRequestDetailsType();
            DoExpressCheckoutPaymentResponseType        ECResponse          = new DoExpressCheckoutPaymentResponseType();
            DoExpressCheckoutPaymentResponseDetailsType varECResponse       = new DoExpressCheckoutPaymentResponseDetailsType();

            ECRequest.DoExpressCheckoutPaymentRequest           = varECRequest;
            varECRequest.DoExpressCheckoutPaymentRequestDetails = varECRequestDetails;
            ECResponse.DoExpressCheckoutPaymentResponseDetails  = varECResponse;

            varECRequestDetails.Token   = PayPalToken;
            varECRequestDetails.PayerID = PayerID;

            varECRequestDetails.PaymentAction = PaymentActionCodeType.Authorization;
            if (TransactionMode == AppLogic.ro_TXModeAuthCapture || AppLogic.AppConfigBool("PayPal.ForceCapture") || PayPalController.GetAppropriateExpressType() == ExpressAPIType.PayPalAcceleratedBording)
            {
                varECRequestDetails.PaymentAction = PaymentActionCodeType.Sale;
            }
            varECRequestDetails.PaymentActionSpecified = true;

            PaymentDetailsType ECPaymentDetails    = new PaymentDetailsType();
            BasicAmountType    ECPaymentOrderTotal = new BasicAmountType();

            ECPaymentOrderTotal.Value      = Localization.CurrencyStringForGatewayWithoutExchangeRate(OrderTotal);
            ECPaymentOrderTotal.currencyID =
                (CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), AppLogic.AppConfig("Localization.StoreCurrency"), true);
            ECPaymentDetails.InvoiceID    = OrderNumber.ToString();
            ECPaymentDetails.Custom       = cart.ThisCustomer.CustomerID.ToString();
            ECPaymentDetails.ButtonSource = PayPalController.BN + "_EC_US";
            ECPaymentDetails.NotifyURL    = AppLogic.GetStoreHTTPLocation(true) + AppLogic.AppConfig("PayPal.NotificationURL");

            varECRequest.Version = API_VER;

            ECPaymentDetails.OrderTotal = ECPaymentOrderTotal;

            List <PaymentDetailsType> ECPaymentDetailsList = new List <PaymentDetailsType>();

            ECPaymentDetailsList.Add(ECPaymentDetails);

            varECRequestDetails.PaymentDetails = ECPaymentDetailsList.ToArray();

            ECResponse = IPayPal.DoExpressCheckoutPayment(ECRequest);

            if (ECResponse.Ack.ToString().StartsWith("success", StringComparison.InvariantCultureIgnoreCase))
            {
                AuthorizationTransID = CommonLogic.IIF(varECRequestDetails.PaymentAction == PaymentActionCodeType.Sale, "CAPTURE=", "AUTH=") + ECResponse.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].TransactionID;
                result = AppLogic.ro_OK;
                AuthorizationResult = ECResponse.Ack.ToString();
                SetECFaultRedirect(cart.ThisCustomer, string.Empty);
            }
            else
            {
                if (ECResponse.Errors != null)
                {
                    if (ECResponse.Errors.Any(e => e.ErrorCode == ECFaultRedirectErrorCode.ToString()))
                    {
                        // Express Checkout failed funding recovery feature returns a 10486 which signifies that
                        //  the user should be redirected back to paypal.
                        result =
                            AuthorizationResult = AppLogic.ro_PMPayPalExpressRedirect;
                    }
                    else
                    {
                        result =
                            AuthorizationResult = string.Join(",", ECResponse.Errors.Select(e => e.LongMessage).ToArray());
                    }
                }
            }

            return(result);
        }
Esempio n. 15
0
    // # MassPay API Operation
    // The MassPay API operation makes a payment to one or more PayPal account holders.
    public MassPayResponseType MassPayAPIOperation()
    {
        // Create the MassPayResponseType object
        MassPayResponseType responseMassPayResponseType = new MassPayResponseType();

        try
        {
            // # MassPayReq
            // Details of each payment.
            // `Note:
            // A single MassPayRequest can include up to 250 MassPayItems.`
            MassPayReq massPay = new MassPayReq();
            List <MassPayRequestItemType> massPayItemList = new List <MassPayRequestItemType>();

            // `Amount` for the payment which contains
            //
            // * `Currency Code`
            // * `Amount`
            BasicAmountType amount1 = new BasicAmountType(CurrencyCodeType.USD, "4.00");

            MassPayRequestItemType massPayRequestItem1 = new MassPayRequestItemType(amount1);

            // Email Address of receiver
            massPayRequestItem1.ReceiverEmail = "*****@*****.**";

            // `Amount` for the payment which contains
            //
            // * `Currency Code`
            // * `Amount`
            BasicAmountType        amount2             = new BasicAmountType(CurrencyCodeType.USD, "3.00");
            MassPayRequestItemType massPayRequestItem2 = new MassPayRequestItemType(amount2);

            // Email Address of receiver
            massPayRequestItem2.ReceiverEmail = "*****@*****.**";

            // `Amount` for the payment which contains
            //
            // * `Currency Code`
            // * `Amount`
            BasicAmountType        amount3             = new BasicAmountType(CurrencyCodeType.USD, "7.00");
            MassPayRequestItemType massPayRequestItem3 = new MassPayRequestItemType(amount3);

            // Email Address of receiver
            massPayRequestItem3.ReceiverEmail = "*****@*****.**";
            massPayItemList.Add(massPayRequestItem2);
            massPayItemList.Add(massPayRequestItem1);
            massPayItemList.Add(massPayRequestItem3);
            MassPayRequestType massPayRequest = new MassPayRequestType(massPayItemList);
            massPay.MassPayRequest = massPayRequest;

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

            // # API call
            // Invoke the massPay method in service wrapper object
            responseMassPayResponseType = service.MassPay(massPay);

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

                // # Success values
                if (responseMassPayResponseType.Ack.ToString().Trim().ToUpper().Equals("SUCCESS"))
                {
                    logger.Info("Acknowledgement : " + responseMassPayResponseType.Ack.ToString() + "\n");
                    Console.WriteLine("Acknowledgement : " + responseMassPayResponseType.Ack.ToString() + "\n");
                }
                // # Error Values
                else
                {
                    List <ErrorType> errorMessages = responseMassPayResponseType.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(responseMassPayResponseType);
    }
Esempio n. 16
0
        protected void Search_Submit(object sender, EventArgs e)
        {
            // Create request object
            TransactionSearchRequestType request = new TransactionSearchRequestType();

            if (transactionID.Value != string.Empty)
            {
                request.TransactionID = transactionID.Value;
            }
            // (Required) The earliest transaction date at which to start the search.
            if (startDate != null && startDate.Text != null)
            {
                request.StartDate = startDate.Text;
            }
            // (Optional) The latest transaction date to be included in the search.
            if (endDate != null && endDate.Text != null)
            {
                request.EndDate = endDate.Text;
            }
            // (Optional) Search by the buyer's email address.
            if (payer.Value != string.Empty)
            {
                request.Payer = payer.Value;
            }
            // (Optional) Search by the receiver's email address. If the merchant account has only one email address, this is the primary email. It can also be a non-primary email address.
            if (receiver.Value != string.Empty)
            {
                request.Receiver = receiver.Value;
            }
            // (Optional) Search by the PayPal Account Optional receipt ID. This field is not applicable to point-of-sale transactions.
            if (receiptId.Value != string.Empty)
            {
                request.ReceiptID = receiptId.Value;
            }
            // (Optional) An alphanumeric string (generated by PayPal) that uniquely identifies a recurring profile. You can specify the Profile ID in the TransactionSearch API operation to obtain all payments associated with the identified profile.
            if (profileId.Value != string.Empty)
            {
                request.ProfileID = profileId.Value;
            }
            // (Optional) Search by auction item number of the purchased goods. This field is not applicable to point-of-sale.
            if (auctionItemNumber.Value != string.Empty)
            {
                request.AuctionItemNumber = auctionItemNumber.Value;
            }
            // (Optional) Search by invoice identification key, as set by you for the original transaction. This field searches the records for items the merchant sells.
            if (invoiceID.Value != string.Empty)
            {
                request.InvoiceID = invoiceID.Value;
            }
            // (Optional) Search by credit card number, as set by you for the original transaction. This field searches the records for items the merchant sells. The field is not applicable to point-of-sale.
            // Note: No wildcards are allowed.
            if (cardNumber.Value != string.Empty)
            {
                request.CardNumber = cardNumber.Value;
            }
            // (Optional) Search by classification of transaction. Some kinds of possible classes of transactions are not searchable with this field. You cannot search for bank transfer withdrawals, for example. It is one of the following values:
            // * All – All transaction classifications
            // * Sent – Only payments sent
            // * Received – Only payments received
            // * MassPay – Only mass payments
            // * MoneyRequest – Only money requests
            // * FundsAdded – Only funds added to balance
            // * FundsWithdrawn – Only funds withdrawn from balance
            // * Referral – Only transactions involving referrals
            // * Fee – Only transactions involving fees
            // * Subscription – Only transactions involving subscriptions
            // * Dividend – Only transactions involving dividends
            // * Billpay – Only transactions involving BillPay Transactions
            // * Refund – Only transactions involving funds
            // * CurrencyConversions – Only transactions involving currency conversions
            // * BalanceTransfer – Only transactions involving balance transfers
            // * Reversal – Only transactions involving BillPay reversals
            // * Shipping – Only transactions involving UPS shipping fees
            // * BalanceAffecting – Only transactions that affect the account balance
            // * ECheck – Only transactions involving eCheck
            if (transactionClass.SelectedIndex != 0)
            {
                request.TransactionClass = (PaymentTransactionClassCodeType)
                                           Enum.Parse(typeof(PaymentTransactionClassCodeType), transactionClass.SelectedValue);
            }
            // (Optional) Search by transaction amount.
            // Note: You must set the currencyID attribute to one of the 3-character currency codes for any of the supported PayPal currencies.
            if (amount.Value != string.Empty && currencyCode.SelectedIndex != 0)
            {
                request.CurrencyCode = (CurrencyCodeType)
                                       Enum.Parse(typeof(CurrencyCodeType), currencyCode.SelectedValue);
                BasicAmountType searchAmount = new BasicAmountType(request.CurrencyCode, amount.Value);
                request.Amount = searchAmount;
            }
            // (Optional) Search by transaction status. It is one of the following values:
            // * Pending – The payment is pending. The specific reason the payment is pending is returned by the GetTransactionDetails API PendingReason field.
            // * Processing – The payment is being processed.
            // * Success – The payment has been completed and the funds have been added successfully to your account balance.
            // * Denied – You denied the payment. This happens only if the payment was previously pending.
            // * Reversed – A payment was reversed due to a chargeback or other type of reversal. The funds have been removed from your account balance and returned to the buyer.
            if (transactionStatus.SelectedIndex != 0)
            {
                request.Status = (PaymentTransactionStatusCodeType)
                                 Enum.Parse(typeof(PaymentTransactionStatusCodeType), transactionStatus.SelectedValue);
            }


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

            wrapper.TransactionSearchRequest = 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 TransactionSearch method in service wrapper object
            TransactionSearchResponseType transactionDetails = service.TransactionSearch(wrapper);

            // Check for API return status
            processResponse(service, transactionDetails);
        }
    // # DoCapture API Operation
    // Captures an authorized payment.
    public DoCaptureResponseType DoCaptureAPIOperation()
    {
        // Create the DoCaptureResponseType object
        DoCaptureResponseType responseDoCaptureResponseType = new DoCaptureResponseType();

        try
        {
            // Create the DoCapture object
            DoCaptureReq doCapture = new DoCaptureReq();

            // `Amount` to capture which takes mandatory params:
            //
            // * `currencyCode`
            // * `amount`
            BasicAmountType amount = new BasicAmountType(CurrencyCodeType.USD, "4.00");

            // `DoCaptureRequest` which takes mandatory params:
            //
            // * `Authorization ID` - Authorization identification number of the
            // payment you want to capture. This is the transaction ID returned from
            // DoExpressCheckoutPayment, DoDirectPayment, or CheckOut. For
            // point-of-sale transactions, this is the transaction ID returned by
            // the CheckOut call when the payment action is Authorization.
            // * `amount` - Amount to capture
            // * `CompleteCode` - Indicates whether or not this is your last capture.
            // It is one of the following values:
            // * Complete – This is the last capture you intend to make.
            // * NotComplete – You intend to make additional captures.
            // `Note:
            // If Complete, any remaining amount of the original authorized
            // transaction is automatically voided and all remaining open
            // authorizations are voided.`
            DoCaptureRequestType doCaptureRequest = new DoCaptureRequestType("O-4VR15106P7416533H", amount, CompleteCodeType.NOTCOMPLETE);
            doCapture.DoCaptureRequest = doCaptureRequest;

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

            // # API call
            // Invoke the DoCapture method in service wrapper object
            responseDoCaptureResponseType = service.DoCapture(doCapture);

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

                // # Success values
                if (responseDoCaptureResponseType.Ack.ToString().Trim().ToUpper().Equals("SUCCESS"))
                {
                    // Authorization identification number
                    logger.Info("Authorization ID : " + responseDoCaptureResponseType.DoCaptureResponseDetails.AuthorizationID + "\n");
                    Console.WriteLine("Authorization ID : " + responseDoCaptureResponseType.DoCaptureResponseDetails.AuthorizationID + "\n");
                }
                // # Error Values
                else
                {
                    List <ErrorType> errorMessages = responseDoCaptureResponseType.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(responseDoCaptureResponseType);
    }
Esempio n. 18
0
        public static String MakeECRecurringProfile(ShoppingCart cart, int orderNumber, String payPalToken, String payerID, DateTime nextRecurringShipDate)
        {
            PayPalAPISoapBinding   IPayPalRefund;
            PayPalAPIAASoapBinding IPayPal;

            PayPalController.GetPaypalRequirements(out IPayPalRefund, out IPayPal);
            String result = String.Empty;

            CreateRecurringPaymentsProfileReq                ECRecurringRequest  = new CreateRecurringPaymentsProfileReq();
            CreateRecurringPaymentsProfileRequestType        varECRequest        = new CreateRecurringPaymentsProfileRequestType();
            CreateRecurringPaymentsProfileRequestDetailsType varECRequestDetails = new CreateRecurringPaymentsProfileRequestDetailsType();
            CreateRecurringPaymentsProfileResponseType       ECRecurringResponse = new CreateRecurringPaymentsProfileResponseType();

            //Re-Use the Internal Gateway Recurring Billing logic for calculating how much of the order is recurring
            ShoppingCart cartRecur       = new ShoppingCart(cart.ThisCustomer.SkinID, cart.ThisCustomer, CartTypeEnum.RecurringCart, orderNumber, false);
            Decimal      CartTotalRecur  = Decimal.Round(cartRecur.Total(true), 2, MidpointRounding.AwayFromZero);
            Decimal      RecurringAmount = CartTotalRecur - CommonLogic.IIF(cartRecur.Coupon.CouponType == CouponTypeEnum.GiftCard, CommonLogic.IIF(CartTotalRecur < cartRecur.Coupon.DiscountAmount, CartTotalRecur, cartRecur.Coupon.DiscountAmount), 0);

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

            BasicAmountType ecRecurringAmount = new BasicAmountType();

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

            BillingPeriodDetailsType varECSchedulePaymentDetails = GetECRecurringPeriodDetails(ecRecurringIntervalType, ecRecurringInterval);

            varECSchedulePaymentDetails.Amount = ecRecurringAmount;
            varECSchedulePaymentDetails.TotalBillingCyclesSpecified = false;

            ScheduleDetailsType varECSchedule = new ScheduleDetailsType();

            //Need a better description, but it must match the one sent in StartEC
            varECSchedule.Description                        = "Recurring order created on " + System.DateTime.Now.ToShortDateString() + " from " + AppLogic.AppConfig("StoreName");
            varECSchedule.MaxFailedPayments                  = 0; //Cancel the order if a recurrence fails
            varECSchedule.MaxFailedPaymentsSpecified         = true;
            varECSchedule.AutoBillOutstandingAmount          = AutoBillType.NoAutoBill;
            varECSchedule.AutoBillOutstandingAmountSpecified = true;
            varECSchedule.PaymentPeriod                      = varECSchedulePaymentDetails;

            RecurringPaymentsProfileDetailsType varECProfileDetails = new RecurringPaymentsProfileDetailsType();

            varECProfileDetails.SubscriberName   = cart.ThisCustomer.FirstName + " " + cart.ThisCustomer.LastName;
            varECProfileDetails.BillingStartDate = nextRecurringShipDate;

            varECRequestDetails.ScheduleDetails = varECSchedule;
            varECRequestDetails.Token           = payPalToken;
            varECRequestDetails.RecurringPaymentsProfileDetails = varECProfileDetails;

            if (cart.IsAllDownloadComponents())
            {
                PaymentDetailsItemType varECPaymentDetails = new PaymentDetailsItemType();
                varECPaymentDetails.ItemCategory          = ItemCategoryType.Digital;
                varECPaymentDetails.ItemCategorySpecified = true;

                List <PaymentDetailsItemType> ECPaymentDetailsList = new List <PaymentDetailsItemType>();

                ECPaymentDetailsList.Add(varECPaymentDetails);

                varECRequestDetails.PaymentDetailsItem = ECPaymentDetailsList.ToArray();
            }

            varECRequest.Version = API_VER;
            varECRequest.CreateRecurringPaymentsProfileRequestDetails = varECRequestDetails;

            ECRecurringRequest.CreateRecurringPaymentsProfileRequest = varECRequest;

            ECRecurringResponse = IPayPal.CreateRecurringPaymentsProfile(ECRecurringRequest);

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

            //Log the transaction
            OrderTransactionCollection ecRecurringOrderTransaction = new OrderTransactionCollection(orderNumber);

            ecRecurringOrderTransaction.AddTransaction("PayPal Express Checkout Recurring Profile Creation",
                                                       ECRecurringRequest.ToString(),
                                                       result,
                                                       payerID,                                                                                                                                                                                       //PNREF = payerID
                                                       (ECRecurringResponse.CreateRecurringPaymentsProfileResponseDetails.ProfileID == null ? "No ProfileID provided" : ECRecurringResponse.CreateRecurringPaymentsProfileResponseDetails.ProfileID), //Code = ProfileID
                                                       AppLogic.ro_PMPayPalExpress,
                                                       null,
                                                       RecurringAmount);

            return(result);
        }
Esempio n. 19
0
        public String ReAuthorizeOrder(int OrderNumber)
        {
            // Once the PayPal honor period (3 days) is over, PayPal no longer ensures that 100%
            // of the funds will be available. A ReAuthorize will start a new settle period.

            String result = String.Empty;

            String  PNREF      = String.Empty;
            String  TransID    = String.Empty;
            Decimal OrderTotal = 0;

            using (var con = new SqlConnection(DB.GetDBConn()))
            {
                con.Open();
                using (var rs = DB.GetRS("select * from orders   with (NOLOCK)  where OrderNumber=" + OrderNumber.ToString(), con))
                {
                    if (rs.Read())
                    {
                        PNREF      = DB.RSField(rs, "AuthorizationPNREF");
                        TransID    = Regex.Match(PNREF, "(?<=AUTH=)[0-9A-Z]+", RegexOptions.Compiled).ToString();
                        OrderTotal = DB.RSFieldDecimal(rs, "OrderTotal");
                    }
                }
            }

            if (TransID.Length == 0 || TransID == "0")
            {
                result = "Invalid or Empty Transaction ID";
            }
            else
            {
                try
                {
                    BasicAmountType totalAmount = new BasicAmountType();
                    totalAmount.Value      = Localization.CurrencyStringForGatewayWithoutExchangeRate(OrderTotal);
                    totalAmount.currencyID = (CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), AppLogic.AppConfig("Localization.StoreCurrency"), true);

                    DoReauthorizationRequestType Reauth = new DoReauthorizationRequestType();
                    Reauth.Amount          = totalAmount;
                    Reauth.AuthorizationID = TransID;
                    Reauth.Version         = API_VER;

                    DoReauthorizationReq ReauthReq = new DoReauthorizationReq();

                    ReauthReq.DoReauthorizationRequest = Reauth;

                    DoReauthorizationResponseType ReauthResponse;
                    ReauthResponse = (DoReauthorizationResponseType)IPayPal.DoReauthorization(ReauthReq);

                    //if (LogToErrorTable)
                    //{
                    //    PayPalController.Log(XmlCommon.SerializeObject(ReauthReq, ReauthReq.GetType()), "DoReauthorization Request");
                    //    PayPalController.Log(XmlCommon.SerializeObject(ReauthResponse, ReauthResponse.GetType()), "DoReauthorization Response");
                    //}

                    if (ReauthResponse != null && ReauthResponse.Ack.ToString().StartsWith("success", StringComparison.InvariantCultureIgnoreCase))
                    {
                        result = AppLogic.ro_OK;
                        DB.ExecuteSQL("update orders set AuthorizedOn=getdate(), AuthorizationPNREF=AuthorizationPNREF+'|REAU=" + ReauthResponse.AuthorizationID + "' where OrderNumber=" + OrderNumber.ToString());
                    }
                    else
                    {
                        if (ReauthResponse.Errors != null)
                        {
                            bool first = true;
                            for (int ix = 0; ix < ReauthResponse.Errors.Length; ix++)
                            {
                                if (!first)
                                {
                                    result += ", ";
                                }
                                result += "Error: [" + ReauthResponse.Errors[ix].ErrorCode + "] " + ReauthResponse.Errors[ix].LongMessage;
                                first   = false;
                            }
                        }
                    }
                }
                catch
                {
                    result = "NO RESPONSE FROM GATEWAY!";
                }
            }
            return(result);
        }
Esempio n. 20
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);
        }
    // # SetExpressCheckout API Operation
    // The SetExpressCheckout API operation initiates an Express Checkout transaction.
    public SetExpressCheckoutResponseType SetExpressCheckoutAPIOperation()
    {
        // Create the SetExpressCheckoutResponseType object
        SetExpressCheckoutResponseType responseSetExpressCheckoutResponseType = new SetExpressCheckoutResponseType();

        try
        {
            // # SetExpressCheckoutReq
            SetExpressCheckoutRequestDetailsType setExpressCheckoutRequestDetails = new SetExpressCheckoutRequestDetailsType();

            // URL to which the buyer's browser is returned after choosing to pay
            // with PayPal. For digital goods, you must add JavaScript to this page
            // to close the in-context experience.
            // `Note:
            // PayPal recommends that the value be the final review page on which
            // the buyer confirms the order and payment or billing agreement.`
            setExpressCheckoutRequestDetails.ReturnURL = "http://localhost/return";

            // URL to which the buyer is returned if the buyer does not approve the
            // use of PayPal to pay you. For digital goods, you must add JavaScript
            // to this page to close the in-context experience.
            // `Note:
            // PayPal recommends that the value be the original page on which the
            // buyer chose to pay with PayPal or establish a billing agreement.`
            setExpressCheckoutRequestDetails.CancelURL = "http://localhost/cancel";

            // # Payment Information
            // list of information about the payment
            List <PaymentDetailsType> paymentDetailsList = new List <PaymentDetailsType>();

            // information about the first payment
            PaymentDetailsType paymentDetails1 = new PaymentDetailsType();

            // 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 orderTotal1 = new BasicAmountType(CurrencyCodeType.USD, "2.00");
            paymentDetails1.OrderTotal = orderTotal1;

            // How you want to obtain payment. When implementing parallel payments,
            // this field is required and must be set to `Order`. When implementing
            // digital goods, this field is required and must be set to `Sale`. If the
            // transaction does not include a one-time purchase, this field is
            // ignored. It is one of the following values:
            //
            // * `Sale` - This is a final sale for which you are requesting payment
            // (default).
            // * `Authorization` - This payment is a basic authorization subject to
            // settlement with PayPal Authorization and Capture.
            // * `Order` - This payment is an order authorization subject to
            // settlement with PayPal Authorization and Capture.
            // `Note:
            // You cannot set this field to Sale in SetExpressCheckout request and
            // then change the value to Authorization or Order in the
            // DoExpressCheckoutPayment request. If you set the field to
            // Authorization or Order in SetExpressCheckout, you may set the field
            // to Sale.`
            paymentDetails1.PaymentAction = PaymentActionCodeType.ORDER;

            // Unique identifier for the merchant. For parallel payments, this field
            // is required and must contain the Payer Id or the email address of the
            // merchant.
            SellerDetailsType sellerDetails1 = new SellerDetailsType();
            sellerDetails1.PayPalAccountID = "*****@*****.**";
            paymentDetails1.SellerDetails  = sellerDetails1;

            // A unique identifier of the specific payment request, which is
            // required for parallel payments.
            paymentDetails1.PaymentRequestID = "PaymentRequest1";

            // `Address` to which the order is shipped, which takes mandatory params:
            //
            // * `Street Name`
            // * `City`
            // * `State`
            // * `Country`
            // * `Postal Code`
            AddressType shipToAddress1 = new AddressType();
            shipToAddress1.Street1         = "Ape Way";
            shipToAddress1.CityName        = "Austin";
            shipToAddress1.StateOrProvince = "TX";
            shipToAddress1.Country         = CountryCodeType.US;
            shipToAddress1.PostalCode      = "78750";

            paymentDetails1.ShipToAddress = shipToAddress1;

            // 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
            paymentDetails1.NotifyURL = "http://IPNhost";

            // information about the second payment
            PaymentDetailsType paymentDetails2 = new PaymentDetailsType();
            // 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 orderTotal2 = new BasicAmountType(CurrencyCodeType.USD, "4.00");
            paymentDetails2.OrderTotal = orderTotal2;

            // How you want to obtain payment. When implementing parallel payments,
            // this field is required and must be set to `Order`. When implementing
            // digital goods, this field is required and must be set to `Sale`. If the
            // transaction does not include a one-time purchase, this field is
            // ignored. It is one of the following values:
            //
            // * `Sale` - This is a final sale for which you are requesting payment
            // (default).
            // * `Authorization` - This payment is a basic authorization subject to
            // settlement with PayPal Authorization and Capture.
            // * `Order` - This payment is an order authorization subject to
            // settlement with PayPal Authorization and Capture.
            // `Note:
            // You cannot set this field to Sale in SetExpressCheckout request and
            // then change the value to Authorization or Order in the
            // DoExpressCheckoutPayment request. If you set the field to
            // Authorization or Order in SetExpressCheckout, you may set the field
            // to Sale.`
            paymentDetails2.PaymentAction = PaymentActionCodeType.ORDER;

            // Unique identifier for the merchant. For parallel payments, this field
            // is required and must contain the Payer Id or the email address of the
            // merchant.
            SellerDetailsType sellerDetails2 = new SellerDetailsType();
            sellerDetails2.PayPalAccountID = "*****@*****.**";
            paymentDetails2.SellerDetails  = sellerDetails2;

            // A unique identifier of the specific payment request, which is
            // required for parallel payments.
            paymentDetails2.PaymentRequestID = "PaymentRequest2";

            // 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
            paymentDetails2.NotifyURL = "http://IPNhost";

            // `Address` to which the order is shipped, which takes mandatory params:
            //
            // * `Street Name`
            // * `City`
            // * `State`
            // * `Country`
            // * `Postal Code`
            AddressType shipToAddress2 = new AddressType();
            shipToAddress2.Street1         = "Ape Way";
            shipToAddress2.CityName        = "Austin";
            shipToAddress2.StateOrProvince = "TX";
            shipToAddress2.Country         = CountryCodeType.US;
            shipToAddress2.PostalCode      = "78750";
            paymentDetails2.ShipToAddress  = shipToAddress2;

            paymentDetailsList.Add(paymentDetails1);
            paymentDetailsList.Add(paymentDetails2);

            setExpressCheckoutRequestDetails.PaymentDetails = paymentDetailsList;

            SetExpressCheckoutReq         setExpressCheckout        = new SetExpressCheckoutReq();
            SetExpressCheckoutRequestType setExpressCheckoutRequest = new SetExpressCheckoutRequestType(setExpressCheckoutRequestDetails);

            setExpressCheckout.SetExpressCheckoutRequest = setExpressCheckoutRequest;

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

            // # API call
            // Invoke the SetExpressCheckout method in service wrapper object
            responseSetExpressCheckoutResponseType = service.SetExpressCheckout(setExpressCheckout);

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

                // # Success values
                if (responseSetExpressCheckoutResponseType.Ack.ToString().Trim().ToUpper().Equals("SUCCESS"))
                {
                    // # Redirecting to PayPal for authorization
                    // Once you get the "Success" response, needs to authorise the
                    // transaction by making buyer to login into PayPal. For that,
                    // need to construct redirect url using EC token from response.
                    // For example,
                    // `redirectURL="https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token="+setExpressCheckoutResponse.Token;`

                    // Express Checkout Token
                    logger.Info("Express Checkout Token : " + responseSetExpressCheckoutResponseType.Token + "\n");
                    Console.WriteLine("Express Checkout Token : " + responseSetExpressCheckoutResponseType.Token + "\n");
                }
                // # Error Values
                else
                {
                    List <ErrorType> errorMessages = responseSetExpressCheckoutResponseType.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(responseSetExpressCheckoutResponseType);
    }
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);
        }
        // # DoDirectPaymentAPIOperation
        // The MassPay API operation makes a payment to one or more PayPal account holders.
        public static DoDirectPaymentResponseType DoDirectPaymentAPIOperation(CreditCardDetailsType creditCard, string amount)
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            // Create the DoDirectPaymentResponseType object
            DoDirectPaymentResponseType responseDoDirectPaymentResponseType = new DoDirectPaymentResponseType();

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

                // Information about the credit card to be charged.

                doDirectPaymentRequestDetails.CreditCard = creditCard;

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

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

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

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

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

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

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

                    // # Success values
                    if (responseDoDirectPaymentResponseType.Ack.ToString().Trim().ToUpper().Equals("SUCCESS"))
                    {
                        // Unique identifier of the transaction
                        logger.Info("Transaction ID : " + responseDoDirectPaymentResponseType.TransactionID + "\n");
                        HttpContext.Current.Session["acknowledgement"] = string.Concat("Transaction ID : ", responseDoDirectPaymentResponseType.TransactionID, "<br />");
                    }
                    // # Error Values
                    else
                    {
                        List <ErrorType> errorMessages = responseDoDirectPaymentResponseType.Errors;
                        foreach (ErrorType error in errorMessages)
                        {
                            logger.Debug("API Error Message : " + error.LongMessage);
                            HttpContext.Current.Session["acknowledgement"] = string.Concat("API Error Message : ", error.LongMessage, "<br />");
                        }
                    }
                }
            }
            // # Exception log
            catch (System.Exception ex)
            {
                // Log the exception message
                logger.Debug("Error Message : " + ex.Message);
                // Console.WriteLine("Error Message : " + ex.Message);
            }
            return(responseDoDirectPaymentResponseType);
        }
Esempio n. 24
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. 25
0
        // if RefundAmount == 0.0M, then then ENTIRE order amount will be refunded!
        public override string RefundOrder(int OriginalOrderNumber, int NewOrderNumber, decimal RefundAmount, String RefundReason, Address UseBillingAddress)
        {
            String result = String.Empty;

            DB.ExecuteSQL("update orders set RefundTXCommand=NULL, RefundTXResult=NULL where OrderNumber=" + OriginalOrderNumber.ToString());
            String  TransID    = String.Empty;
            Decimal OrderTotal = System.Decimal.Zero;

            using (var con = new SqlConnection(DB.GetDBConn()))
            {
                con.Open();
                using (var rs = DB.GetRS("select * from Orders  with (NOLOCK)  where OrderNumber=" + OriginalOrderNumber.ToString(), con))
                {
                    if (rs.Read())
                    {
                        TransID    = Regex.Match(DB.RSField(rs, "AuthorizationPNREF"), "(?<=CAPTURE=)[0-9A-Z]+", RegexOptions.Compiled).ToString();
                        OrderTotal = DB.RSFieldDecimal(rs, "OrderTotal");
                    }
                }
            }

            if (TransID.Length == 0 || TransID == "0")
            {
                result = "Invalid or Empty Transaction ID";
            }
            else
            {
                try
                {
                    RefundTransactionReq          RefundReq         = new RefundTransactionReq();
                    RefundTransactionRequestType  RefundRequestType = new RefundTransactionRequestType();
                    RefundTransactionResponseType RefundResponse;
                    BasicAmountType BasicAmount = new BasicAmountType();

                    RefundRequestType.TransactionID = TransID;
                    RefundRequestType.Version       = API_VER;

                    BasicAmount.currencyID = (CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), AppLogic.AppConfig("Localization.StoreCurrency"), true);

                    //If partial refund set value ( like 1.95). If FULL Refund leave it empty. The transactionID will take care of the amount
                    if (OrderTotal == RefundAmount || RefundAmount == 0.0M)
                    {
                        RefundRequestType.RefundType = RefundType.Full;
                    }
                    else
                    {
                        BasicAmount.Value            = Localization.CurrencyStringForGatewayWithoutExchangeRate(RefundAmount);
                        RefundRequestType.RefundType = RefundType.Partial;
                    }
                    RefundRequestType.Amount = BasicAmount;
                    RefundRequestType.RefundTypeSpecified = true;

                    if (!String.IsNullOrEmpty(RefundReason))
                    {
                        RefundRequestType.Memo = RefundReason;
                    }

                    RefundReq.RefundTransactionRequest = RefundRequestType;

                    DB.ExecuteSQL("update orders set RefundTXCommand=" + DB.SQuote(XmlCommon.SerializeObject(RefundRequestType, RefundRequestType.GetType())) + " where OrderNumber=" + OriginalOrderNumber.ToString());

                    RefundResponse = (RefundTransactionResponseType)IPayPalRefund.RefundTransaction(RefundReq);


                    //if (LogToErrorTable)
                    //{
                    //    PayPalController.Log(XmlCommon.SerializeObject(RefundReq, RefundReq.GetType()), "RefundTransaction Request");
                    //    PayPalController.Log(XmlCommon.SerializeObject(RefundResponse, RefundResponse.GetType()), "RefundTransaction Response");
                    //}

                    DB.ExecuteSQL("update orders set RefundTXCommand=" + DB.SQuote(XmlCommon.SerializeObject(RefundReq, RefundReq.GetType()))
                                  + ", RefundTXResult=" + DB.SQuote(XmlCommon.SerializeObject(RefundResponse, RefundResponse.GetType())) + " where OrderNumber=" + OriginalOrderNumber.ToString());

                    String RefundTXResult = String.Empty;
                    if (RefundResponse != null && RefundResponse.Ack.ToString().StartsWith("success", StringComparison.InvariantCultureIgnoreCase))
                    {
                        result = AppLogic.ro_OK;
                        String RefundTransID = RefundResponse.RefundTransactionID;
                        DB.ExecuteSQL("update orders set AuthorizationPNREF=AuthorizationPNREF+'|REFUND=" + RefundTransID + "' where OrderNumber=" + OriginalOrderNumber.ToString());
                    }
                    else
                    {
                        if (RefundResponse.Errors != null)
                        {
                            bool first = true;
                            for (int ix = 0; ix < RefundResponse.Errors.Length; ix++)
                            {
                                if (!first)
                                {
                                    result += ", ";
                                }
                                result += "Error: [" + RefundResponse.Errors[ix].ErrorCode + "] " + RefundResponse.Errors[ix].LongMessage;
                                first   = false;
                            }

                            result += "Note: If you are using Accelerated Boarding for PayPal Express you will not be able to modify orders until you sign up for a full account and enter your API credentials.";
                        }
                    }
                }
                catch
                {
                    result = "NO RESPONSE FROM GATEWAY!";
                }
            }
            return(result);
        }
        // # DoExpressCheckoutPayment API Operation
        // The DoExpressCheckoutPayment API operation completes an Express Checkout transaction.
        // If you set up a billing agreement in your SetExpressCheckout API call,
        // the billing agreement is created when you call the DoExpressCheckoutPayment API operation.
        public DoExpressCheckoutPaymentResponseType DoExpressCheckoutPaymentAPIOperation()
        {
            // Create the DoExpressCheckoutPaymentResponseType object
            DoExpressCheckoutPaymentResponseType responseDoExpressCheckoutPaymentResponseType =
                new DoExpressCheckoutPaymentResponseType();

            try
            {
                // Create the DoExpressCheckoutPaymentReq object
                DoExpressCheckoutPaymentReq doExpressCheckoutPayment = new DoExpressCheckoutPaymentReq();

                DoExpressCheckoutPaymentRequestDetailsType doExpressCheckoutPaymentRequestDetails =
                    new DoExpressCheckoutPaymentRequestDetailsType();

                // The timestamped token value that was returned in the
                // `SetExpressCheckout` response and passed in the
                // `GetExpressCheckoutDetails` request.
                doExpressCheckoutPaymentRequestDetails.Token = "EC-3PG29673CT337061M";

                // Unique paypal buyer account identification number as returned in
                // `GetExpressCheckoutDetails` Response
                doExpressCheckoutPaymentRequestDetails.PayerID = "WJ3Q38FZ9FDYS";

                // # Payment Information
                // list of information about the payment
                List <PaymentDetailsType> paymentDetailsList = new List <PaymentDetailsType>();

                // information about the first payment
                PaymentDetailsType paymentDetails1 = new PaymentDetailsType();

                // 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 orderTotal1 = new BasicAmountType(CurrencyCodeType.USD, "2.00");
                paymentDetails1.OrderTotal = orderTotal1;

                // How you want to obtain payment. When implementing parallel payments,
                // this field is required and must be set to `Order`. When implementing
                // digital goods, this field is required and must be set to `Sale`. If the
                // transaction does not include a one-time purchase, this field is
                // ignored. It is one of the following values:
                //
                // * `Sale` - This is a final sale for which you are requesting payment
                // (default).
                // * `Authorization` - This payment is a basic authorization subject to
                // settlement with PayPal Authorization and Capture.
                // * `Order` - This payment is an order authorization subject to
                // settlement with PayPal Authorization and Capture.
                // Note:
                // You cannot set this field to Sale in SetExpressCheckout request and
                // then change the value to Authorization or Order in the
                // DoExpressCheckoutPayment request. If you set the field to
                // Authorization or Order in SetExpressCheckout, you may set the field
                // to Sale.
                paymentDetails1.PaymentAction = PaymentActionCodeType.ORDER;

                // Unique identifier for the merchant. For parallel payments, this field
                // is required and must contain the Payer Id or the email address of the
                // merchant.
                SellerDetailsType sellerDetails1 = new SellerDetailsType();
                sellerDetails1.PayPalAccountID = "*****@*****.**";
                paymentDetails1.SellerDetails  = sellerDetails1;

                // A unique identifier of the specific payment request, which is
                // required for parallel payments.
                paymentDetails1.PaymentRequestID = "PaymentRequest1";

                // information about the second payment
                PaymentDetailsType paymentDetails2 = new PaymentDetailsType();
                // 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 orderTotal2 = new BasicAmountType(CurrencyCodeType.USD, "4.00");
                paymentDetails2.OrderTotal = orderTotal2;

                // How you want to obtain payment. When implementing parallel payments,
                // this field is required and must be set to `Order`. When implementing
                // digital goods, this field is required and must be set to `Sale`. If the
                // transaction does not include a one-time purchase, this field is
                // ignored. It is one of the following values:
                //
                // * `Sale` - This is a final sale for which you are requesting payment
                // (default).
                // * `Authorization` - This payment is a basic authorization subject to
                // settlement with PayPal Authorization and Capture.
                // * `Order` - This payment is an order authorization subject to
                // settlement with PayPal Authorization and Capture.
                // `Note:
                // You cannot set this field to Sale in SetExpressCheckout request and
                // then change the value to Authorization or Order in the
                // DoExpressCheckoutPayment request. If you set the field to
                // Authorization or Order in SetExpressCheckout, you may set the field
                // to Sale.`
                paymentDetails2.PaymentAction = PaymentActionCodeType.ORDER;

                // Unique identifier for the merchant. For parallel payments, this field
                // is required and must contain the Payer Id or the email address of the
                // merchant.
                SellerDetailsType sellerDetails2 = new SellerDetailsType();
                sellerDetails2.PayPalAccountID = "*****@*****.**";
                paymentDetails2.SellerDetails  = sellerDetails2;

                // A unique identifier of the specific payment request, which is
                // required for parallel payments.
                paymentDetails2.PaymentRequestID = "PaymentRequest2";
                paymentDetailsList.Add(paymentDetails1);
                paymentDetailsList.Add(paymentDetails2);
                doExpressCheckoutPaymentRequestDetails.PaymentDetails = paymentDetailsList;

                DoExpressCheckoutPaymentRequestType doExpressCheckoutPaymentRequest =
                    new DoExpressCheckoutPaymentRequestType(doExpressCheckoutPaymentRequestDetails);
                doExpressCheckoutPayment.DoExpressCheckoutPaymentRequest = doExpressCheckoutPaymentRequest;

                var config = new Dictionary <string, string>
                {
                    { "mode", "sandbox" },
                    { "account1.apiUsername", "konstantin_merchant_api1.scandiaconsulting.com" },
                    { "account1.apiPassword", "1398157263" },
                    { "account1.apiSignature", "AFcWxV21C7fd0v3bYYYRCpSSRl31AlRjlcug7qV.VXWV14E1KtmQPsPL" }
                };

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

                // # API call
                // Invoke the DoExpressCheckoutPayment method in service wrapper object
                responseDoExpressCheckoutPaymentResponseType = service.DoExpressCheckoutPayment(doExpressCheckoutPayment);

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

                    // # Success values
                    if (responseDoExpressCheckoutPaymentResponseType.Ack.ToString().Trim().ToUpper().Equals("SUCCESS"))
                    {
                        // Transaction identification number of the transaction that was
                        // created.
                        // This field is only returned after a successful transaction
                        // for DoExpressCheckout has occurred.
                        if (responseDoExpressCheckoutPaymentResponseType.DoExpressCheckoutPaymentResponseDetails.PaymentInfo != null)
                        {
                            IEnumerator <PaymentInfoType> paymentInfoIterator =
                                responseDoExpressCheckoutPaymentResponseType.DoExpressCheckoutPaymentResponseDetails.PaymentInfo.GetEnumerator();
                            while (paymentInfoIterator.MoveNext())
                            {
                                PaymentInfoType paymentInfo = paymentInfoIterator.Current;
                                Console.WriteLine("Transaction ID : " + paymentInfo.TransactionID + "\n");
                            }
                        }
                    }
                    // # Error Values
                    else
                    {
                        List <ErrorType> errorMessages = responseDoExpressCheckoutPaymentResponseType.Errors;
                        foreach (ErrorType error in errorMessages)
                        {
                            Console.WriteLine("API Error Message : " + error.LongMessage + "\n");
                        }
                    }
                }

                return(responseDoExpressCheckoutPaymentResponseType);
            }
            // # Exception log
            catch (System.Exception ex)
            {
                // Log the exception message
                Console.WriteLine("Error Message : " + ex.Message);
            }
            return(responseDoExpressCheckoutPaymentResponseType);
        }
Esempio n. 27
0
        public override string CaptureOrder(Order o)
        {
            String result = String.Empty;

            o.CaptureTXCommand = "";
            o.CaptureTXResult  = "";

            // check for ReauthorizationID first, if doesn't exist, use original AuthorizationID
            String TransID = Regex.Match(o.AuthorizationPNREF, "(?<=REAU=)[0-9A-Z]+", RegexOptions.Compiled).ToString();

            if (TransID.Length == 0)
            {
                TransID = Regex.Match(o.AuthorizationPNREF, "(?<=AUTH=)[0-9A-Z]+", RegexOptions.Compiled).ToString();
            }

            Decimal OrderTotal = o.OrderBalance;

            if (TransID.Length == 0 || TransID == "0")
            {
                result = "Invalid or Empty Transaction ID";
            }
            else
            {
                try
                {
                    DoCaptureReq          CaptureReq         = new DoCaptureReq();
                    DoCaptureRequestType  CaptureRequestType = new DoCaptureRequestType();
                    DoCaptureResponseType CaptureResponse;

                    BasicAmountType totalAmount = new BasicAmountType();
                    totalAmount.Value      = Localization.CurrencyStringForGatewayWithoutExchangeRate(OrderTotal);
                    totalAmount.currencyID = (CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), AppLogic.AppConfig("Localization.StoreCurrency"), true);

                    CaptureRequestType.Amount          = totalAmount;
                    CaptureRequestType.AuthorizationID = TransID;

                    CaptureRequestType.CompleteType = CompleteCodeType.Complete;
                    CaptureRequestType.Version      = API_VER;

                    CaptureReq.DoCaptureRequest = CaptureRequestType;

                    o.CaptureTXCommand = XmlCommon.SerializeObject(CaptureReq, CaptureReq.GetType());                     //"Not Available For PayPal";

                    CaptureResponse = (DoCaptureResponseType)IPayPal.DoCapture(CaptureReq);

                    //if (LogToErrorTable)
                    //{
                    //    PayPalController.Log(XmlCommon.SerializeObject(CaptureReq, CaptureReq.GetType()), "DoCapture Request");
                    //    PayPalController.Log(XmlCommon.SerializeObject(CaptureResponse, CaptureResponse.GetType()), "DoCapture Response");
                    //}

                    o.CaptureTXResult = XmlCommon.SerializeObject(CaptureResponse, CaptureResponse.GetType());

                    if (CaptureResponse != null && CaptureResponse.Ack.ToString().StartsWith("success", StringComparison.InvariantCultureIgnoreCase))
                    {
                        result = AppLogic.ro_OK;
                        String CaptureTransID = CaptureResponse.DoCaptureResponseDetails.PaymentInfo.TransactionID;
                        o.AuthorizationPNREF = o.AuthorizationPNREF + "|CAPTURE=" + CaptureTransID;
                    }
                    else
                    {
                        if (CaptureResponse.Errors != null)
                        {
                            bool first = true;
                            for (int ix = 0; ix < CaptureResponse.Errors.Length; ix++)
                            {
                                if (!first)
                                {
                                    result += ", ";
                                }
                                result += "Error: [" + CaptureResponse.Errors[ix].ErrorCode + "] " + CaptureResponse.Errors[ix].LongMessage;
                                first   = false;
                            }
                        }
                    }
                }
                catch
                {
                    result = "NO RESPONSE FROM GATEWAY!";
                }
            }
            return(result);
        }
    // # 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. 29
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);
        }
Esempio n. 30
0
        protected void Search_Submit(object sender, EventArgs e)
        {
            // Create request object
            TransactionSearchRequestType request = new TransactionSearchRequestType();

            if (transactionID.Value != "")
            {
                request.TransactionID = transactionID.Value;
            }
            if (startDate != null && startDate.Text != null)
            {
                request.StartDate = startDate.Text;
            }
            if (endDate != null && endDate.Text != null)
            {
                request.EndDate = endDate.Text;
            }
            if (payer.Value != "")
            {
                request.Payer = payer.Value;
            }
            if (receiver.Value != "")
            {
                request.Receiver = receiver.Value;
            }
            if (receiptId.Value != "")
            {
                request.ReceiptID = receiptId.Value;
            }
            if (profileId.Value != "")
            {
                request.ProfileID = profileId.Value;
            }
            if (auctionItemNumber.Value != "")
            {
                request.AuctionItemNumber = auctionItemNumber.Value;
            }
            if (invoiceID.Value != "")
            {
                request.InvoiceID = invoiceID.Value;
            }
            if (cardNumber.Value != "")
            {
                request.CardNumber = cardNumber.Value;
            }
            if (transactionClass.SelectedIndex != 0)
            {
                request.TransactionClass = (PaymentTransactionClassCodeType)
                                           Enum.Parse(typeof(PaymentTransactionClassCodeType), transactionClass.SelectedValue);
            }
            if (amount.Value != "" && currencyCode.SelectedIndex != 0)
            {
                request.CurrencyCode = (CurrencyCodeType)
                                       Enum.Parse(typeof(CurrencyCodeType), currencyCode.SelectedValue);
                BasicAmountType searchAmount = new BasicAmountType(request.CurrencyCode, amount.Value);
                request.Amount = searchAmount;
            }
            if (transactionStatus.SelectedIndex != 0)
            {
                request.Status = (PaymentTransactionStatusCodeType)
                                 Enum.Parse(typeof(PaymentTransactionStatusCodeType), transactionStatus.SelectedValue);
            }


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

            wrapper.TransactionSearchRequest = request;
            PayPalAPIInterfaceServiceService service            = new PayPalAPIInterfaceServiceService();
            TransactionSearchResponseType    transactionDetails = service.TransactionSearch(wrapper);

            // Check for API return status
            processResponse(service, transactionDetails);
        }