Example #1
0
        public ActionResult BuyProduct(int?productId)
        {
            if (!productId.HasValue)
            {
                return(RedirectToAction("PayPalCancel"));
            }
            Order order = PayPalHelper.CreateOrder(productId.Value);

            if (order == null)
            {
                return(RedirectToAction("PayPalCancel"));
            }
            string domain    = PayPalHelper.GetDomainName(Request);
            var    returnURL = domain + "/Payment/PaymentDetails";
            var    cancelURL = domain + "/Payment/PaypalCancel";
            SetExpressCheckoutReq          request     = PayPalHelper.GetSetExpressCheckoutReq(order, returnURL, cancelURL);
            CustomSecurityHeaderType       credentials = PayPalHelper.GetPayPalCredentials();
            PayPalAPIAAInterfaceClient     client      = new PayPalAPIAAInterfaceClient();
            SetExpressCheckoutResponseType response    = client.SetExpressCheckout(ref credentials, request);

            if (response.Errors != null && response.Errors.Length > 0)
            {
                throw new Exception("Exception occured when calling PayPal: " + response.Errors[0].LongMessage);
            }
            string redirectUrl = string.Format("{0}?cmd=_express-checkout&token={1}", PayPalHelper.GetPaypalRequestUrl(), response.Token);

            return(Redirect(redirectUrl));
        }
Example #2
0
 public static PayerInfoType GetExpressCheckout(string token)
 {
     System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
     using (var client = new PayPalAPIAAInterfaceClient(new BasicHttpsBinding(), new EndpointAddress(EndpointUrl)))
     {
         var credentials = new CustomSecurityHeaderType()
         {
             Credentials = new UserIdPasswordType()
             {
                 Username  = APIUserName,
                 Password  = APIPassword,
                 Signature = APISignature
             }
         };
         GetExpressCheckoutDetailsReq req = new GetExpressCheckoutDetailsReq()
         {
             GetExpressCheckoutDetailsRequest = new GetExpressCheckoutDetailsRequestType()
             {
                 Version = "121.0",
                 Token   = token
             }
         };
         var    resp   = client.GetExpressCheckoutDetails(ref credentials, req);
         string errors = CheckErrors(resp);
         if (errors == String.Empty)
         {
             return(resp.GetExpressCheckoutDetailsResponseDetails.PayerInfo);
         }
         return(new PayerInfoType()
         {
             PayerID = errors
         });
     }
 }
Example #3
0
        /// <summary>
        /// Constructs a security header from values in <see cref="ApiContext"/>.
        /// </summary>
        /// <returns>Security information of type <see cref="CustomSecurityHeaderType"/>.</returns>
        protected virtual CustomSecurityHeaderType GetSecurityHeader()
        {
            CustomSecurityHeaderType sechdr = new CustomSecurityHeaderType();

            //Check for oAuth
            if (ApiContext.ApiCredential.oAuthToken != null && ApiContext.ApiCredential.oAuthToken.Length > 0)
            {
                if (ApiContext.ApiCredential.eBayToken != null && ApiContext.ApiCredential.eBayToken.Length > 0)
                {
                    sechdr.eBayAuthToken = ApiContext.ApiCredential.eBayToken;
                }

                //else
                //{
                //    sechdr.oAuthToken = ApiContext.ApiCredential.oAuthToken;
                //}
            }
            else if (ApiContext.ApiCredential.eBayToken != null && ApiContext.ApiCredential.eBayToken.Length > 0)
            {
                sechdr.eBayAuthToken = ApiContext.ApiCredential.eBayToken;
            }


            return(sechdr);
        }
Example #4
0
        public ActionResult PaymentDetails(string token)
        {
            if (token.IsNullOrWhiteSpace())
            {
                return(RedirectToAction("PayPalCancel"));
            }
            GetExpressCheckoutDetailsReq          req         = PayPalHelper.GetGetExpressCheckoutDetailsReq(token);
            CustomSecurityHeaderType              credentials = PayPalHelper.GetPayPalCredentials();
            PayPalAPIAAInterfaceClient            client      = new PayPalAPIAAInterfaceClient();
            GetExpressCheckoutDetailsResponseType response    = client.GetExpressCheckoutDetails(ref credentials, req);

            if (response.Errors != null && response.Errors.Length > 0)
            {
                throw new Exception("Exception occured when calling PayPal: " + response.Errors[0].LongMessage);
            }
            GetExpressCheckoutDetailsResponseDetailsType respDetails = response.GetExpressCheckoutDetailsResponseDetails;
            Order order = PayPalHelper.UpdateOrderAfterAuthentication(respDetails.Custom, respDetails.PayerInfo.PayerID);
            var   model = new PaymentModel
            {
                Order     = order,
                BuyerName = respDetails.PayerInfo.PayerName.FirstName + respDetails.PayerInfo.PayerName.LastName
            };

            Session["CheckoutDetails"] = response;
            return(View("PaymentDetails", model));
        }
		/// <summary>
		/// Constructs a security header from values in <see cref="ApiCall.ApiContext"/>.
		/// </summary>
		/// <returns>Security information of type <see cref="CustomSecurityHeaderType"/>.</returns>
		protected override CustomSecurityHeaderType GetSecurityHeader()
		{
			CustomSecurityHeaderType sechdr = new CustomSecurityHeaderType();
			if (ApiContext.ApiCredential.eBayToken != null && ApiContext.ApiCredential.eBayToken.Length > 0)
			{
				sechdr.eBayAuthToken = ApiContext.ApiCredential.eBayToken;
			}
			else
			{
			        throw new SdkException("GetTokenStatus needs a valid, active auth token to be called!");
			}

			if (ApiContext.ApiCredential.ApiAccount != null)
			{
				sechdr.Credentials = new UserIdPasswordType();
				sechdr.Credentials.AppId = ApiContext.ApiCredential.ApiAccount.Application;
				sechdr.Credentials.DevId = ApiContext.ApiCredential.ApiAccount.Developer;
				sechdr.Credentials.AuthCert = ApiContext.ApiCredential.ApiAccount.Certificate;
			}
			else
			{
			        throw new SdkException("GetTokenStatus needs the full set of developer credentials to be called!");			
			}
			
			return (sechdr);
		}
Example #6
0
        public ShoppingCartPayment Pay(ShoppingCartPayment orderDetails)
        {
            if (string.IsNullOrEmpty(orderDetails.authToken))
            {
                return(orderDetails);
            }
            if (!CheckUserBuyer(orderDetails.authToken))
            {
                return(orderDetails);
            }
            if (orderDetails.amount <= 0.01)
            {
                return(orderDetails);
            }
            PayPalAPIAAInterfaceClient pp          = CreatePaypalConnection();
            CustomSecurityHeaderType   credentials = CreateHeaderCredentials(orderDetails.username,
                                                                             orderDetails.password, orderDetails.signature);
            SetExpressCheckoutReq request = CreateExpressCheckoutRequest(orderDetails.amount);

            try
            {
                System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
                var response = pp.SetExpressCheckout(ref credentials, request);
                if (response.Ack == AckCodeType.Success)
                {
                    orderDetails.successfulPayment = true;
                    return(orderDetails);
                }
            }
            catch (Exception ex) { }
            orderDetails.successfulPayment = false;
            return(orderDetails);
        }
Example #7
0
        /// <summary>
        /// Constructs a security header from values in <see cref="ApiCall.ApiContext"/>.
        /// </summary>
        /// <returns>Security information of type <see cref="CustomSecurityHeaderType"/>.</returns>
        protected override CustomSecurityHeaderType GetSecurityHeader()
        {
            CustomSecurityHeaderType sechdr = new CustomSecurityHeaderType();

            if (ApiContext.ApiCredential.eBayToken != null && ApiContext.ApiCredential.eBayToken.Length > 0)
            {
                sechdr.eBayAuthToken = ApiContext.ApiCredential.eBayToken;
            }
            else
            {
                throw new SdkException("GetTokenStatus needs a valid, active auth token to be called!");
            }

            if (ApiContext.ApiCredential.ApiAccount != null)
            {
                sechdr.Credentials          = new UserIdPasswordType();
                sechdr.Credentials.AppId    = ApiContext.ApiCredential.ApiAccount.Application;
                sechdr.Credentials.DevId    = ApiContext.ApiCredential.ApiAccount.Developer;
                sechdr.Credentials.AuthCert = ApiContext.ApiCredential.ApiAccount.Certificate;
            }
            else
            {
                throw new SdkException("GetTokenStatus needs the full set of developer credentials to be called!");
            }

            return(sechdr);
        }
 CustomSecurityHeaderType GetCustomSecurityHeader(IPaymentGatewaySettings settings)
 {
     CustomSecurityHeaderType result = new CustomSecurityHeaderType();
     result.Credentials.Username = settings.Username;
     result.Credentials.Password = settings.Password;
     result.Credentials.Signature = Properties.PayPalExpress.Default.Signature;
     result.Credentials.Subject = String.Empty;
     return result;
 }
