Пример #1
0
        /// <summary>
        /// Handles refund
        /// </summary>
        /// <param name="request">RefundPaymentRequest</param>
        /// <returns>RefundPaymentResult</returns>
        public override RefundPaymentResult Refund(RefundPaymentRequest request)
        {
            var    result        = new RefundPaymentResult();
            string transactionId = request.Order.CaptureTransactionId;

            var req = new RefundTransactionReq();

            req.RefundTransactionRequest = new RefundTransactionRequestType();
            //NOTE: Specify amount in partial refund
            req.RefundTransactionRequest.RefundType          = RefundType.Full;
            req.RefundTransactionRequest.RefundTypeSpecified = true;
            req.RefundTransactionRequest.Version             = PayPalHelper.GetApiVersion();
            req.RefundTransactionRequest.TransactionID       = transactionId;

            using (var service = new PayPalAPISoapBinding())
            {
                service.Url = PayPalHelper.GetPaypalServiceUrl(Settings);
                service.RequesterCredentials = PayPalHelper.GetPaypalApiCredentials(Settings);
                RefundTransactionResponseType response = service.RefundTransaction(req);

                string error   = string.Empty;
                bool   Success = PayPalHelper.CheckSuccess(_helper, response, out error);
                if (Success)
                {
                    result.NewPaymentStatus = PaymentStatus.Refunded;
                    //cancelPaymentResult.RefundTransactionID = response.RefundTransactionID;
                }
                else
                {
                    result.AddError(error);
                }
            }

            return(result);
        }
Пример #2
0
        public APIWrapper(string apiUserName, string apiPassword, string signature, CurrencyCode defaultCurrencyCode, bool isLive)
        {
            //TODO: CMC - Add Validation Here
            _apiUserName = apiUserName;
            _apiPassword = apiPassword;
            _signature   = signature;
            if (!Enum.IsDefined(typeof(CurrencyCodeType), Enum.GetName(typeof(CurrencyCode), defaultCurrencyCode)))
            {
                throw new ArgumentException(string.Format("Provided currency code is not a valid PayPalSvc.CurrencyCodeType. Currency Code: {0}.", defaultCurrencyCode), "defaultCurrencyCode");
            }
            ppCurrencyType = (CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), Enum.GetName(typeof(CurrencyCode), defaultCurrencyCode), true);
            _currencyCode  = defaultCurrencyCode;
            _isLive        = isLive;

            service     = new PayPalAPISoapBinding();
            service.Url = PayPalServiceUtility.GetPayPalServiceEndpoint(IsLive, true, true);
            service.RequesterCredentials                       = new CustomSecurityHeaderType();
            service.RequesterCredentials.Credentials           = new UserIdPasswordType();
            service.RequesterCredentials.Credentials.Username  = APIUserName;
            service.RequesterCredentials.Credentials.Password  = APIPassword;
            service.RequesterCredentials.Credentials.Signature = Signature;
            service.RequesterCredentials.Credentials.Subject   = string.Empty;

            service2     = new PayPalAPIAASoapBinding();
            service2.Url = PayPalServiceUtility.GetPayPalServiceEndpoint(IsLive, true, true);
            service2.RequesterCredentials                       = new CustomSecurityHeaderType();
            service2.RequesterCredentials.Credentials           = new UserIdPasswordType();
            service2.RequesterCredentials.Credentials.Username  = APIUserName;
            service2.RequesterCredentials.Credentials.Password  = APIPassword;
            service2.RequesterCredentials.Credentials.Signature = Signature;
            service2.RequesterCredentials.Credentials.Subject   = string.Empty;
        }
Пример #3
0
        protected PayPalAPISoapBinding GetApiService(TSetting settings)
        {
            var service = new PayPalAPISoapBinding();

            service.Url = settings.UseSandbox ? "https://api-3t.sandbox.paypal.com/2.0/" : "https://api-3t.paypal.com/2.0/";

            service.RequesterCredentials = GetApiCredentials(settings);

            return(service);
        }