Example #9
0
        /// <summary>
        /// Constructs a security header from values in <see cref="ApiContext"/>.
        /// </summary>
        /// <returns>Security information of type <see cref="CustomSecurityHeaderType"/>.</returns>
        protected virtual CustomSecurityHeaderType GetSecurityHeader()
        {
            CustomSecurityHeaderType sechdr = new CustomSecurityHeaderType();

            if (ApiContext.ApiCredential.eBayToken != null && ApiContext.ApiCredential.eBayToken.Length > 0)
            {
                sechdr.eBayAuthToken = ApiContext.ApiCredential.eBayToken;
            }

            return(sechdr);
        }
        protected CustomSecurityHeaderType GetApiCredentials(PayPalApiSettingsBase settings)
        {
            var customSecurityHeaderType = new CustomSecurityHeaderType();

            customSecurityHeaderType.Credentials           = new UserIdPasswordType();
            customSecurityHeaderType.Credentials.Username  = settings.ApiAccountName;
            customSecurityHeaderType.Credentials.Password  = settings.ApiAccountPassword;
            customSecurityHeaderType.Credentials.Signature = settings.Signature;
            customSecurityHeaderType.Credentials.Subject   = "";

            return(customSecurityHeaderType);
        }
        protected void btnPay_Click(object sender, EventArgs e)
        {
            if (radPaypal.Checked)
            {
                PayPalAPIAAInterfaceClient paypalAAInt = new PayPalAPIAAInterfaceClient();
                string hosting = ConfigurationManager.AppSettings["HostingPrefix"];

                CustomSecurityHeaderType type = new CustomSecurityHeaderType();
                type.Credentials = new UserIdPasswordType()
                {
                    Username = ConfigurationManager.AppSettings["PP_APIUsername"],
                    Password = ConfigurationManager.AppSettings["PP_APIPassword"],
                    Signature = ConfigurationManager.AppSettings["PP_APISignature"]
                };

                SetExpressCheckoutRequestDetailsType sdt = new SetExpressCheckoutRequestDetailsType();
                sdt.NoShipping = "1";
                PaymentDetailsType pdt = new PaymentDetailsType()
                {
                    OrderDescription = "Payment Details Sushant",
                    OrderTotal = new BasicAmountType()
                    {
                        currencyID = CurrencyCodeType.USD,
                        Value = "100.00"
                    }
                };

                sdt.PaymentDetails = new PaymentDetailsType[] { pdt };
                sdt.CancelURL = hosting + "Default.aspx";
                sdt.ReturnURL = hosting + "ExpressCheckoutSuccess.aspx";

                SetExpressCheckoutReq req = new SetExpressCheckoutReq()
                {
                    SetExpressCheckoutRequest = new SetExpressCheckoutRequestType()
                    {
                        SetExpressCheckoutRequestDetails = sdt,
                        Version = "60.0"
                    }
                };

                var resp = paypalAAInt.SetExpressCheckout(ref type, req);
                if (resp.Errors != null && resp.Errors.Length > 0)
                {
                    // errors occured
                    throw new Exception("Exception(s) occured when calling PayPal. First exception: " +
                        resp.Errors[0].LongMessage);
                }

                Response.Redirect(string.Format("{0}?cmd=_express-checkout&token={1}",
                    ConfigurationManager.AppSettings["PayPalSubmitUrl"], resp.Token));
            }
        }
        protected void btnPay_Click(object sender, EventArgs e)
        {
            if (radPaypal.Checked)
            {
                PayPalAPIAAInterfaceClient paypalAAInt = new PayPalAPIAAInterfaceClient();
                string hosting = ConfigurationManager.AppSettings["HostingPrefix"];

                CustomSecurityHeaderType type = new CustomSecurityHeaderType();
                type.Credentials = new UserIdPasswordType()
                {
                    Username  = ConfigurationManager.AppSettings["PP_APIUsername"],
                    Password  = ConfigurationManager.AppSettings["PP_APIPassword"],
                    Signature = ConfigurationManager.AppSettings["PP_APISignature"]
                };

                SetExpressCheckoutRequestDetailsType sdt = new SetExpressCheckoutRequestDetailsType();
                sdt.NoShipping = "1";
                PaymentDetailsType pdt = new PaymentDetailsType()
                {
                    OrderDescription = "Payment Details Sushant",
                    OrderTotal       = new BasicAmountType()
                    {
                        currencyID = CurrencyCodeType.USD,
                        Value      = "100.00"
                    }
                };

                sdt.PaymentDetails = new PaymentDetailsType[] { pdt };
                sdt.CancelURL      = hosting + "Default.aspx";
                sdt.ReturnURL      = hosting + "ExpressCheckoutSuccess.aspx";

                SetExpressCheckoutReq req = new SetExpressCheckoutReq()
                {
                    SetExpressCheckoutRequest = new SetExpressCheckoutRequestType()
                    {
                        SetExpressCheckoutRequestDetails = sdt,
                        Version = "60.0"
                    }
                };

                var resp = paypalAAInt.SetExpressCheckout(ref type, req);
                if (resp.Errors != null && resp.Errors.Length > 0)
                {
                    // errors occured
                    throw new Exception("Exception(s) occured when calling PayPal. First exception: " +
                                        resp.Errors[0].LongMessage);
                }

                Response.Redirect(string.Format("{0}?cmd=_express-checkout&token={1}",
                                                ConfigurationManager.AppSettings["PayPalSubmitUrl"], resp.Token));
            }
        }
 GetExpressCheckoutDetailsResponseType GetExpressCheckoutDetailsRequest(IPaymentGatewaySettings settings, string token)
 {
     GetExpressCheckoutDetailsReq req = new GetExpressCheckoutDetailsReq();
     GetExpressCheckoutDetailsResponseType result = null;
     var request = new GetExpressCheckoutDetailsRequestType();
     req.GetExpressCheckoutDetailsRequest = request;
     request.Token = token;
     request.Version = API_VERSION;
     var service = GetPayPalAAInterfaceClient(settings);
     CustomSecurityHeaderType customSecurityHeader = new CustomSecurityHeaderType();
     GetExpressCheckoutDetailsResponseType response = service.GetExpressCheckoutDetails(ref customSecurityHeader, req);
     result = response;
     return response;
 }
Example #14
0
        public static void GetPaypalRequirements(out PayPalAPISoapBinding IPayPalRefund, out PayPalAPIAASoapBinding IPayPal)
        {
            IPayPal       = new PayPalAPIAASoapBinding();
            IPayPalRefund = new PayPalAPISoapBinding();

            if (AppLogic.AppConfigBool("UseLiveTransactions"))
            {
                IPayPal.Url = AppLogic.AppConfig("PayPal.API.LiveURL");
            }
            else
            {
                IPayPal.Url = AppLogic.AppConfig("PayPal.API.TestURL");
            }
            IPayPalRefund.Url = IPayPal.Url;

            IPayPal.UserAgent       = HttpContext.Current.Request.UserAgent;
            IPayPalRefund.UserAgent = IPayPal.UserAgent;

            UserIdPasswordType PayPalUser = new UserIdPasswordType();

            if (PayPalController.GetAppropriateExpressType() == ExpressAPIType.PayPalAcceleratedBording)
            {
                PayPalUser.Subject = AppLogic.AppConfig("PayPal.API.AcceleratedBoardingEmailAddress");
            }
            else
            {
                PayPalUser.Username  = AppLogic.AppConfig("PayPal.API.Username");
                PayPalUser.Password  = AppLogic.AppConfig("PayPal.API.Password");
                PayPalUser.Signature = AppLogic.AppConfig("PayPal.API.Signature");

                //Subject should be the Sellers e-mail address (if you are using 3-part API calls) with the correct account permissions. You also have
                //set up permissions for this e-mail address for the "type" of transaction you want to allow.
                //This access changes are made in the Sandbox.
                //The name of the entity on behalf of which this profile is issuing calls
                //This is for Third-Party access
                // You have to set up Virtual Terminals and complete the Billing Agreement in the Sandbox before you can make Direct Payments
                PayPalUser.Subject = AppLogic.AppConfig("PayPal.API.MerchantEMailAddress");
            }



            CustomSecurityHeaderType CSecHeaderType = new CustomSecurityHeaderType();

            CSecHeaderType.Credentials    = PayPalUser;
            CSecHeaderType.MustUnderstand = true;

            IPayPal.RequesterCredentials       = CSecHeaderType;
            IPayPalRefund.RequesterCredentials = CSecHeaderType;
        }
Example #15
0
        static void Main(string[] args)
        {
            SetExpressCheckoutReq req = new SetExpressCheckoutReq
            {
                SetExpressCheckoutRequest = new SetExpressCheckoutRequestType
                {
                    Version = "74.0",
                    SetExpressCheckoutRequestDetails = new SetExpressCheckoutRequestDetailsType
                    {
                        OrderTotal = new BasicAmountType
                        {
                            Value      = "10.00",
                            currencyID = CurrencyCodeType.EUR
                        },
                        ReturnURL = "http://www.google.com",
                        CancelURL = "http://www.google.com"
                    }
                }
            };
            CustomSecurityHeaderType cred = new CustomSecurityHeaderType
            {
                Credentials = new UserIdPasswordType
                {
                    Username  = "******",
                    Password  = "******",
                    Signature = "AFcWxV21C7fd0v3bYYYRCpSSRl31AhzL0GoBgvn-TKnJd6oSO-B8Lqz6",
                    AppId     = "APP-80W284485P519543T"
                }
            };

            PayPalAPIAAInterfaceClient pp = new PayPalAPIAAInterfaceClient();

            pp.Endpoint.Address = new System.ServiceModel.EndpointAddress("https://api-3t.sandbox.paypal.com/nvp");
            try
            {
                System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
                var resp = pp.SetExpressCheckout(ref cred, req);
                Console.Out.WriteLine(resp.CorrelationID);
                Console.Out.WriteLine(resp.Ack.ToString());
                foreach (ErrorType msg in resp.Errors)
                {
                    Console.Out.WriteLine(msg.LongMessage);
                }
            }
            catch (Exception ex)
            {
                Console.Out.WriteLine(ex.Message);
            }
        }
Example #16
0
 public static string SetExpressCheckout(string email, double total, string returnUrl, string cancelUrl, bool allowGuestCheckout, bool showCreditCardAndAddress)
 {
     System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
     using (var client = new PayPalAPIAAInterfaceClient(new BasicHttpsBinding(), new EndpointAddress(EndpointUrl)))
     {
         var credentials = new CustomSecurityHeaderType()
         {
             Credentials = new UserIdPasswordType()
             {
                 Username  = APIUserName,
                 Password  = APIPassword,
                 Signature = APISignature
             }
         };
         SetExpressCheckoutReq req = new SetExpressCheckoutReq()
         {
             SetExpressCheckoutRequest = new SetExpressCheckoutRequestType()
             {
                 Version = "121.0",
                 SetExpressCheckoutRequestDetails = new SetExpressCheckoutRequestDetailsType()
                 {
                     BuyerEmail = email,
                     OrderTotal = new BasicAmountType()
                     {
                         currencyID = CurrencyCodeType.USD,
                         Value      = total.ToString()
                     },
                     ReturnURL             = returnUrl,
                     CancelURL             = cancelUrl,
                     SolutionType          = allowGuestCheckout ? SolutionTypeType.Sole : SolutionTypeType.Mark,
                     SolutionTypeSpecified = allowGuestCheckout,
                     LandingPage           = LandingPageType.Billing,
                     LandingPageSpecified  = showCreditCardAndAddress
                 }
             }
         };
         var    resp   = client.SetExpressCheckout(ref credentials, req);
         string errors = CheckErrors(resp);
         if (errors == String.Empty)
         {
             return(resp.Token);
         }
         else
         {
             return(errors);
         }
     }
 }
Example #17
0
        public static CustomSecurityHeaderType GetPayPalCredentials()
        {
            UserIdPasswordType credentials = new UserIdPasswordType()
            {
                Username  = ConfigurationManager.AppSettings["PayPalAPIUsername"],
                Password  = ConfigurationManager.AppSettings["PayPalAPIPassword"],
                Signature = ConfigurationManager.AppSettings["PayPalAPISignature"],
            };

            CustomSecurityHeaderType header = new CustomSecurityHeaderType()
            {
                Credentials = credentials
            };

            return(header);
        }
Example #18
0
        public ChargeResult DoPayment(string CCNumber, Int32 Amount, string FirstName, string LastName, string Address, string City, string Zip, string State, string Country, string Telephone, string DOB, string EmailAddress, string CardHolderName, string ExpiryMonth, string ExpiryYear, string CVC2, String Currency)
        {
            // CreditCardDetailsType cardDetails = MapCardDetails(CCNumber, FirstName, LastName, Address, City, Zip, State, Country, Telephone, DOB, EmailAddress, CardHolderName, ExpiryMonth, ExpiryYear, CVC2);
            DoDirectPaymentResponseType result;

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

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

                var dp = new DoDirectPaymentReq
                {
                    DoDirectPaymentRequest = pp_Request
                };

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

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

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

            chargeResult.Id = result.TransactionID;

            return(chargeResult);
        }
Example #19
0
        /// <summary>
        /// Constructs a security header from values in <see cref="ApiCall.ApiContext"/>.
        /// </summary>
        /// <returns>Security information of type <see cref="CustomSecurityHeaderType"/>.</returns>
        protected override CustomSecurityHeaderType GetSecurityHeader()
        {
            CustomSecurityHeaderType sechdr = new CustomSecurityHeaderType();

            if (ApiContext.ApiCredential.ApiAccount != null)
            {
                sechdr.Credentials          = new UserIdPasswordType();
                sechdr.Credentials.AppId    = ApiContext.ApiCredential.ApiAccount.Application;
                sechdr.Credentials.DevId    = ApiContext.ApiCredential.ApiAccount.Developer;
                sechdr.Credentials.AuthCert = ApiContext.ApiCredential.ApiAccount.Certificate;
            }
            else
            {
                throw new SdkException("GetSessionID needs Api Account to be called!");
            }

            return(sechdr);
        }
Example #20
0
    public PayPalReturn GetTransactionDetails(string transactionID)
    {
        //PayPal Return Structure
        PayPalReturn rv = new PayPalReturn();

        rv.IsSucess = false;

        //Requests
        //TransactionID = "6XT85330WL909250J"
        GetTransactionDetailsReq request = new GetTransactionDetailsReq();

        request.GetTransactionDetailsRequest = new GetTransactionDetailsRequestType();
        request.GetTransactionDetailsRequest.TransactionID = transactionID;
        request.GetTransactionDetailsRequest.Version       = "51.0";

        //Headers
        CustomSecurityHeaderType headers = new CustomSecurityHeaderType();

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

        //Client
        PayPalAPISoapBinding client = new PayPalAPISoapBinding();

        client.RequesterCredentials = headers;
        client.Timeout = 15000;
        GetTransactionDetailsResponseType response = client.GetTransactionDetails(request);

        if (response.Ack == AckCodeType.Success || response.Ack == AckCodeType.SuccessWithWarning)
        {
            rv.IsSucess      = true;
            rv.TransactionID = response.PaymentTransactionDetails.PaymentInfo.TransactionID;
            rv.ObjectValue   = response.PaymentTransactionDetails;
        }
        else
        {
            rv.ErrorMessage = response.Errors[0].LongMessage;
        }
        return(rv);
    }
        /// <summary>
        /// Constructs a security header from values in <see cref="ApiCall.ApiContext"/>.
        /// </summary>
        /// <returns>Security information of type <see cref="CustomSecurityHeaderType"/>.</returns>
        protected override CustomSecurityHeaderType GetSecurityHeader()
        {
            CustomSecurityHeaderType sechdr = new CustomSecurityHeaderType();

            if (ApiContext.ApiCredential.ApiAccount != null)
            {
                sechdr.Credentials          = new UserIdPasswordType();
                sechdr.Credentials.AppId    = ApiContext.ApiCredential.ApiAccount.Application;
                sechdr.Credentials.DevId    = ApiContext.ApiCredential.ApiAccount.Developer;
                sechdr.Credentials.AuthCert = ApiContext.ApiCredential.ApiAccount.Certificate;

                //Need Username if SecretID is used
                if (ApiContext.ApiCredential.eBayAccount != null && ApiContext.ApiCredential.eBayAccount.UserName != null &&
                    ApiContext.ApiCredential.eBayAccount.UserName.Length > 0)
                {
                    sechdr.Credentials.Username = ApiContext.ApiCredential.eBayAccount.UserName;
                }
            }

            return(sechdr);
        }
        private CustomSecurityHeaderType PaypalSecurityHeader()
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            var credentials = new CustomSecurityHeaderType();

            credentials.Credentials = new UserIdPasswordType();
            if (Settings.UseSandbox == "True")
            {
                _paypalService2 = new PayPalAPIAAInterfaceClient("PayPalAPISandbox");
                _paypalService1 = new PayPalAPIInterfaceClient("PayPalAPIINTSandbox");
            }
            else
            {
                _paypalService2 = new PayPalAPIAAInterfaceClient("PayPalAPIProduction");
                _paypalService1 = new PayPalAPIInterfaceClient("PayPalAPIINTProduction");
            }
            credentials.Credentials.Username  = Settings.UserName;
            credentials.Credentials.Password  = Settings.Password;
            credentials.Credentials.Signature = Settings.Signature;
            credentials.Credentials.Subject   = "";
            return(credentials);
        }