Пример #4
0
        protected PayPalAPISoapBinding GetApiService(TSetting settings)
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            var service = new PayPalAPISoapBinding();

            service.Url = settings.UseSandbox ? "https://api-3t.sandbox.paypal.com/2.0/" : "https://api-3t.paypal.com/2.0/";

            service.RequesterCredentials = GetApiCredentials(settings);

            return(service);
        }
Пример #5
0
        /// <summary>
        /// Refunds a payment
        /// </summary>
        /// <param name="refundPaymentRequest">Request</param>
        /// <returns>Result</returns>
        public RefundPaymentResult Refund(RefundPaymentRequest refundPaymentRequest)
        {
            var result = new RefundPaymentResult();

            string transactionId = refundPaymentRequest.Order.CaptureTransactionId;

            var req = new RefundTransactionReq();

            req.RefundTransactionRequest = new RefundTransactionRequestType();
            //NOTE: Specify amount in partial refund
            req.RefundTransactionRequest.RefundType          = RefundType.Full;
            req.RefundTransactionRequest.RefundTypeSpecified = true;
            req.RefundTransactionRequest.Version             = GetApiVersion();
            req.RefundTransactionRequest.TransactionID       = transactionId;

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

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

                RefundTransactionResponseType response = service1.RefundTransaction(req);

                string error   = string.Empty;
                bool   Success = PaypalHelper.CheckSuccess(response, out error);
                if (Success)
                {
                    result.NewPaymentStatus = PaymentStatus.Refunded;
                    //cancelPaymentResult.RefundTransactionID = response.RefundTransactionID;
                }
                else
                {
                    result.AddError(error);
                }
            }

            return(result);
        }
        /// <summary>
        /// Initializes the PayPalExpressPaymentProcessor
        /// </summary>
        private void InitSettings()
        {
            useSandBox         = SettingManager.GetSettingValueBoolean("PaymentMethod.PaypalExpress.UseSandbox");
            APIAccountName     = SettingManager.GetSettingValue("PaymentMethod.PaypalExpress.APIAccountName");
            APIAccountPassword = SettingManager.GetSettingValue("PaymentMethod.PaypalExpress.APIAccountPassword");
            Signature          = SettingManager.GetSettingValue("PaymentMethod.PaypalExpress.Signature");

            if (string.IsNullOrEmpty(APIAccountName))
            {
                throw new NopException("Paypal Express API Account Name is empty");
            }

            if (string.IsNullOrEmpty(Signature))
            {
                throw new NopException("Paypal Express API Account Password is empty");
            }

            if (string.IsNullOrEmpty(APIAccountPassword))
            {
                throw new NopException("Paypal Express Signature is empty");
            }

            service1 = new PayPalAPISoapBinding();
            service2 = new PayPalAPIAASoapBinding();


            if (!useSandBox)
            {
                service2.Url = service1.Url = "https://api-3t.paypal.com/2.0/";
            }
            else
            {
                service2.Url = service1.Url = "https://api-3t.sandbox.paypal.com/2.0/";
            }

            service1.RequesterCredentials                       = new CustomSecurityHeaderType();
            service1.RequesterCredentials.Credentials           = new UserIdPasswordType();
            service1.RequesterCredentials.Credentials.Username  = APIAccountName;
            service1.RequesterCredentials.Credentials.Password  = APIAccountPassword;
            service1.RequesterCredentials.Credentials.Signature = Signature;
            service1.RequesterCredentials.Credentials.Subject   = "";

            service2.RequesterCredentials                       = new CustomSecurityHeaderType();
            service2.RequesterCredentials.Credentials           = new UserIdPasswordType();
            service2.RequesterCredentials.Credentials.Username  = APIAccountName;
            service2.RequesterCredentials.Credentials.Password  = APIAccountPassword;
            service2.RequesterCredentials.Credentials.Signature = Signature;
            service2.RequesterCredentials.Credentials.Subject   = "";
        }
Пример #7
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;
        }
Пример #8
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);
    }