Example #23
0
        public ActionResult PaymentConfirmation(int?orderId)
        {
            if (!orderId.HasValue)
            {
                return(RedirectToAction("PayPalCancel"));
            }
            var response = Session["CheckoutDetails"] as GetExpressCheckoutDetailsResponseType;

            if (response == null)
            {
                return(RedirectToAction("PayPalCancel"));
            }
            DoExpressCheckoutPaymentReq          payReq      = PayPalHelper.GetDoExpressCheckoutPaymentReq(response);
            CustomSecurityHeaderType             credentials = PayPalHelper.GetPayPalCredentials();
            PayPalAPIAAInterfaceClient           client      = new PayPalAPIAAInterfaceClient();
            DoExpressCheckoutPaymentResponseType doResponse  = client.DoExpressCheckoutPayment(ref credentials, payReq);

            if (doResponse.Errors != null && doResponse.Errors.Length > 0)
            {
                throw new Exception("Exception occured when calling PayPal: " + doResponse.Errors[0].LongMessage);
            }
            PayPalHelper.UpdateOrderAfterConfirmation(orderId.Value);
            return(RedirectToAction("PayPalSuccess"));
        }
Example #24
0
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                CustomSecurityHeaderType _credentials = new CustomSecurityHeaderType();
                //{
                //    Credentials = new UserIdPasswordType()
                //    {
                //        Username = "******",
                //        Password = "******",
                //        Signature = "Ao--X15RhKPZUeA3L9bihv008SFUAc03629aPWDtEWfOvvTchBkLtV3A",
                //    }
                //};

                //GetExpressCheckoutDetailsRequestType request = new GetExpressCheckoutDetailsRequestType();
                //request.Token = Request.QueryString["Token"].ToString();

                //// Invoke the API
                //GetExpressCheckoutDetailsReq wrapper = new GetExpressCheckoutDetailsReq();
                //wrapper.GetExpressCheckoutDetailsRequest = request;



                PayPalAPI.PayPalAPIAAInterfaceClient objPayPalAPI = new PayPalAPIAAInterfaceClient();

                //var getExpRes = objPayPalAPI.GetExpressCheckoutDetails(ref _credentials,wrapper);
                //if(getExpRes.Ack==AckCodeType.Success && getExpRes.GetExpressCheckoutDetailsResponseDetails.PaymentInfo[0].PaymentStatus==PaymentStatusCodeType.Pending)
                //{
                //    //Show Error Message and save details in DB
                //}
                //else
                //{
                Dictionary <string, string> PPPayment = new Dictionary <string, string>();
                PPPayment = (Dictionary <string, string>)Session["PPPaymentDetails"];
                var payReq = new DoExpressCheckoutPaymentReq
                {
                    DoExpressCheckoutPaymentRequest = new DoExpressCheckoutPaymentRequestType
                    {
                        Version = "98",
                        DoExpressCheckoutPaymentRequestDetails = new DoExpressCheckoutPaymentRequestDetailsType
                        {
                            Token                  = Request.QueryString["Token"].ToString(),
                            PayerID                = Request.QueryString["PayerId"].ToString(),
                            PaymentAction          = PaymentActionCodeType.Sale,
                            PaymentActionSpecified = true,

                            PaymentDetails = new[]
                            {
                                new PaymentDetailsType
                                {
                                    OrderTotal = new BasicAmountType
                                    {
                                        currencyID = CurrencyCodeType.AUD,
                                        Value      = PPPayment["Amount"].ToString(),
                                    }
                                }
                            }
                        }
                    }
                };
                _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 DoExpRes = objPayPalAPI.DoExpressCheckoutPayment(ref _credentials, payReq);


                //Read the connection string from Web.Config file
                string ConnectionString = ConfigurationManager.ConnectionStrings["DefaultConnectionsql"].ConnectionString;
                using (SqlConnection con = new SqlConnection(ConnectionString))
                {
                    try
                    {
                        //Create the SqlCommand object
                        SqlCommand cmd = new SqlCommand("sp_InsertPayPalPaymentDetails", con);

                        //Specify that the SqlCommand is a stored procedure
                        cmd.CommandType = System.Data.CommandType.StoredProcedure;



                        //Add the input parameters to the command object
                        cmd.Parameters.AddWithValue("@AccNum", PPPayment["AccNum"]);
                        cmd.Parameters.AddWithValue("@Amount", PPPayment["Amount"]);
                        cmd.Parameters.AddWithValue("@Token", Request.QueryString["Token"].ToString());
                        cmd.Parameters.AddWithValue("@PayerId", Request.QueryString["PayerId"].ToString());
                        cmd.Parameters.AddWithValue("@ExpressChkResp", DoExpRes.Ack);
                        if (DoExpRes.Errors != null)
                        {
                            if (DoExpRes.Errors.Count() > 0)
                            {
                                cmd.Parameters.AddWithValue("@PPError", DoExpRes.Errors[0].ShortMessage);
                            }
                        }
                        else
                        {
                            cmd.Parameters.AddWithValue("@PPError", "");
                        }
                        if (DoExpRes.DoExpressCheckoutPaymentResponseDetails.BillingAgreementID != null)
                        {
                            cmd.Parameters.AddWithValue("@BillingAgreementId", DoExpRes.DoExpressCheckoutPaymentResponseDetails.BillingAgreementID);
                        }
                        else
                        {
                            cmd.Parameters.AddWithValue("@BillingAgreementId", "");
                        }
                        if (DoExpRes.DoExpressCheckoutPaymentResponseDetails.MsgSubID != null)
                        {
                            cmd.Parameters.AddWithValue("@MsgSubId", DoExpRes.DoExpressCheckoutPaymentResponseDetails.MsgSubID);
                        }
                        else
                        {
                            cmd.Parameters.AddWithValue("@MsgSubId", "");
                        }
                        if (DoExpRes.DoExpressCheckoutPaymentResponseDetails.Note != null)
                        {
                            cmd.Parameters.AddWithValue("@Note", DoExpRes.DoExpressCheckoutPaymentResponseDetails.Note);
                        }
                        else
                        {
                            cmd.Parameters.AddWithValue("@Note", "");
                        }
                        if (DoExpRes.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].GrossAmount != null)
                        {
                            cmd.Parameters.AddWithValue("@GrossAmount", DoExpRes.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].GrossAmount.Value);
                        }
                        else
                        {
                            cmd.Parameters.AddWithValue("@GrossAmount", "");
                        }
                        if (DoExpRes.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].PaymentDate != null)
                        {
                            cmd.Parameters.AddWithValue("@PaymentDate", DoExpRes.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].PaymentDate);
                        }
                        else
                        {
                            cmd.Parameters.AddWithValue("@PaymentDate", "");
                        }
                        if (DoExpRes.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].PaymentError != null)
                        {
                            cmd.Parameters.AddWithValue("@PaymentError", DoExpRes.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].PaymentError.ShortMessage);
                        }
                        else
                        {
                            cmd.Parameters.AddWithValue("@PaymentError", "");
                        }
                        if (DoExpRes.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].PaymentRequestID != null)
                        {
                            cmd.Parameters.AddWithValue("@PaymentRequestID", DoExpRes.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].PaymentRequestID);
                        }
                        else
                        {
                            cmd.Parameters.AddWithValue("@PaymentRequestID", "");
                        }
                        if (DoExpRes.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].PaymentStatus != null)
                        {
                            cmd.Parameters.AddWithValue("@PaymentStatus", DoExpRes.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].PaymentStatus);
                        }
                        else
                        {
                            cmd.Parameters.AddWithValue("@PaymentStatus", "");
                        }
                        if (DoExpRes.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].PaymentType != null)
                        {
                            cmd.Parameters.AddWithValue("@PaymentType", DoExpRes.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].PaymentType.ToString());
                        }
                        else
                        {
                            cmd.Parameters.AddWithValue("@PaymentType", "");
                        }
                        if (DoExpRes.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].ReceiptID != null)
                        {
                            cmd.Parameters.AddWithValue("@ReceiptID", DoExpRes.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].ReceiptID);
                        }
                        else
                        {
                            cmd.Parameters.AddWithValue("@ReceiptID", "");
                        }
                        if (DoExpRes.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].ReceiptReferenceNumber != null)
                        {
                            cmd.Parameters.AddWithValue("@ReceiptReferenceNumber", DoExpRes.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].ReceiptReferenceNumber);
                        }
                        else
                        {
                            cmd.Parameters.AddWithValue("@ReceiptReferenceNumber", "");
                        }
                        if (DoExpRes.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].TransactionID != null)
                        {
                            cmd.Parameters.AddWithValue("@TransactionID", DoExpRes.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].TransactionID);
                        }
                        else
                        {
                            cmd.Parameters.AddWithValue("@TransactionID", "");
                        }
                        if (DoExpRes.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].TransactionType != null)
                        {
                            cmd.Parameters.AddWithValue("@TransactionType", DoExpRes.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].TransactionType.ToString());
                        }
                        else
                        {
                            cmd.Parameters.AddWithValue("@TransactionType", "");
                        }


                        //Open the connection and execute the query
                        con.Open();

                        cmd.ExecuteScalar();
                    }
                    catch (Exception ex)
                    {
                        StreamWriter file2 = File.AppendText(HttpContext.Current.Server.MapPath("~/Logs/file.txt"));

                        file2.WriteLine("Saving Error : " + DateTime.Now + "   " + ex.Message);

                        file2.Close();
                    }
                }

                if (DoExpRes.Ack == AckCodeType.Success && DoExpRes.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].PaymentStatus == PaymentStatusCodeType.Completed)
                {
                    Label1.Text = "PayPal Payment Successful ";
                }
            }
            catch (Exception ex)
            {
                StreamWriter file2 = File.AppendText(HttpContext.Current.Server.MapPath("~/Logs/file.txt"));

                file2.WriteLine("Exception : " + DateTime.Now + "  " + ex.Message);

                file2.Close();

                Response.Redirect("Default.aspx?PP=Error");
            }
            //}
        }
		/// <summary>
		/// Constructs a security header from values in <see cref="ApiCall.ApiContext"/>.
		/// </summary>
		/// <returns>Security information of type <see cref="CustomSecurityHeaderType"/>.</returns>
		protected override CustomSecurityHeaderType GetSecurityHeader()
		{
			CustomSecurityHeaderType sechdr = new CustomSecurityHeaderType();

			if (ApiContext.ApiCredential.ApiAccount != null)
			{
				sechdr.Credentials = new UserIdPasswordType();
				sechdr.Credentials.AppId = ApiContext.ApiCredential.ApiAccount.Application;
				sechdr.Credentials.DevId = ApiContext.ApiCredential.ApiAccount.Developer;
				sechdr.Credentials.AuthCert = ApiContext.ApiCredential.ApiAccount.Certificate;
				
				//Need Username if SecretID is used
				if (ApiContext.ApiCredential.eBayAccount != null && ApiContext.ApiCredential.eBayAccount.UserName != null
					&& ApiContext.ApiCredential.eBayAccount.UserName.Length > 0)
				{
					sechdr.Credentials.Username = ApiContext.ApiCredential.eBayAccount.UserName;
				}

			}
			
			return (sechdr);
		}
Example #26
0
        /// <summary>
        /// Constructs a security header from values in <see cref="ApiCall.ApiContext"/>.
        /// </summary>
        /// <returns>Security information of type <see cref="CustomSecurityHeaderType"/>.</returns>
        protected override CustomSecurityHeaderType GetSecurityHeader()
        {
            CustomSecurityHeaderType sechdr = new CustomSecurityHeaderType();

            if (ApiContext.ApiCredential.ApiAccount != null)
            {
                sechdr.Credentials = new UserIdPasswordType();
                sechdr.Credentials.AppId = ApiContext.ApiCredential.ApiAccount.Application;
                sechdr.Credentials.DevId = ApiContext.ApiCredential.ApiAccount.Developer;
                sechdr.Credentials.AuthCert = ApiContext.ApiCredential.ApiAccount.Certificate;
            }
            else
            {
                    throw new SdkException("GetSessionID needs Api Account to be called!");
            }

            return (sechdr);
        }
Example #27
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);
            }
        }
Example #28
0
 public static OrderInfo Charge(decimal total, string PayPalToken, string payerId)
 {
     System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
     using (var client = new PayPalAPIAAInterfaceClient(new BasicHttpsBinding(), new EndpointAddress(EndpointUrl)))
     {
         var credentials = new CustomSecurityHeaderType()
         {
             Credentials = new UserIdPasswordType()
             {
                 Username  = APIUserName,
                 Password  = APIPassword,
                 Signature = APISignature
             }
         };
         DoExpressCheckoutPaymentReq req = new DoExpressCheckoutPaymentReq()
         {
             DoExpressCheckoutPaymentRequest = new DoExpressCheckoutPaymentRequestType()
             {
                 Version = "121.0",
                 DoExpressCheckoutPaymentRequestDetails = new DoExpressCheckoutPaymentRequestDetailsType()
                 {
                     PaymentAction          = PaymentActionCodeType.Sale,
                     PaymentActionSpecified = true,
                     Token          = PayPalToken,
                     PayerID        = payerId,
                     PaymentDetails = new PaymentDetailsType[1] {
                         new PaymentDetailsType()
                         {
                             OrderTotal = new BasicAmountType()
                             {
                                 currencyID = CurrencyCodeType.USD,
                                 Value      = total.ToString("F2")
                             },
                             ShippingTotal = new BasicAmountType()
                             {
                                 currencyID = CurrencyCodeType.USD,
                                 Value      = "0.00"
                             },
                             TaxTotal = new BasicAmountType()
                             {
                                 currencyID = CurrencyCodeType.USD,
                                 Value      = "0.00"
                             },
                             ItemTotal = new BasicAmountType()
                             {
                                 currencyID = CurrencyCodeType.USD,
                                 Value      = total.ToString("F2")
                             }
                         }
                     }
                 }
             }
         };
         DoExpressCheckoutPaymentResponseType resp = client.DoExpressCheckoutPayment(ref credentials, req);
         string    errors = CheckErrors(resp);
         OrderInfo info   = new OrderInfo();
         if (errors == String.Empty)
         {
             info.Ack           = resp.Ack.ToString();
             info.TransactionID = resp.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].TransactionID;
             info.ReceiptID     = resp.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].ReceiptID;
         }
         else
         {
             info.Ack = errors;
         }
         return(info);
     }
 }
Example #29
0
        static public OrderInfo Charge(string firstName, string lastName, string address1, string address2, string city, string state, string zip, string country, string ccType, string ccNumber, string ccAuthCode,
                                       int ccExpireYear, int ccExpireMonth, decimal priceFinal, decimal priceTax, decimal priceShipping)
        {
            System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
            CreditCardTypeType cardType = CreditCardTypeType.Visa;

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

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

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

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

            using (var client = new PayPalAPIAAInterfaceClient(new BasicHttpsBinding(), new EndpointAddress(EndpointUrl)))
            {
                var credentials = new CustomSecurityHeaderType()
                {
                    Credentials = new UserIdPasswordType()
                    {
                        Username  = APIUserName,
                        Password  = APIPassword,
                        Signature = APISignature
                    }
                };
                DoDirectPaymentReq req = new DoDirectPaymentReq()
                {
                    DoDirectPaymentRequest = new DoDirectPaymentRequestType()
                    {
                        Version = "121.0",
                        DoDirectPaymentRequestDetails = new DoDirectPaymentRequestDetailsType()
                        {
                            CreditCard = new CreditCardDetailsType()
                            {
                                CardOwner = new PayerInfoType()
                                {
                                    PayerName = new PersonNameType()
                                    {
                                        FirstName = firstName,
                                        LastName  = lastName
                                    },
                                    Address = new AddressType()
                                    {
                                        CityName        = city,
                                        StateOrProvince = state,
                                        PostalCode      = zip,
                                        Country         = countryCode,
                                        Street1         = address1,
                                        Street2         = address2
                                    }
                                },
                                CreditCardNumber        = ccNumber,
                                CreditCardType          = cardType,
                                CreditCardTypeSpecified = true,
                                CVV2              = ccAuthCode,
                                ExpMonth          = ccExpireMonth,
                                ExpMonthSpecified = true,
                                ExpYear           = ccExpireYear,
                                ExpYearSpecified  = true
                            },
                            PaymentAction  = PaymentActionCodeType.Sale,
                            PaymentDetails = new PaymentDetailsType()
                            {
                                OrderTotal = new BasicAmountType()
                                {
                                    currencyID = CurrencyCodeType.USD,
                                    Value      = priceFinal.ToString("F2")
                                },
                                ShippingTotal = new BasicAmountType()
                                {
                                    currencyID = CurrencyCodeType.USD,
                                    Value      = priceShipping.ToString("F2")
                                },
                                TaxTotal = new BasicAmountType()
                                {
                                    currencyID = CurrencyCodeType.USD,
                                    Value      = priceTax.ToString("F2")
                                }
                            }
                        }
                    }
                };
                var response = client.DoDirectPayment(ref credentials, req);
                // check errors
                string    errors = CheckErrors(response);
                OrderInfo info   = new OrderInfo();
                if (errors == String.Empty)
                {
                    info.Ack           = response.Ack.ToString();
                    info.TransactionID = response.TransactionID;
                    info.CVV2Code      = response.CVV2Code;
                }
                else
                {
                    info.Ack = errors;
                }
                return(info);
            }
        }