Пример #9
0
        public static string GetECDetails(string payPalToken, int customerId)
        {
            var payPalRefund  = new PayPalAPISoapBinding();
            var payPalBinding = new PayPalAPIAASoapBinding();
            var payerId       = string.Empty;
            var addressStatus = string.Empty;
            var request       = new GetExpressCheckoutDetailsReq();
            var requestType   = new GetExpressCheckoutDetailsRequestType();
            var response      = new GetExpressCheckoutDetailsResponseType();
            var responseType  = new GetExpressCheckoutDetailsResponseDetailsType();

            GetPaypalRequirements(out payPalRefund, out payPalBinding);

            request.GetExpressCheckoutDetailsRequest          = requestType;
            response.GetExpressCheckoutDetailsResponseDetails = responseType;
            requestType.Token   = payPalToken;
            requestType.Version = API_VER;

            response = payPalBinding.GetExpressCheckoutDetails(request);

            var payerInfo = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo;

            payerId = payerInfo.PayerID;
            if (string.IsNullOrEmpty(payerId))              // If we don't have a PayerID the transaction must be aborted.
            {
                return(string.Empty);
            }

            addressStatus = payerInfo.Address.AddressStatus.ToString();

            //Is address AVS Confirmed or Unconfirmed?
            var requireConfirmedAddress = AppLogic.AppConfigBool("PayPal.Express.AVSRequireConfirmedAddress");

            if (requireConfirmedAddress && !addressStatus.Equals("Confirmed", StringComparison.OrdinalIgnoreCase))
            {
                return("AVSFAILED");
            }

            var customer = new Customer(customerId, true);

            customer.UpdateCustomer(
                email: customer.IsRegistered
                                        ? null
                                        : payerInfo.Payer,
                firstName: payerInfo.PayerName.FirstName,
                lastName: payerInfo.PayerName.LastName,
                phone: payerInfo.Address.Phone != null
                                        ? payerInfo.Address.Phone
                                        : string.Empty,
                okToEmail: false
                );

            //Use the address from PayPal
            var payPalAddress = Address.FindOrCreateOffSiteAddress(
                customerId: customerId,
                city: payerInfo.Address.CityName,
                stateAbbreviation: AppLogic.GetStateAbbreviation(payerInfo.Address.StateOrProvince, payerInfo.Address.CountryName),
                postalCode: payerInfo.Address.PostalCode,
                countryName: payerInfo.Address.CountryName,
                offSiteSource: AppLogic.ro_PMPayPalExpress,
                firstName: payerInfo.PayerName.FirstName,
                lastName: payerInfo.PayerName.LastName,
                address1: payerInfo.Address.Street1,
                address2: payerInfo.Address.Street2,
                phone: payerInfo.Address.Phone != null
                                        ? payerInfo.Address.Phone
                                        : null
                );

            customer.SetPrimaryAddress(payPalAddress.AddressID, AddressTypes.Billing);
            customer.SetPrimaryAddress(payPalAddress.AddressID, AddressTypes.Shipping);

            return(payerId);
        }
Пример #10
0
        public static string StartEC(ShoppingCart cart, bool boolBypassOrderReview, IDictionary <string, string> checkoutOptions)
        {
            var payPalRefund   = new PayPalAPISoapBinding();
            var payPalBinding  = new PayPalAPIAASoapBinding();
            var redirectUrl    = new StringBuilder();
            var ecOrderTotal   = new BasicAmountType();
            var request        = new SetExpressCheckoutReq();
            var requestType    = new SetExpressCheckoutRequestType();
            var requestDetails = new SetExpressCheckoutRequestDetailsType();
            var response       = new SetExpressCheckoutResponseType();
            var result         = string.Empty;
            var urlHelper      = DependencyResolver.Current.GetService <UrlHelper>();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            try
            {
                response = payPalBinding.SetExpressCheckout(request);

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

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

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

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

                redirectUrl.Append(response.Token);

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

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

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

            return(redirectUrl.ToString());
        }