Example #30
0
		/// <summary>
		/// Constructs a security header from values in <see cref="ApiContext"/>.
		/// </summary>
		/// <returns>Security information of type <see cref="CustomSecurityHeaderType"/>.</returns>
		protected virtual CustomSecurityHeaderType GetSecurityHeader()
		{
			CustomSecurityHeaderType sechdr = new CustomSecurityHeaderType();
			if (ApiContext.ApiCredential.eBayToken != null && ApiContext.ApiCredential.eBayToken.Length > 0)
			{
				sechdr.eBayAuthToken = ApiContext.ApiCredential.eBayToken;
			}
			
			return (sechdr);
		}
Example #31
0
    public PayPalReturn Pay(string orderNumber, string paymentAmount, string buyerLastName, string buyerFirstName, string buyerAddress, string buyerCity, string buyerStateOrProvince, string buyerCountryCode, string buyerCountryName, string buyerZipCode, string creditCardType, string creditCardNumber, string CVV2, string expMonth, string expYear)
    {
        //PayPal Return Structure
        PayPalReturn rv = new PayPalReturn();

        rv.IsSucess = false;

        DoDirectPaymentRequestDetailsType requestDetails = new DoDirectPaymentRequestDetailsType();

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

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

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

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

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

        DoDirectPaymentReq request = new DoDirectPaymentReq();

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

        //Headers
        CustomSecurityHeaderType headers = new CustomSecurityHeaderType();

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

        //Client
        PayPalAPIAASoapBinding client = new PayPalAPIAASoapBinding();

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

        if (response.Ack == AckCodeType.Success || response.Ack == AckCodeType.SuccessWithWarning)
        {
            rv.IsSucess      = true;
            rv.TransactionID = response.TransactionID;
        }
        else
        {
            rv.ErrorMessage = response.Errors[0].LongMessage;
        }
        return(rv);
    }
Example #32
0
        /// <summary>
        ///
        /// </summary>
        internal void SendRequest()
        {
            try
            {
                if (AbstractRequest == null)
                {
                    throw new ApiException("RequestType reference not set to an instance of an object.", new System.ArgumentNullException());
                }
                if (ApiContext == null)
                {
                    throw new ApiException("ApiContext reference not set to an instance of an object.", new System.ArgumentNullException());
                }
                if (ApiContext.ApiCredential == null)
                {
                    throw new ApiException("Credentials reference in ApiContext object not set to an instance of an object.", new System.ArgumentNullException());
                }

                string apiName = AbstractRequest.GetType().Name.Replace("RequestType", "");

                if (this.ApiContext.EnableMetrics)
                {
                    mCallMetrics = this.ApiContext.CallMetricsTable.GetNewEntry(apiName);
                    mCallMetrics.ApiCallStarted = System.DateTime.Now;
                }

                CustomSecurityHeaderType secHdr = this.GetSecurityHeader();

                // Get default constructor.

                /*
                 * ConstructorInfo svcCCTor = this.mServiceType.GetConstructor(
                 *  BindingFlags.Instance | BindingFlags.Public, null,
                 *  CallingConventions.HasThis, null, null);
                 */
                ConstructorInfo svcCCTor = this.mServiceType.GetConstructor(new Type[] { });

                object svcInst = svcCCTor.Invoke(null);

                PropertyInfo pi;

                pi = this.mServiceType.GetProperty("ApiLogManager");
                if (pi == null)
                {
                    throw new SdkException("ApiLogManager was not found in InterfaceServiceType");
                }
                pi.SetValue(svcInst, this.mApiContext.ApiLogManager, null);

                pi = this.mServiceType.GetProperty("EnableComression");
                if (pi == null)
                {
                    throw new SdkException("EnableComression was not found in InterfaceServiceType");
                }
                pi.SetValue(svcInst, this.mEnableCompression, null);

                //Add oAuth
                //if (pi == null)
                //    throw new SdkException("RequesterCredentials was not found in InterfaceServiceType");
                //pi.SetValue(svcInst, this., null);
                if (string.IsNullOrEmpty(this.ApiContext.ApiCredential.oAuthToken))
                {
                    pi = this.mServiceType.GetProperty("RequesterCredentials");
                    if (pi == null)
                    {
                        throw new SdkException("RequesterCredentials was not found in InterfaceServiceType");
                    }
                    pi.SetValue(svcInst, secHdr, null);
                }

                pi = this.mServiceType.GetProperty("WebProxy");
                if (pi == null)
                {
                    throw new SdkException("WebProxy was not found in InterfaceServiceType");
                }
                pi.SetValue(svcInst, this.mApiContext.WebProxy, null);
                if (this.mApiContext.WebProxy != null)
                {
                    LogMessage("Proxy Server is Set", MessageType.Information, MessageSeverity.Informational);
                }

                pi = this.mServiceType.GetProperty("CallMetricsEntry");
                if (pi == null)
                {
                    throw new SdkException("CallMetricsEntry was not found in InterfaceServiceType");
                }
                if (this.ApiContext.EnableMetrics)
                {
                    pi.SetValue(svcInst, this.mCallMetrics, null);
                }
                else
                {
                    pi.SetValue(svcInst, null, null);
                }

                pi = this.mServiceType.GetProperty("OAuthToken");
                if (!string.IsNullOrEmpty(this.ApiContext.ApiCredential.oAuthToken))
                {
                    this.mOAuth = this.ApiContext.ApiCredential.oAuthToken;
                    pi.SetValue(svcInst, this.OAuth, null);
                }

                string url = "";
                try
                {
                    if (ApiContext.SoapApiServerUrl != null && ApiContext.SoapApiServerUrl.Length > 0)
                    {
                        url = String.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}?callname={1}&siteid={2}&client=netsoap",
                                            ApiContext.SoapApiServerUrl, apiName, SiteUtility.GetSiteID(Site).ToString(System.Globalization.CultureInfo.InvariantCulture));
                    }
                    else
                    {
                        url = (string)this.mServiceType.GetProperty("Url").GetValue(svcInst, null);
                        url = String.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}?callname={1}&siteid={2}&client=netsoap",
                                            url, apiName, SiteUtility.GetSiteID(Site).ToString(System.Globalization.CultureInfo.InvariantCulture));
                    }

                    //svcCCTor.Url = url;
                    this.mServiceType.GetProperty("Url").SetValue(svcInst, url, null);
                }
                catch (Exception ex)
                {
                    throw new ApiException(ex.Message, ex);
                }

                LogMessage(url, MessageType.Information, MessageSeverity.Informational);

                //svcCCTor.Timeout = Timeout;
                this.mServiceType.GetProperty("Timeout").SetValue(svcInst, Timeout, null);

                AbstractRequest.Version = Version;

                if (!mDetailLevelOverride && AbstractRequest.DetailLevel == null)
                {
                    AbstractRequest.DetailLevel = new DetailLevelCodeTypeCollection();
                    AbstractRequest.DetailLevel.AddRange(mDetailLevelList);
                }

                //Added OutputSelector to base call JIRA-SDK-561
                AbstractRequest.OutputSelector = new StringCollection();
                AbstractRequest.OutputSelector.AddRange(mOutputSelector);

                if (ApiContext.ErrorLanguage != ErrorLanguageCodeType.CustomCode)
                {
                    AbstractRequest.ErrorLanguage = ApiContext.ErrorLanguage.ToString();
                }

                //Populate the message
                AbstractRequest.MessageID = System.Guid.NewGuid().ToString();

                Type     methodtype = svcInst.GetType();
                object[] reqparm    = new object[] { AbstractRequest };

                int       retries    = 0;
                int       maxRetries = 0;
                bool      doretry    = false;
                CallRetry retry      = null;
                if (mCallRetry != null)
                {
                    retry      = mCallRetry;
                    maxRetries = retry.MaximumRetries;
                }
                else if (ApiContext.CallRetry != null)
                {
                    retry      = ApiContext.CallRetry;
                    maxRetries = retry.MaximumRetries;
                }


                do
                {
                    Exception callException = null;
                    try
                    {
                        mResponse     = null;
                        mApiException = null;

                        if (retries > 0)
                        {
                            LogMessage("Invoking Call Retry", MessageType.Information, MessageSeverity.Informational);
                            System.Threading.Thread.Sleep(retry.DelayTime);
                        }

                        if (BeforeRequest != null)
                        {
                            BeforeRequest(this, new BeforeRequestEventArgs(AbstractRequest));
                        }


                        //Invoke the Service
                        DateTime start = DateTime.Now;
                        mResponse     = (AbstractResponseType)methodtype.GetMethod(apiName).Invoke(svcInst, reqparm);
                        mResponseTime = DateTime.Now - start;

                        if (AfterRequest != null)
                        {
                            AfterRequest(this, new AfterRequestEventArgs(mResponse));
                        }

                        // Catch Token Expiration warning
                        if (mResponse != null && secHdr.HardExpirationWarning != null)
                        {
                            ApiContext.ApiCredential.TokenHardExpirationWarning(
                                System.Convert.ToDateTime(secHdr.HardExpirationWarning, System.Globalization.CultureInfo.CurrentUICulture));
                        }


                        if (mResponse != null && mResponse.Errors != null && mResponse.Errors.Count > 0)
                        {
                            throw new ApiException(new ErrorTypeCollection(mResponse.Errors));
                        }
                    }

                    catch (Exception ex)
                    {
                        // this catches soap faults
                        if (ex.GetType() == typeof(TargetInvocationException))
                        {
                            // we never care about the outer exception
                            Exception iex = ex.InnerException;

                            // Parse Soap Faults
                            if (iex.GetType() == typeof(SoapException))
                            {
                                ex = ApiException.FromSoapException((SoapException)iex);
                            }
                            else if (iex.GetType() == typeof(InvalidOperationException))
                            {
                                // Go to innermost exception
                                while (iex.InnerException != null)
                                {
                                    iex = iex.InnerException;
                                }
                                ex = new ApiException(iex.Message, iex);
                            }
                            else if (iex.GetType() == typeof(HttpException))
                            {
                                HttpException httpEx = (HttpException)iex;
                                String        str    = "HTTP Error Code: " + httpEx.StatusCode;
                                ex = new ApiException(str, iex);
                            }
                            else
                            {
                                ex = new ApiException(iex.Message, iex);
                            }
                        }
                        callException = ex;

                        // log the message - override current switches - *if* (a) we wouldn't normally log it, and (b)
                        // the exception matches the exception filter.

                        if (retry != null)
                        {
                            doretry = retry.ShouldRetry(ex);
                        }

                        if (!doretry || retries == maxRetries)
                        {
                            throw ex;
                        }
                        else
                        {
                            string soapReq  = (string)this.mServiceType.GetProperty("SoapRequest").GetValue(svcInst, null);
                            string soapResp = (string)this.mServiceType.GetProperty("SoapResponse").GetValue(svcInst, null);

                            LogMessagePayload(soapReq + "\r\n\r\n" + soapResp, MessageSeverity.Informational, ex);
                            MessageSeverity svr = ((ApiException)ex).SeverityErrorCount > 0 ? MessageSeverity.Error : MessageSeverity.Warning;
                            LogMessage(ex.Message, MessageType.Exception, svr);
                        }
                    }

                    finally
                    {
                        string soapReq  = (string)this.mServiceType.GetProperty("SoapRequest").GetValue(svcInst, null);
                        string soapResp = (string)this.mServiceType.GetProperty("SoapResponse").GetValue(svcInst, null);

                        if (!doretry || retries == maxRetries)
                        {
                            LogMessagePayload(soapReq + "\r\n\r\n" + soapResp, MessageSeverity.Informational, callException);
                        }

                        if (mResponse != null && mResponse.TimestampSpecified)
                        {
                            ApiContext.CallUpdate(mResponse.Timestamp);
                        }
                        else
                        {
                            ApiContext.CallUpdate(new DateTime(0));
                        }

                        mSoapRequest  = soapReq;
                        mSoapResponse = soapResp;
                        retries++;
                    }
                } while (doretry && retries <= maxRetries);
            }

            catch (Exception ex)
            {
                ApiException aex = ex as ApiException;

                if (aex != null)
                {
                    mApiException = aex;
                }
                else
                {
                    mApiException = new ApiException(ex.Message, ex);
                }
                MessageSeverity svr = mApiException.SeverityErrorCount > 0 ? MessageSeverity.Error : MessageSeverity.Warning;
                LogMessage(mApiException.Message, MessageType.Exception, svr);

                if (mApiException.SeverityErrorCount > 0)
                {
                    throw mApiException;
                }
            }
            finally
            {
                if (this.ApiContext.EnableMetrics)
                {
                    mCallMetrics.ApiCallEnded = DateTime.Now;
                }
            }
        }
Example #33
0
        internal void SendRequest2()
        {
            try
            {
                if (AbstractRequest == null)
                {
                    throw new ApiException("RequestType reference not set to an instance of an object.", new System.ArgumentNullException());
                }
                if (ApiContext == null)
                {
                    throw new ApiException("ApiContext reference not set to an instance of an object.", new System.ArgumentNullException());
                }
                if (ApiContext.ApiCredential == null)
                {
                    throw new ApiException("Credentials reference in ApiContext object not set to an instance of an object.", new System.ArgumentNullException());
                }



                string apiName     = AbstractRequest.GetType().Name.Replace("RequestType", "");
                var    requestName = Type.GetType("eBay.Service.Core.Soap." + apiName + "Request");


                if (this.ApiContext.EnableMetrics)
                {
                    mCallMetrics = this.ApiContext.CallMetricsTable.GetNewEntry(apiName);
                    mCallMetrics.ApiCallStarted = System.DateTime.Now;
                }


                string url = "";
                try
                {
                    if (ApiContext.SoapApiServerUrl != null && ApiContext.SoapApiServerUrl.Length > 0)
                    {
                        url = String.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}?callname={1}&siteid={2}&client=netsoap",
                                            ApiContext.SoapApiServerUrl, apiName, SiteUtility.GetSiteID(Site).ToString(System.Globalization.CultureInfo.InvariantCulture));
                    }
                    else
                    {
                        url = "https://api.ebay.com/wsapi";
                        url = String.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}?callname={1}&siteid={2}&client=netsoap",
                                            url, apiName, SiteUtility.GetSiteID(Site).ToString(System.Globalization.CultureInfo.InvariantCulture));
                    }
                }
                catch (Exception ex)
                {
                    throw new ApiException(ex.Message, ex);
                }

                LogMessage(url, MessageType.Information, MessageSeverity.Informational);



                //mEnableCompression//数据压缩
                //moAuthToken//moAuthToken授权//
                //mWebProxy//代理
                //mCallMetrics速度监控



                var eBayAPIInterfaceClient = eBayAPIInstance.Instance.GeteBayAPIClient(url, timeout: this.Timeout);
                //var 报文 = new 报文();
                //eBayAPIInterfaceClient.Endpoint.EndpointBehaviors.Add(new ContextPropagationBehavior(报文));
                //PropertyInfo pi;

                //pi = this.mServiceType.GetProperty("ApiLogManager");
                //if (pi == null)
                //    throw new SdkException("ApiLogManager was not found in InterfaceServiceType");
                //pi.SetValue(svcInst, this.mApiContext.ApiLogManager, null);

                //pi = this.mServiceType.GetProperty("EnableComression");
                //if (pi == null)
                //    throw new SdkException("EnableComression was not found in InterfaceServiceType");
                //pi.SetValue(svcInst, this.mEnableCompression, null);

                //Add oAuth
                //if (pi == null)
                //    throw new SdkException("RequesterCredentials was not found in InterfaceServiceType");
                //pi.SetValue(svcInst, this., null);
                //if (string.IsNullOrEmpty(this.ApiContext.ApiCredential.oAuthToken))
                //{
                //    pi = this.mServiceType.GetProperty("RequesterCredentials");
                //    if (pi == null)
                //        throw new SdkException("RequesterCredentials was not found in InterfaceServiceType");
                //    pi.SetValue(svcInst, secHdr, null);
                //}

                //pi = this.mServiceType.GetProperty("WebProxy");
                //if (pi == null)
                //    throw new SdkException("WebProxy was not found in InterfaceServiceType");
                //pi.SetValue(svcInst, this.mApiContext.WebProxy, null);
                //if (this.mApiContext.WebProxy != null)
                //{
                //    LogMessage("Proxy Server is Set", MessageType.Information, MessageSeverity.Informational);
                //}

                //pi = this.mServiceType.GetProperty("CallMetricsEntry");
                //if (pi == null)
                //    throw new SdkException("CallMetricsEntry was not found in InterfaceServiceType");
                //if (this.ApiContext.EnableMetrics)
                //    pi.SetValue(svcInst, this.mCallMetrics, null);
                //else
                //    pi.SetValue(svcInst, null, null);

                //pi = this.mServiceType.GetProperty("OAuthToken");
                //if (!string.IsNullOrEmpty(this.ApiContext.ApiCredential.oAuthToken))
                //{
                //    this.mOAuth = this.ApiContext.ApiCredential.oAuthToken;
                //    pi.SetValue(svcInst, this.OAuth, null);
                //}



                ////svcCCTor.Timeout = Timeout;
                //this.mServiceType.GetProperty("Timeout").SetValue(svcInst, Timeout, null);

                AbstractRequest.Version = Version;

                if (!mDetailLevelOverride && AbstractRequest.DetailLevel == null)
                {
                    AbstractRequest.DetailLevel = mDetailLevelList;
                }

                //Added OutputSelector to base call JIRA-SDK-561
                AbstractRequest.OutputSelector = mOutputSelector;

                if (ApiContext.ErrorLanguage != ErrorLanguageCodeType.CustomCode)
                {
                    AbstractRequest.ErrorLanguage = ApiContext.ErrorLanguage.ToString();
                }

                //Populate the message
                AbstractRequest.MessageID = System.Guid.NewGuid().ToString();

                //Type methodtype = svcInst.GetType();
                //object[] reqparm = new object[] { AbstractRequest };

                CustomSecurityHeaderType secHdr = this.GetSecurityHeader();
                var request = System.Activator.CreateInstance(requestName);
                requestName.GetProperty("RequesterCredentials").SetValue(request, secHdr);
                requestName.GetProperty(apiName + "RequestType").SetValue(request, AbstractRequest);
                //, secHdr, this.AbstractRequest
                int       retries    = 0;
                int       maxRetries = 0;
                bool      doretry    = false;
                CallRetry retry      = null;
                if (mCallRetry != null)
                {
                    retry      = mCallRetry;
                    maxRetries = retry.MaximumRetries;
                }
                else if (ApiContext.CallRetry != null)
                {
                    retry      = ApiContext.CallRetry;
                    maxRetries = retry.MaximumRetries;
                }



                do
                {
                    Exception callException = null;
                    try
                    {
                        //        mResponse = null;
                        //        mApiException = null;

                        if (retries > 0)
                        {
                            LogMessage("Invoking Call Retry", MessageType.Information, MessageSeverity.Informational);
                            System.Threading.Thread.Sleep(retry.DelayTime);
                        }

                        if (BeforeRequest != null)
                        {
                            BeforeRequest(this, new BeforeRequestEventArgs(AbstractRequest));
                        }


                        //Invoke the Service
                        DateTime start = DateTime.Now;
                        //mResponse = (AbstractResponseType)methodtype.GetMethod(apiName).Invoke(svcInst, reqparm);

                        if (mCallMetrics != null)
                        {
                            mCallMetrics.NetworkSendStarted = DateTime.Now;
                            //request.Headers.Add("X-EBAY-API-METRICS", "true");
                        }
                        var response = eBayAPIInterfaceClient.GetType().GetMethod(apiName).Invoke(eBayAPIInterfaceClient, new[] { request });

                        mResponse = (AbstractResponseType)response.GetType().GetProperty(apiName + "ResponseType").GetValue(response);
                        if (mCallMetrics != null)
                        {
                            mCallMetrics.NetworkReceiveEnded = DateTime.Now;
                            //mCallMetrics.ServerProcessingTime = convertProcessingTime(response.Headers.Get("X-EBAY-API-PROCESS-TIME"));
                        }
                        //validate(response.StatusCode);
                        mResponseTime = DateTime.Now - start;

                        if (AfterRequest != null)
                        {
                            AfterRequest(this, new AfterRequestEventArgs(mResponse));
                        }

                        // Catch Token Expiration warning
                        if (mResponse != null && secHdr.HardExpirationWarning != null)
                        {
                            ApiContext.ApiCredential.TokenHardExpirationWarning(
                                System.Convert.ToDateTime(secHdr.HardExpirationWarning, System.Globalization.CultureInfo.CurrentUICulture));
                        }


                        if (mResponse != null && mResponse.Errors != null && mResponse.Errors.Count > 0)
                        {
                            throw new ApiException(new List <ErrorType>(mResponse.Errors));
                        }
                    }

                    catch (Exception ex)
                    {
                        // this catches soap faults
                        if (ex.GetType() == typeof(TargetInvocationException))
                        {
                            // we never care about the outer exception
                            Exception iex = ex.InnerException;

                            //// Parse Soap Faults
                            //if (iex.GetType() == typeof(SoapException))
                            //{
                            //    ex = ApiException.FromSoapException((SoapException)iex);
                            //}
                            //else
                            if (iex.GetType() == typeof(InvalidOperationException))
                            {
                                // Go to innermost exception
                                while (iex.InnerException != null)
                                {
                                    iex = iex.InnerException;
                                }
                                ex = new ApiException(iex.Message, iex);
                            }
                            else if (iex.GetType() == typeof(HttpException))
                            {
                                HttpException httpEx = (HttpException)iex;
                                String        str    = "HTTP Error Code: " + httpEx.StatusCode;
                                ex = new ApiException(str, iex);
                            }
                            else
                            {
                                ex = new ApiException(iex.Message, iex);
                            }
                        }
                        callException = ex;

                        // log the message - override current switches - *if* (a) we wouldn't normally log it, and (b)
                        // the exception matches the exception filter.

                        if (retry != null)
                        {
                            doretry = retry.ShouldRetry(ex);
                        }

                        if (!doretry || retries == maxRetries)
                        {
                            throw ex;
                        }
                        else
                        {
                            //string soapReq = 报文.发送.LastOrDefault();//  (string)this.mServiceType.GetProperty("SoapRequest").GetValue(svcInst, null);
                            //string soapResp = 报文.接收.LastOrDefault(); // (string)this.mServiceType.GetProperty("SoapResponse").GetValue(svcInst, null);

                            //LogMessagePayload(soapReq + "\r\n\r\n" + soapResp, MessageSeverity.Informational, ex);
                            MessageSeverity svr = ((ApiException)ex).SeverityErrorCount > 0 ? MessageSeverity.Error : MessageSeverity.Warning;
                            LogMessage(ex.Message, MessageType.Exception, svr);
                        }
                    }

                    finally
                    {
                        //string soapReq = 报文.发送.LastOrDefault();// (string)this.mServiceType.GetProperty("SoapRequest").GetValue(svcInst, null);
                        //string soapResp = 报文.接收.LastOrDefault(); //(string)this.mServiceType.GetProperty("SoapResponse").GetValue(svcInst, null);

                        //if (!doretry || retries == maxRetries)
                        //    LogMessagePayload(soapReq + "\r\n\r\n" + soapResp, MessageSeverity.Informational, callException);

                        if (mResponse != null && mResponse.Timestamp.HasValue)
                        {
                            ApiContext.CallUpdate(mResponse.Timestamp.Value);
                        }
                        else
                        {
                            ApiContext.CallUpdate(new DateTime(0));
                        }

                        //mSoapRequest = soapReq;
                        //mSoapResponse = soapResp;
                        retries++;



                        //var ssss = System.Xml.Linq.XElement.Parse(soapResp);
                        //var sdfsdfdsf = ssss.Elements().LastOrDefault().FirstNode.ToString();

                        //var ser = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(eBay.Service.Core.Soap.GetApiAccessRulesResponseType), "GetApiAccessRulesResponse");
                        //using (var ms = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(sdfsdfdsf)))
                        //{
                        //    var jsonObject = ser.ReadObject(ms);
                        //}
                    }
                } while (doretry && retries <= maxRetries);
            }

            catch (Exception ex)
            {
                ApiException aex = ex as ApiException;

                if (aex != null)
                {
                    mApiException = aex;
                }
                else
                {
                    mApiException = new ApiException(ex.Message, ex);
                }
                MessageSeverity svr = mApiException.SeverityErrorCount > 0 ? MessageSeverity.Error : MessageSeverity.Warning;
                LogMessage(mApiException.Message, MessageType.Exception, svr);

                if (mApiException.SeverityErrorCount > 0)
                {
                    throw mApiException;
                }
            }
            finally
            {
                if (this.ApiContext.EnableMetrics)
                {
                    mCallMetrics.ApiCallEnded = DateTime.Now;
                }
            }
        }