Esempio n. 1
0
        protected void Submit_Click(object sender, EventArgs e)
        {
            PayPalAPIInterfaceServiceService service      = new PayPalAPIInterfaceServiceService();
            GetExpressCheckoutDetailsReq     getECWrapper = new GetExpressCheckoutDetailsReq();

            getECWrapper.GetExpressCheckoutDetailsRequest = new GetExpressCheckoutDetailsRequestType(token.Value);
            GetExpressCheckoutDetailsResponseType getECResponse = service.GetExpressCheckoutDetails(getECWrapper);

            // Create request object
            DoExpressCheckoutPaymentRequestType        request        = new DoExpressCheckoutPaymentRequestType();
            DoExpressCheckoutPaymentRequestDetailsType requestDetails = new DoExpressCheckoutPaymentRequestDetailsType();

            request.DoExpressCheckoutPaymentRequestDetails = requestDetails;

            requestDetails.PaymentDetails = getECResponse.GetExpressCheckoutDetailsResponseDetails.PaymentDetails;
            requestDetails.Token          = token.Value;
            requestDetails.PayerID        = payerId.Value;
            requestDetails.PaymentAction  = (PaymentActionCodeType)
                                            Enum.Parse(typeof(PaymentActionCodeType), paymentAction.SelectedValue);

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

            wrapper.DoExpressCheckoutPaymentRequest = request;
            DoExpressCheckoutPaymentResponseType doECResponse = service.DoExpressCheckoutPayment(wrapper);

            // Check for API return status
            setKeyResponseObjects(service, doECResponse);
        }
Esempio n. 2
0
        /**
         *
         */
        public DoExpressCheckoutPaymentResponseType DoExpressCheckoutPayment(DoExpressCheckoutPaymentReq DoExpressCheckoutPaymentReq, string apiUsername)
        {
            setStandardParams(DoExpressCheckoutPaymentReq.DoExpressCheckoutPaymentRequest);
            string resp = call("DoExpressCheckoutPayment", DoExpressCheckoutPaymentReq.toXMLString(), apiUsername);

            return(new DoExpressCheckoutPaymentResponseType(resp));
        }
Esempio n. 3
0
        public async Task <AckCodeType> DoExpressCheckoutAsync(DoExpressCheckoutPaymentReq request)
        {
            PayPalAPIAAInterfaceClient client = new PayPalAPIAAInterfaceClient();
            var response = await client.DoExpressCheckoutPaymentAsync(GetAuthorizationRequest(), request);

            return(response.DoExpressCheckoutPaymentResponse1.Ack);
        }
Esempio n. 4
0
        public void DoExpressCheckoutPayment(string token, string payerId)
        {
            var service      = new PayPalAPIInterfaceServiceService();
            var getECWrapper = new GetExpressCheckoutDetailsReq {
                GetExpressCheckoutDetailsRequest = new GetExpressCheckoutDetailsRequestType(token)
            };

            var request        = new DoExpressCheckoutPaymentRequestType();
            var requestDetails = new DoExpressCheckoutPaymentRequestDetailsType();

            request.DoExpressCheckoutPaymentRequestDetails = requestDetails;

            var getECResponse = service.GetExpressCheckoutDetails(getECWrapper);

            requestDetails.PaymentDetails = getECResponse.GetExpressCheckoutDetailsResponseDetails.PaymentDetails;
            requestDetails.Token          = token;
            requestDetails.PayerID        = payerId;
            requestDetails.PaymentAction  = PaymentActionCodeType.SALE;

            var wrapper = new DoExpressCheckoutPaymentReq {
                DoExpressCheckoutPaymentRequest = request
            };

            var doECResponse = service.DoExpressCheckoutPayment(wrapper);

            var ack = doECResponse.Ack.HasValue ? doECResponse.Ack.Value : AckCodeType.FAILURE;

            AssertCheckoutResponse(ack, doECResponse.Errors);
        }
Esempio n. 5
0
        public CheckoutPaymentResult DoExpressCheckoutPayment(User user, string token, string payerId)
        {
            var            getEcResponse = _GetExpressCheckoutDetails(token);
            CheckoutStatus status;

            if (!Enum.TryParse(getEcResponse.GetExpressCheckoutDetailsResponseDetails.CheckoutStatus, true, out status))
            {
                return new CheckoutPaymentResult {
                           Errors = new List <string> {
                               "NOCHECKOUTSTATUS"
                           }
                }
            }
            ;
            if (status == CheckoutStatus.PaymentActionNotInitiated)
            {
                user.PaypalPayerId = payerId;

                var request        = new DoExpressCheckoutPaymentRequestType();
                var requestDetails = new DoExpressCheckoutPaymentRequestDetailsType {
                    Token = token, PayerID = payerId, PaymentAction = PaymentActionCodeType.SALE
                };
                request.DoExpressCheckoutPaymentRequestDetails = requestDetails;
                requestDetails.PaymentDetails = getEcResponse.GetExpressCheckoutDetailsResponseDetails.PaymentDetails;
                var wrapper = new DoExpressCheckoutPaymentReq {
                    DoExpressCheckoutPaymentRequest = request
                };
                var doEcResponse = _payPalApiService.DoExpressCheckoutPayment(wrapper, GetApiUserName());
                var custom       = getEcResponse.GetExpressCheckoutDetailsResponseDetails.PaymentDetails[0].Custom.Split('|');
                var result       = new CheckoutPaymentResult {
                    BillingAgreementId = doEcResponse.DoExpressCheckoutPaymentResponseDetails.BillingAgreementID,
                    PaymentStatus      = doEcResponse.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].PaymentStatus.ToString(),
                    PendingReason      = doEcResponse.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].PendingReason.ToString(),
                    TransactionId      = doEcResponse.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].TransactionID,
                    ProductName        = (ProductNames)Enum.Parse(typeof(ProductNames), custom[0], true),
                    Referrer           = custom[1],
                    Errors             = new List <string>(),
                };
                if (doEcResponse.Ack.Equals(AckCodeType.FAILURE) || (doEcResponse.Errors != null && doEcResponse.Errors.Count > 0))
                {
                    foreach (var error in doEcResponse.Errors)
                    {
                        result.Errors.Add(error.LongMessage);
                    }
                }
                else
                {
                    _userService.Purchase(user, result.ProductName, payerId);
                }
                return(result);
            }
            return(new CheckoutPaymentResult {
                Errors = new List <string> {
                    status.ToString()
                }
            });
        }
    }
        /**
         * AUTO_GENERATED
         */
        public DoExpressCheckoutPaymentResponseType DoExpressCheckoutPayment(DoExpressCheckoutPaymentReq doExpressCheckoutPaymentReq, string apiUserName)
        {
            setStandardParams(doExpressCheckoutPaymentReq.DoExpressCheckoutPaymentRequest);
            string      response    = Call("DoExpressCheckoutPayment", doExpressCheckoutPaymentReq.ToXMLString(), apiUserName);
            XmlDocument xmlDocument = new XmlDocument();

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

            return(new DoExpressCheckoutPaymentResponseType(xmlNode));
        }
        /// <summary>
        /// Do paypal express checkout
        /// </summary>
        /// <param name="Token">Paypal express checkout token</param>
        /// <param name="PayerID">Paypal payer identifier</param>
        /// <param name="OrderTotal">Order total</param>
        /// <param name="processPaymentResult">Process payment result</param>
        public void DoExpressCheckout(string Token, string PayerID, decimal OrderTotal, ProcessPaymentResult processPaymentResult)
        {
            InitSettings();
            TransactMode transactionMode = GetCurrentTransactionMode();

            DoExpressCheckoutPaymentReq         req     = new DoExpressCheckoutPaymentReq();
            DoExpressCheckoutPaymentRequestType request = new DoExpressCheckoutPaymentRequestType();

            req.DoExpressCheckoutPaymentRequest = request;
            request.Version = this.APIVersion;
            DoExpressCheckoutPaymentRequestDetailsType details = new DoExpressCheckoutPaymentRequestDetailsType();

            request.DoExpressCheckoutPaymentRequestDetails = details;
            PaymentDetailsType paymentDetails = new PaymentDetailsType();

            details.PaymentDetails = paymentDetails;
            if (transactionMode == TransactMode.Authorize)
            {
                details.PaymentAction = PaymentActionCodeType.Authorization;
            }
            else
            {
                details.PaymentAction = PaymentActionCodeType.Sale;
            }
            details.Token                        = Token;
            details.PayerID                      = PayerID;
            paymentDetails.OrderTotal            = new BasicAmountType();
            paymentDetails.OrderTotal.Value      = OrderTotal.ToString("N", new CultureInfo("en-us"));
            paymentDetails.OrderTotal.currencyID = PaypalHelper.GetPaypalCurrency(CurrencyManager.PrimaryStoreCurrency);
            paymentDetails.ButtonSource          = "nopCommerceCart";

            DoExpressCheckoutPaymentResponseType response = service2.DoExpressCheckoutPayment(req);
            string error;

            if (!PaypalHelper.CheckSuccess(response, out error))
            {
                throw new NopException(error);
            }

            processPaymentResult.AuthorizationTransactionID     = response.DoExpressCheckoutPaymentResponseDetails.PaymentInfo.TransactionID;
            processPaymentResult.AuthorizationTransactionResult = response.Ack.ToString();
            //processPaymentResult.AuthorizationDate = response.Timestamp;
            //processPaymentResult.AuthorizationDate = DateTime.Now;

            if (transactionMode == TransactMode.Authorize)
            {
                processPaymentResult.PaymentStatus = PaymentStatusEnum.Authorized;
            }
            else
            {
                processPaymentResult.PaymentStatus = PaymentStatusEnum.Paid;
            }
        }
        public IPaymentResult CompletePayment(IInvoice invoice, IPayment payment, string token, string payerId)
        {
            var config = new Dictionary <string, string>
            {
                { "mode", "sandbox" },
                { "account1.apiUsername", _settings.ApiUsername },
                { "account1.apiPassword", _settings.ApiPassword },
                { "account1.apiSignature", _settings.ApiSignature }
            };
            var service = new PayPalAPIInterfaceServiceService(config);

            var getExpressCheckoutDetails = new GetExpressCheckoutDetailsReq
            {
                GetExpressCheckoutDetailsRequest = new GetExpressCheckoutDetailsRequestType(token)
            };
            var expressCheckoutDetailsResponse = service.GetExpressCheckoutDetails(getExpressCheckoutDetails);

            if (expressCheckoutDetailsResponse != null)
            {
                if (expressCheckoutDetailsResponse.Ack == AckCodeType.SUCCESS)
                {
                    // do express checkout
                    var doExpressCheckoutPayment = new DoExpressCheckoutPaymentReq();
                    var doExpressCheckoutPaymentRequestDetails = new DoExpressCheckoutPaymentRequestDetailsType
                    {
                        Token          = token,
                        PayerID        = payerId,
                        PaymentDetails = new List <PaymentDetailsType> {
                            GetPaymentDetails(invoice)
                        }
                    };

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

                    var doExpressCheckoutPaymentResponse = service.DoExpressCheckoutPayment(doExpressCheckoutPayment);

                    if (doExpressCheckoutPaymentResponse != null)
                    {
                        if (doExpressCheckoutPaymentResponse.Ack == AckCodeType.SUCCESS)
                        {
                            payment.Authorized = true;
                            payment.Collected  = true;
                            return(new PaymentResult(Attempt <IPayment> .Succeed(payment), invoice, true));
                        }
                    }
                }
            }

            return(new PaymentResult(Attempt <IPayment> .Succeed(payment), invoice, false));
        }
Esempio n. 9
0
        public static PayPalConfirmPaymentModel GetPayment(string token)
        {
            if (string.IsNullOrEmpty(token))
            {
                throw new ArgumentNullException("token");
            }

            Dictionary <string, string>      config       = PayPal.Api.ConfigManager.Instance.GetProperties();
            PayPalAPIInterfaceServiceService service      = new PayPalAPIInterfaceServiceService(config);
            GetExpressCheckoutDetailsReq     getECWrapper = new GetExpressCheckoutDetailsReq();

            getECWrapper.GetExpressCheckoutDetailsRequest = new GetExpressCheckoutDetailsRequestType(token);

            GetExpressCheckoutDetailsResponseType getECResponse = service.GetExpressCheckoutDetails(getECWrapper);

            DoExpressCheckoutPaymentRequestType        request        = new DoExpressCheckoutPaymentRequestType();
            DoExpressCheckoutPaymentRequestDetailsType requestDetails = new DoExpressCheckoutPaymentRequestDetailsType();

            request.DoExpressCheckoutPaymentRequestDetails = requestDetails;

            requestDetails.PaymentDetails = getECResponse.GetExpressCheckoutDetailsResponseDetails.PaymentDetails;
            requestDetails.Token          = getECResponse.GetExpressCheckoutDetailsResponseDetails.Token;
            requestDetails.PayerID        = getECResponse.GetExpressCheckoutDetailsResponseDetails.PayerInfo.PayerID;

            DoExpressCheckoutPaymentReq wrapper = new DoExpressCheckoutPaymentReq();

            wrapper.DoExpressCheckoutPaymentRequest = request;
            DoExpressCheckoutPaymentResponseType doECResponse = service.DoExpressCheckoutPayment(wrapper);

            if (doECResponse.Ack == AckCodeType.SUCCESS)
            {
                var paymentInfo = doECResponse.DoExpressCheckoutPaymentResponseDetails.PaymentInfo.First();

                var confirmModel = new PayPalConfirmPaymentModel
                {
                    Success          = true,
                    PaymentRequestID = paymentInfo.PaymentRequestID,
                    OrderTotal       = decimal.Parse(paymentInfo.GrossAmount.value),
                    OrderDate        = string.IsNullOrEmpty(paymentInfo.PaymentDate)
                                                ? DateTimeOffset.Parse(paymentInfo.PaymentDate)
                                                : (DateTimeOffset?)null
                };
                return(confirmModel);
            }
            return(new PayPalConfirmPaymentModel
            {
                Success = false,
                ErrorMessage = string.Join(". ", doECResponse.Errors.Select(x => x.LongMessage).ToList())
            });
        }
Esempio n. 10
0
        protected void Submit_Click(object sender, EventArgs e)
        {
            // Configuration map containing signature credentials and other required configuration.
            // For a full list of configuration parameters refer in wiki page
            // [https://github.com/paypal/sdk-core-dotnet/wiki/SDK-Configuration-Parameters]
            Dictionary <string, string> configurationMap = Configuration.GetAcctAndConfig();

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

            GetExpressCheckoutDetailsReq getECWrapper = new GetExpressCheckoutDetailsReq();

            // (Required) A timestamped token, the value of which was returned by SetExpressCheckout response.
            // Character length and limitations: 20 single-byte characters
            getECWrapper.GetExpressCheckoutDetailsRequest = new GetExpressCheckoutDetailsRequestType(token.Value);
            // # API call
            // Invoke the GetExpressCheckoutDetails method in service wrapper object
            GetExpressCheckoutDetailsResponseType getECResponse = service.GetExpressCheckoutDetails(getECWrapper);

            // Create request object
            DoExpressCheckoutPaymentRequestType        request        = new DoExpressCheckoutPaymentRequestType();
            DoExpressCheckoutPaymentRequestDetailsType requestDetails = new DoExpressCheckoutPaymentRequestDetailsType();

            request.DoExpressCheckoutPaymentRequestDetails = requestDetails;

            requestDetails.PaymentDetails = getECResponse.GetExpressCheckoutDetailsResponseDetails.PaymentDetails;
            // (Required) The timestamped token value that was returned in the SetExpressCheckout response and passed in the GetExpressCheckoutDetails request.
            requestDetails.Token = token.Value;
            // (Required) Unique PayPal buyer account identification number as returned in the GetExpressCheckoutDetails response
            requestDetails.PayerID = payerId.Value;
            // (Required) How you want to obtain payment. It is one of the following values:
            // * Authorization – This payment is a basic authorization subject to settlement with PayPal Authorization and Capture.
            // * Order – This payment is an order authorization subject to settlement with PayPal Authorization and Capture.
            // * Sale – This is a final sale for which you are requesting payment.
            // Note: You cannot set this value to Sale in the SetExpressCheckout request and then change this value to Authorization in the DoExpressCheckoutPayment request.
            requestDetails.PaymentAction = (PaymentActionCodeType)
                                           Enum.Parse(typeof(PaymentActionCodeType), paymentAction.SelectedValue);

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

            wrapper.DoExpressCheckoutPaymentRequest = request;
            // # API call
            // Invoke the DoExpressCheckoutPayment method in service wrapper object
            DoExpressCheckoutPaymentResponseType doECResponse = service.DoExpressCheckoutPayment(wrapper);

            // Check for API return status
            setKeyResponseObjects(service, doECResponse);
        }
        /// <summary>
        /// The do express checkout payment.
        /// </summary>
        /// <param name="invoice">
        /// The invoice.
        /// </param>
        /// <param name="payment">
        /// The payment.
        /// </param>
        /// <param name="token">
        /// The token.
        /// </param>
        /// <param name="payerId">
        /// The payer id.
        /// </param>
        /// <param name="record">
        /// The record of the transaction.
        /// </param>
        /// <returns>
        /// The <see cref="PayPalExpressTransactionRecord"/>.
        /// </returns>
        internal PayPalExpressTransactionRecord DoExpressCheckoutPayment(IInvoice invoice, IPayment payment, string token, string payerId, PayPalExpressTransactionRecord record)
        {
            var factory = new PayPalPaymentDetailsTypeFactory();

            ExpressCheckoutResponse result = null;

            try
            {
                // do express checkout
                var request = new DoExpressCheckoutPaymentRequestType(
                    new DoExpressCheckoutPaymentRequestDetailsType
                {
                    Token          = token,
                    PayerID        = payerId,
                    PaymentDetails =
                        new List <PaymentDetailsType>
                    {
                        factory.Build(invoice, PaymentActionCodeType.ORDER)
                    }
                });

                var doExpressCheckoutPayment = new DoExpressCheckoutPaymentReq
                {
                    DoExpressCheckoutPaymentRequest = request
                };

                var service  = GetPayPalService();
                var response = service.DoExpressCheckoutPayment(doExpressCheckoutPayment);
                result = _responseFactory.Build(response, token);

                var transactionId = response.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].TransactionID;
                var currency      = response.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].GrossAmount.currencyID;
                var amount        = response.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].GrossAmount.value;

                record.Data.CheckoutPaymentTransactionId = transactionId;
                record.Data.CurrencyId       = currency.ToString();
                record.Data.AuthorizedAmount = amount;
            }
            catch (Exception ex)
            {
                result = _responseFactory.Build(ex);
            }

            record.DoExpressCheckoutPayment = result;
            record.Success = result.Success();

            return(record);
        }
Esempio n. 12
0
        public DoExpressCheckoutPaymentResponseType DoExpressCheckoutPayment(ProcessPaymentRequest processPaymentRequest)
        {
            var result   = new DoExpressCheckoutPaymentResponseType();
            var settings = CommonServices.Settings.LoadSetting <PayPalExpressPaymentSettings>(processPaymentRequest.StoreId);

            // populate payment details
            var paymentDetails = new PaymentDetailsType
            {
                OrderTotal = new BasicAmountType
                {
                    Value      = Math.Round(processPaymentRequest.OrderTotal, 2).ToString("N", new CultureInfo("en-us")),
                    currencyID = PayPalHelper.GetPaypalCurrency(_currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId))
                },
                Custom       = processPaymentRequest.OrderGuid.ToString(),
                ButtonSource = SmartStoreVersion.CurrentFullVersion
            };

            // build the request
            var req = new DoExpressCheckoutPaymentReq
            {
                DoExpressCheckoutPaymentRequest = new DoExpressCheckoutPaymentRequestType
                {
                    Version = PayPalHelper.GetApiVersion(),
                    DoExpressCheckoutPaymentRequestDetails = new DoExpressCheckoutPaymentRequestDetailsType
                    {
                        Token                  = processPaymentRequest.PaypalToken,
                        PayerID                = processPaymentRequest.PaypalPayerId,
                        PaymentAction          = PayPalHelper.GetPaymentAction(settings),
                        PaymentActionSpecified = true,
                        PaymentDetails         = new PaymentDetailsType[]
                        {
                            paymentDetails
                        }
                    }
                }
            };

            //execute request
            using (var service = new PayPalAPIAASoapBinding())
            {
                service.Url = PayPalHelper.GetPaypalServiceUrl(settings);
                service.RequesterCredentials = PayPalHelper.GetPaypalApiCredentials(settings);
                result = service.DoExpressCheckoutPayment(req);
            }
            return(result);
        }
Esempio n. 13
0
        protected string ProcessPaypalTransaction(string token, string payerId, decimal total)
        {
            var client      = new PayPalAPIAAInterfaceClient();
            var credentials = GetPaypalCredentials();
            var request     = new DoExpressCheckoutPaymentReq
            {
                DoExpressCheckoutPaymentRequest = new DoExpressCheckoutPaymentRequestType
                {
                    Version = "89.0",
                    DoExpressCheckoutPaymentRequestDetails = new DoExpressCheckoutPaymentRequestDetailsType
                    {
                        Token          = token,
                        PayerID        = payerId,
                        PaymentAction  = PaymentActionCodeType.Sale,
                        PaymentDetails = new PaymentDetailsType[]
                        {
                            new PaymentDetailsType
                            {
                                OrderTotal = new BasicAmountType {
                                    Value = total.ToString(), currencyID = CurrencyCodeType.USD
                                }
                            }
                        }
                    }
                }
            };
            var response = client.DoExpressCheckoutPayment(ref credentials, request);

            if (response.Ack == AckCodeType.Failure)
            {
                throw new InvalidOperationException("Paypal returned the following error: " + response.Errors.FirstOrDefault().LongMessage);
            }

            if (response.DoExpressCheckoutPaymentResponseDetails.PaymentInfo.Count() == 0)
            {
                throw new InvalidOperationException("No payment transaction returned from paypal");
            }

            if (string.IsNullOrWhiteSpace(response.DoExpressCheckoutPaymentResponseDetails.PaymentInfo.First().TransactionID))
            {
                throw new InvalidOperationException("No payment transaction ID returned");
            }

            return(response.DoExpressCheckoutPaymentResponseDetails.PaymentInfo.First().TransactionID);
        }
Esempio n. 14
0
        public DoExpressCheckoutPaymentResponseType DoExpressCheckoutPayment(ProcessPaymentRequest processPaymentRequest)
        {
            var result   = new DoExpressCheckoutPaymentResponseType();
            var store    = Services.StoreService.GetStoreById(processPaymentRequest.StoreId);
            var settings = Services.Settings.LoadSetting <PayPalExpressPaymentSettings>(processPaymentRequest.StoreId);

            // populate payment details
            var paymentDetails = new PaymentDetailsType
            {
                OrderTotal = new BasicAmountType
                {
                    Value      = Math.Round(processPaymentRequest.OrderTotal, 2).ToString("N", new CultureInfo("en-us")),
                    currencyID = GetApiCurrency(store.PrimaryStoreCurrency)
                },
                Custom       = processPaymentRequest.OrderGuid.ToString(),
                ButtonSource = SmartStoreVersion.CurrentFullVersion
            };

            // build the request
            var req = new DoExpressCheckoutPaymentReq
            {
                DoExpressCheckoutPaymentRequest = new DoExpressCheckoutPaymentRequestType
                {
                    Version = ApiVersion,
                    DoExpressCheckoutPaymentRequestDetails = new DoExpressCheckoutPaymentRequestDetailsType
                    {
                        Token                  = processPaymentRequest.PaypalToken,
                        PayerID                = processPaymentRequest.PaypalPayerId,
                        PaymentAction          = GetPaymentAction(settings),
                        PaymentActionSpecified = true,
                        PaymentDetails         = new PaymentDetailsType[]
                        {
                            paymentDetails
                        }
                    }
                }
            };

            //execute request
            using (var service = GetApiAaService(settings))
            {
                result = service.DoExpressCheckoutPayment(req);
            }
            return(result);
        }
Esempio n. 15
0
        public static DoExpressCheckoutPaymentReq GetDoExpressCheckoutPaymentReq(GetExpressCheckoutDetailsResponseType response)
        {
            DoExpressCheckoutPaymentReq payReq = new DoExpressCheckoutPaymentReq()
            {
                DoExpressCheckoutPaymentRequest = new DoExpressCheckoutPaymentRequestType()
                {
                    Version = ConfigurationManager.AppSettings["PayPalAPIVersion"],
                    DoExpressCheckoutPaymentRequestDetails = new DoExpressCheckoutPaymentRequestDetailsType()
                    {
                        Token          = response.GetExpressCheckoutDetailsResponseDetails.Token,
                        PaymentAction  = PaymentActionCodeType.Sale,
                        PayerID        = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.PayerID,
                        PaymentDetails = response.GetExpressCheckoutDetailsResponseDetails.PaymentDetails
                    }
                }
            };

            return(payReq);
        }
Esempio n. 16
0
        public DoExpressCheckoutPaymentResponseType DoExpressCheckout(HttpResponseBase response, string token)
        {
            var getCheckoutRequest = new GetExpressCheckoutDetailsRequestType();

            getCheckoutRequest.Token = token;
            var getCheckOutInfo = new GetExpressCheckoutDetailsReq();

            getCheckOutInfo.GetExpressCheckoutDetailsRequest = getCheckoutRequest;
            var service     = new PayPalAPIInterfaceServiceService();
            var getResponse = service.GetExpressCheckoutDetails(getCheckOutInfo);
            var doRequest   = new DoExpressCheckoutPaymentRequestType();
            var requestInfo = new DoExpressCheckoutPaymentRequestDetailsType();

            doRequest.DoExpressCheckoutPaymentRequestDetails = requestInfo;
            requestInfo.PaymentDetails = getResponse.GetExpressCheckoutDetailsResponseDetails.PaymentDetails;
            requestInfo.Token          = token;
            requestInfo.PayerID        = getResponse.GetExpressCheckoutDetailsResponseDetails.PayerInfo.PayerID;
            requestInfo.PaymentAction  = PaymentActionCodeType.SALE;
            var wrapper = new DoExpressCheckoutPaymentReq();

            wrapper.DoExpressCheckoutPaymentRequest = doRequest;
            return(service.DoExpressCheckoutPayment(wrapper));
        }
Esempio n. 17
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"));
        }
        // # DoExpressCheckoutPayment API Operation
        // The DoExpressCheckoutPayment API operation completes an Express Checkout transaction.
        // If you set up a billing agreement in your SetExpressCheckout API call,
        // the billing agreement is created when you call the DoExpressCheckoutPayment API operation.
        public DoExpressCheckoutPaymentResponseType DoExpressCheckoutPaymentAPIOperation()
        {
            // Create the DoExpressCheckoutPaymentResponseType object
            DoExpressCheckoutPaymentResponseType responseDoExpressCheckoutPaymentResponseType =
                new DoExpressCheckoutPaymentResponseType();

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

                DoExpressCheckoutPaymentRequestDetailsType doExpressCheckoutPaymentRequestDetails =
                    new DoExpressCheckoutPaymentRequestDetailsType();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                return(responseDoExpressCheckoutPaymentResponseType);
            }
            // # Exception log
            catch (System.Exception ex)
            {
                // Log the exception message
                Console.WriteLine("Error Message : " + ex.Message);
            }
            return(responseDoExpressCheckoutPaymentResponseType);
        }
Esempio n. 19
0
        /// <summary>
        /// Do paypal express checkout
        /// </summary>
        /// <param name="paymentInfo">Payment info required for an order processing</param>
        /// <param name="orderGuid">Unique order identifier</param>
        /// <param name="processPaymentResult">Process payment result</param>
        public void DoExpressCheckout(PaymentInfo paymentInfo,
                                      Guid orderGuid, ProcessPaymentResult processPaymentResult)
        {
            InitSettings();
            TransactMode transactionMode = GetCurrentTransactionMode();

            DoExpressCheckoutPaymentReq         req     = new DoExpressCheckoutPaymentReq();
            DoExpressCheckoutPaymentRequestType request = new DoExpressCheckoutPaymentRequestType();

            req.DoExpressCheckoutPaymentRequest = request;
            request.Version = this.APIVersion;
            DoExpressCheckoutPaymentRequestDetailsType details = new DoExpressCheckoutPaymentRequestDetailsType();

            request.DoExpressCheckoutPaymentRequestDetails = details;
            if (transactionMode == TransactMode.Authorize)
            {
                details.PaymentAction = PaymentActionCodeType.Authorization;
            }
            else
            {
                details.PaymentAction = PaymentActionCodeType.Sale;
            }
            details.PaymentActionSpecified = true;
            details.Token   = paymentInfo.PaypalToken;
            details.PayerID = paymentInfo.PaypalPayerId;

            details.PaymentDetails = new PaymentDetailsType[1];
            PaymentDetailsType paymentDetails1 = new PaymentDetailsType();

            details.PaymentDetails[0]             = paymentDetails1;
            paymentDetails1.OrderTotal            = new BasicAmountType();
            paymentDetails1.OrderTotal.Value      = paymentInfo.OrderTotal.ToString("N", new CultureInfo("en-us"));
            paymentDetails1.OrderTotal.currencyID = PaypalHelper.GetPaypalCurrency(IoC.Resolve <ICurrencyService>().PrimaryStoreCurrency);
            paymentDetails1.Custom       = orderGuid.ToString();
            paymentDetails1.ButtonSource = "nopCommerceCart";

            DoExpressCheckoutPaymentResponseType response = service2.DoExpressCheckoutPayment(req);
            string error;

            if (!PaypalHelper.CheckSuccess(response, out error))
            {
                throw new NopException(error);
            }

            if (response.DoExpressCheckoutPaymentResponseDetails.PaymentInfo != null &&
                response.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0] != null)
            {
                processPaymentResult.AuthorizationTransactionId     = response.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].TransactionID;
                processPaymentResult.AuthorizationTransactionResult = response.Ack.ToString();

                if (transactionMode == TransactMode.Authorize)
                {
                    processPaymentResult.PaymentStatus = PaymentStatusEnum.Authorized;
                }
                else
                {
                    processPaymentResult.PaymentStatus = PaymentStatusEnum.Paid;
                }
            }
            else
            {
                throw new NopException("response.DoExpressCheckoutPaymentResponseDetails.PaymentInfo is null");
            }
        }
Esempio n. 20
0
        public IPaymentResult AuthorizePayment(IInvoice invoice, IPayment payment, string token, string payerId)
        {
            var service = GetPayPalService();

            var getExpressCheckoutReq = new GetExpressCheckoutDetailsReq()
            {
                GetExpressCheckoutDetailsRequest = new GetExpressCheckoutDetailsRequestType(token)
            };

            GetExpressCheckoutDetailsResponseType expressCheckoutDetailsResponse;

            try {
                expressCheckoutDetailsResponse = service.GetExpressCheckoutDetails(getExpressCheckoutReq);
                if (expressCheckoutDetailsResponse.Ack != AckCodeType.SUCCESS && expressCheckoutDetailsResponse.Ack != AckCodeType.SUCCESSWITHWARNING)
                {
                    return(new PaymentResult(Attempt <IPayment> .Fail(payment, CreateErrorResult(expressCheckoutDetailsResponse.Errors)), invoice, false));
                }
            } catch (Exception ex) {
                return(new PaymentResult(Attempt <IPayment> .Fail(payment, ex), invoice, false));
            }

            // check if already do
            if (payment.ExtendedData.GetValue(Constants.ExtendedDataKeys.PaymentAuthorized) != "true")
            {
                // do express checkout
                var doExpressCheckoutPaymentRequest = new DoExpressCheckoutPaymentRequestType(new DoExpressCheckoutPaymentRequestDetailsType
                {
                    Token          = token,
                    PayerID        = payerId,
                    PaymentDetails = new List <PaymentDetailsType> {
                        CreatePayPalPaymentDetails(invoice)
                    }
                });
                var doExpressCheckoutPayment = new DoExpressCheckoutPaymentReq()
                {
                    DoExpressCheckoutPaymentRequest = doExpressCheckoutPaymentRequest
                };

                DoExpressCheckoutPaymentResponseType doExpressCheckoutPaymentResponse;
                try {
                    doExpressCheckoutPaymentResponse = service.DoExpressCheckoutPayment(doExpressCheckoutPayment);
                    if (doExpressCheckoutPaymentResponse.Ack != AckCodeType.SUCCESS && doExpressCheckoutPaymentResponse.Ack != AckCodeType.SUCCESSWITHWARNING)
                    {
                        return(new PaymentResult(Attempt <IPayment> .Fail(payment, CreateErrorResult(doExpressCheckoutPaymentResponse.Errors)), invoice, false));
                    }
                } catch (Exception ex) {
                    return(new PaymentResult(Attempt <IPayment> .Fail(payment, ex), invoice, false));
                }

                var transactionId = doExpressCheckoutPaymentResponse.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].TransactionID;
                var currency      = doExpressCheckoutPaymentResponse.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].GrossAmount.currencyID;
                var amount        = doExpressCheckoutPaymentResponse.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].GrossAmount.value;

                // do authorization
                var doAuthorizationResponse = service.DoAuthorization(new DoAuthorizationReq
                {
                    DoAuthorizationRequest = new DoAuthorizationRequestType
                    {
                        TransactionID = transactionId,
                        Amount        = new BasicAmountType(currency, amount)
                    }
                });
                if (doAuthorizationResponse.Ack != AckCodeType.SUCCESS && doAuthorizationResponse.Ack != AckCodeType.SUCCESSWITHWARNING)
                {
                    return(new PaymentResult(Attempt <IPayment> .Fail(payment, CreateErrorResult(doAuthorizationResponse.Errors)), invoice, false));
                }

                payment.ExtendedData.SetValue(Constants.ExtendedDataKeys.AuthorizationId, doAuthorizationResponse.TransactionID);
                payment.ExtendedData.SetValue(Constants.ExtendedDataKeys.AmountCurrencyId, currency.ToString());
                payment.ExtendedData.SetValue(Constants.ExtendedDataKeys.PaymentAuthorized, "true");
            }

            payment.Authorized = true;

            return(new PaymentResult(Attempt <IPayment> .Succeed(payment), invoice, true));
        }
        public PostProcessPaymentResponse PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
        {
            var paymentResponse = new PostProcessPaymentResponse();
            var req             = new DoExpressCheckoutPaymentReq();
            var request         = new DoExpressCheckoutPaymentRequestType();
            var payment         = postProcessPaymentRequest.Payment;
            var order           = postProcessPaymentRequest.Order;

            req.DoExpressCheckoutPaymentRequest = request;
            request.Version = Settings.Version;
            var details = new DoExpressCheckoutPaymentRequestDetailsType();

            request.DoExpressCheckoutPaymentRequestDetails = details;
            details.PaymentAction = PaymentActionCodeType.Authorization;

            details.PaymentActionSpecified = true;
            details.Token   = postProcessPaymentRequest.Token;
            details.PayerID = postProcessPaymentRequest.PayerId;
            var payer = GetPayerInfo(postProcessPaymentRequest.Token, postProcessPaymentRequest.PayerId);

            var paymentDetail = new PaymentDetailsType();

            paymentDetail.OrderTotal       = new BasicAmountType();
            paymentDetail.OrderTotal.Value = order.GrandTotal.Raw.WithTax.ToString("N", new CultureInfo("en-us"));
            var currencyCode = (CurrencyCodeType)Utils.GetEnumValueByName(typeof(CurrencyCodeType), order.CurrencyCode);

            paymentDetail.OrderTotal.currencyID  = currencyCode;
            paymentDetail.ButtonSource           = "";
            paymentDetail.PaymentAction          = PaymentActionCodeType.Authorization;
            paymentDetail.PaymentActionSpecified = true;

            PaymentDetailsType[] paymentDetails = { paymentDetail };
            details.PaymentDetails = paymentDetails;
            //  System.Net.ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            var credentials = PaypalSecurityHeader();
            DoExpressCheckoutPaymentResponseType response = _paypalService2.DoExpressCheckoutPayment(ref credentials, req);

            if (response.Ack == AckCodeType.Success)
            {
                payment.PaymentMethod  = "ExpressCheckout";
                payment.CvcResult      = payer.AccountVerifyCode;
                payment.AvsResult      = payer.AddressVerifyCode;
                payment.Secure3DResult = "";
                payment.CardHolderName = payer.Email;
                payment.IssuerCountry  = payer.CountryCode;
                payment.CardNo         = payer.PayerId;
                payment.IsVerify       = payer.IsVerify;
                payment.IsValidAddress = payer.IsValidAddress;
                payment.Info1          = "";
                if (!string.IsNullOrEmpty(payer.Address1))
                {
                    payment.Info1 = payer.Address1 + ", ";
                }
                if (!string.IsNullOrEmpty(payer.Address2))
                {
                    payment.Info1 = payment.Info1 + payer.Address2 + ", ";
                }
                if (!string.IsNullOrEmpty(payer.City))
                {
                    payment.Info1 = payment.Info1 + payer.City + ", ";
                }
                if (!string.IsNullOrEmpty(payer.State))
                {
                    payment.Info1 = payment.Info1 + payer.State + ", ";
                }
                if (!string.IsNullOrEmpty(payer.PostCode))
                {
                    payment.Info1 = payment.Info1 + payer.PostCode + ", ";
                }
                if (!string.IsNullOrEmpty(payer.CountryCode))
                {
                    payment.Info1 = payment.Info1 + payer.CountryCode;
                }
                var billAddress = new AddressModel
                {
                    FirstName   = payer.FirstName,
                    LastName    = payer.LastName,
                    Address1    = payer.Address1,
                    Address2    = payer.Address2,
                    City        = payer.City,
                    State       = payer.State,
                    PostCode    = payer.PostCode,
                    Country     = payer.Country,
                    CountryCode = payer.CountryCode,
                    PhoneNo     = payer.CountryCode
                };
                order.BillingAddress             = billAddress;//Mapper.Map<PayerInfo, Address>(payer);
                paymentResponse.Payment          = payment;
                paymentResponse.Order            = order;
                paymentResponse.Payment.AuthCode = response.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].TransactionID;
                paymentResponse.Payment.Status   = PaymentStatus.Authorized.GetHashCode();
            }
            else
            {
                paymentResponse.Order   = order;
                payment.Status          = PaymentStatus.Declined.GetHashCode();
                payment.IsValid         = false;
                paymentResponse.Payment = payment;
                paymentResponse.AddError("decline");
                foreach (var er in response.Errors)
                {
                    paymentResponse.AddError(er.ErrorCode + " : " + er.ShortMessage);
                }
            }
            //if (Settings.IsImmediateCapture)
            //{
            //    var capturePaymentRequest = new CapturePaymentRequest();
            //    var pRes = new CapturePaymentResult();
            //    capturePaymentRequest.CurrencyCode = order.CurrencyCode;
            //    capturePaymentRequest.CaptureTransactionId = Convert.ToString(paymentResponse.Payment.AuthCode);
            //    capturePaymentRequest.OrderTotal = paymentResponse.Payment.OrderAmount;

            //    pRes = Capture(capturePaymentRequest);
            //    if (pRes.Success && string.IsNullOrEmpty(pRes.CaptureTransactionCode) == false)
            //    {
            //        paymentResponse.Payment.AuthCode = pRes.CaptureTransactionCode;
            //        paymentResponse.Payment.Status = PaymentStatus.Paid.GetHashCode();
            //        paymentResponse.Payment.PaidAmount = capturePaymentRequest.OrderTotal;
            //        paymentResponse.Order.PaymentStatus = PaymentStatus.Paid;
            //    }
            //    else
            //    {
            //        paymentResponse.Payment.PSPResponseMessage = pRes.CaptureTransactionResult;
            //    }

            //}
            return(paymentResponse);
        }
Esempio n. 22
0
 /// <remarks/>
 public void DoExpressCheckoutPaymentAsync(DoExpressCheckoutPaymentReq DoExpressCheckoutPaymentReq) {
     this.DoExpressCheckoutPaymentAsync(DoExpressCheckoutPaymentReq, null);
 }
Esempio n. 23
0
 /// <remarks/>
 public void DoExpressCheckoutPaymentAsync(DoExpressCheckoutPaymentReq DoExpressCheckoutPaymentReq, object userState) {
     if ((this.DoExpressCheckoutPaymentOperationCompleted == null)) {
         this.DoExpressCheckoutPaymentOperationCompleted = new System.Threading.SendOrPostCallback(this.OnDoExpressCheckoutPaymentOperationCompleted);
     }
     this.InvokeAsync("DoExpressCheckoutPayment", new object[] {
                 DoExpressCheckoutPaymentReq}, this.DoExpressCheckoutPaymentOperationCompleted, userState);
 }
Esempio n. 24
0
        /// <summary>
        /// Charges the specified payment info.
        /// </summary>
        /// <param name="financialGateway">The financial gateway.</param>
        /// <param name="paymentInfo">The payment info.</param>
        /// <param name="errorMessage">The error message.</param>
        /// <returns></returns>
        public override FinancialTransaction Charge(FinancialGateway financialGateway, PaymentInfo paymentInfo, out string errorMessage)
        {
            errorMessage = string.Empty;

            if (!(paymentInfo is PayPalExpress.PayPalPaymentInfo))
            {
                errorMessage = "PaymentInfo object must be of type PayPalPaymentInfo in order to charge a PayPal Express transaction.";
                return(null);
            }
            PayPalPaymentInfo payPalPaymentInfo = (PayPalPaymentInfo)paymentInfo;

            // Create the DoExpressCheckoutPaymentResponseType object
            DoExpressCheckoutPaymentResponseType responseDoExpressCheckoutPaymentResponseType = new DoExpressCheckoutPaymentResponseType();

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

                DoExpressCheckoutPaymentRequestDetailsType doExpressCheckoutPaymentRequestDetails = new DoExpressCheckoutPaymentRequestDetailsType();

                // The timestamped token value that was returned in the
                // `SetExpressCheckout` response and passed in the
                // `GetExpressCheckoutDetails` request.
                doExpressCheckoutPaymentRequestDetails.Token = payPalPaymentInfo.Token;

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

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

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

                BasicAmountType orderTotal = new BasicAmountType(CurrencyCodeType.USD, paymentInfo.Amount.ToString());
                paymentDetails.OrderTotal = orderTotal;

                // We are actually capturing this payment now.
                paymentDetails.PaymentAction = PaymentActionCodeType.SALE;

                // Unique identifier for the merchant. For parallel payments, this field
                // is required and must contain the Payer Id or the email address of the
                // merchant.
                String            apiUsername   = Encryption.DecryptString(financialGateway.GetAttributeValue("PayPalAPIUsername"));
                SellerDetailsType sellerDetails = new SellerDetailsType();
                sellerDetails.PayPalAccountID = apiUsername;

                paymentDetailsList.Add(paymentDetails);
                doExpressCheckoutPaymentRequestDetails.PaymentDetails = paymentDetailsList;

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

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

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

                if (responseDoExpressCheckoutPaymentResponseType != null)
                {
                    // # Success values
                    if (responseDoExpressCheckoutPaymentResponseType.Ack.ToString().Trim().ToUpper().Equals("SUCCESS"))
                    {
                        // Transaction identification number of the transaction that was
                        // created.
                        // This field is only returned after a successful transaction
                        // for DoExpressCheckout has occurred.
                        if (responseDoExpressCheckoutPaymentResponseType.DoExpressCheckoutPaymentResponseDetails.PaymentInfo != null)
                        {
                            IEnumerator <PaymentInfoType> paymentInfoIterator = responseDoExpressCheckoutPaymentResponseType.DoExpressCheckoutPaymentResponseDetails.PaymentInfo.GetEnumerator();
                            while (paymentInfoIterator.MoveNext())
                            {
                                PaymentInfoType ppPaymentInfo = paymentInfoIterator.Current;

                                var transaction = new FinancialTransaction();
                                transaction.TransactionCode = ppPaymentInfo.TransactionID;
                                return(transaction);
                            }
                        }
                    }
                    // # Error Values
                    else
                    {
                        List <ErrorType> errorMessages = responseDoExpressCheckoutPaymentResponseType.Errors;
                        foreach (ErrorType error in errorMessages)
                        {
                            errorMessage += "API Error Message : " + error.LongMessage + "\n";
                        }
                    }
                }
            }
            // # Exception log
            catch (System.Exception ex)
            {
                errorMessage += "Error Message : " + ex.Message;
            }

            return(null);
        }
Esempio n. 25
0
 public DoExpressCheckoutPaymentResponseType DoExpressCheckoutPayment(DoExpressCheckoutPaymentReq DoExpressCheckoutPaymentReq)
 {
     return(DoExpressCheckoutPayment(DoExpressCheckoutPaymentReq, null));
 }
        /// <summary>
        /// The do express checkout payment.
        /// </summary>
        /// <param name="invoice">
        /// The invoice.
        /// </param>
        /// <param name="payment">
        /// The payment.
        /// </param>
        /// <param name="token">
        /// The token.
        /// </param>
        /// <param name="payerId">
        /// The payer id.
        /// </param>
        /// <param name="record">
        /// The record of the transaction.
        /// </param>
        /// <returns>
        /// The <see cref="PayPalExpressTransactionRecord"/>.
        /// </returns>
        internal PayPalExpressTransactionRecord DoExpressCheckoutPayment(IInvoice invoice, IPayment payment, string token, string payerId, PayPalExpressTransactionRecord record)
        {
            var factory = new PayPalPaymentDetailsTypeFactory();

            ExpressCheckoutResponse result = null;
            try
            {
                // do express checkout
                var request = new DoExpressCheckoutPaymentRequestType(
                        new DoExpressCheckoutPaymentRequestDetailsType
                        {
                            Token = token,
                            PayerID = payerId,
                            PaymentDetails =
                                    new List<PaymentDetailsType>
                                        {
                                            factory.Build(invoice, PaymentActionCodeType.ORDER)
                                        }
                        });

                var doExpressCheckoutPayment = new DoExpressCheckoutPaymentReq
                {
                    DoExpressCheckoutPaymentRequest = request
                };

                var service = GetPayPalService();
                var response = service.DoExpressCheckoutPayment(doExpressCheckoutPayment);
                result = _responseFactory.Build(response, token);

                var transactionId = response.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].TransactionID;
                var currency = response.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].GrossAmount.currencyID;
                var amount = response.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].GrossAmount.value;

                record.Data.CheckoutPaymentTransactionId = transactionId;
                record.Data.CurrencyId = currency.ToString();
                record.Data.AuthorizedAmount = amount;

            }
            catch (Exception ex)
            {
                result = _responseFactory.Build(ex);
            }

            record.DoExpressCheckoutPayment = result;
            record.Success = result.Success();

            return record;
        }
Esempio n. 27
0
        /// <summary>
        /// Processes the payment. Can be used for both positive and negative transactions.
        /// </summary>
        /// <param name="payment">The payment.</param>
        /// <param name="message">The message.</param>
        /// <returns></returns>
        public override bool ProcessPayment(Payment payment, ref string message)
        {
            try
            {
                payment.Status = PaymentStatus.Processing.ToString();

                //ContractId - used as paypal PayerID
                var payerId = payment.ContractId;
                //ValidationCode - used as paypal token
                var token = payment.AuthorizationCode;

                if (string.IsNullOrEmpty(payerId) || string.IsNullOrEmpty(token))
                {
                    return(false);
                }

                // Create the PayPalAPIInterfaceServiceService service object to make the API call
                var service = new PayPalAPIInterfaceServiceService((Dictionary <string, string>)Settings);

                var getECWrapper = new GetExpressCheckoutDetailsReq();
                getECWrapper.GetExpressCheckoutDetailsRequest = new GetExpressCheckoutDetailsRequestType(token);
                var getECResponse = service.GetExpressCheckoutDetails(getECWrapper);

                var request        = new DoExpressCheckoutPaymentRequestType();
                var requestDetails = new DoExpressCheckoutPaymentRequestDetailsType();
                request.DoExpressCheckoutPaymentRequestDetails = requestDetails;

                requestDetails.PaymentDetails = getECResponse.GetExpressCheckoutDetailsResponseDetails.PaymentDetails;
                requestDetails.Token          = token;
                requestDetails.PayerID        = payerId;
                requestDetails.PaymentAction  = PaymentActionCodeType.SALE;

                // Invoke the API
                var wrapper = new DoExpressCheckoutPaymentReq();
                wrapper.DoExpressCheckoutPaymentRequest = request;

                var doECResponse = service.DoExpressCheckoutPayment(wrapper);

                if (doECResponse.Ack.Equals(AckCodeType.FAILURE) || (doECResponse.Errors != null && doECResponse.Errors.Count > 0))
                {
                    return(false);
                }
                else
                {
                    switch (doECResponse.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].PaymentStatus)
                    {
                    case PaymentStatusCodeType.COMPLETED:
                        payment.Status = PaymentStatus.Completed.ToString();
                        break;

                    case PaymentStatusCodeType.INPROGRESS:
                        payment.Status = PaymentStatus.Processing.ToString();
                        break;

                    case PaymentStatusCodeType.DENIED:
                        payment.Status = PaymentStatus.Denied.ToString();
                        break;

                    case PaymentStatusCodeType.FAILED:
                        payment.Status = PaymentStatus.Failed.ToString();
                        break;

                    default:
                        payment.Status =
                            doECResponse.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].PaymentStatus
                            .ToString();
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                message = ex.Message;
                return(false);
            }


            return(true);
        }
Esempio n. 28
0
        //GET : PayPal/PaymentSuccess
        public async Task <ActionResult> PaymentSuccess(Guid invoiceId)
        {
            GetExpressCheckoutDetailsRequestType request = new GetExpressCheckoutDetailsRequestType();

            request.Version = "104.0";
            request.Token   = Request["token"];
            GetExpressCheckoutDetailsReq wrapper = new GetExpressCheckoutDetailsReq();

            wrapper.GetExpressCheckoutDetailsRequest = request;

            //define sdk configuration
            Dictionary <string, string> sdkConfig = new Dictionary <string, string>();

            sdkConfig.Add("mode", ConfigurationManager.AppSettings["paypal.mode"]);
            sdkConfig.Add("account1.apiUsername", ConfigurationManager.AppSettings["paypal.apiUsername"]);
            sdkConfig.Add("account1.apiPassword", ConfigurationManager.AppSettings["paypal.apiPassword"]);
            sdkConfig.Add("account1.apiSignature", ConfigurationManager.AppSettings["paypal.apiSignature"]);
//            sdkConfig.Add("acct1.UserName", ConfigurationManager.AppSettings["paypal.apiUsername"]);
//            sdkConfig.Add("acct1.Password", ConfigurationManager.AppSettings["paypal.apiPassword"]);
//            sdkConfig.Add("acct1.Signature", ConfigurationManager.AppSettings["paypal.apiSignature"]);

            PayPalAPIInterfaceServiceService      s          = new PayPalAPIInterfaceServiceService(sdkConfig);
            GetExpressCheckoutDetailsResponseType ecResponse = s.GetExpressCheckoutDetails(wrapper);

            if (ecResponse.Ack.HasValue &&
                ecResponse.Ack.Value.ToString() != "FAILURE" &&
                ecResponse.Errors.Count == 0)
            {
                double paymentAmount = 0.0;
                double.TryParse(ecResponse.GetExpressCheckoutDetailsResponseDetails.PaymentDetails.FirstOrDefault().OrderTotal.value, out paymentAmount);

                PaymentDetailsType paymentDetail = new PaymentDetailsType();
                paymentDetail.NotifyURL     = "http://replaceIpnUrl.com";
                paymentDetail.PaymentAction = (PaymentActionCodeType)EnumUtils.GetValue("Sale", typeof(PaymentActionCodeType));
                paymentDetail.OrderTotal    = new BasicAmountType((CurrencyCodeType)EnumUtils.GetValue("USD", typeof(CurrencyCodeType)), paymentAmount + "");
                List <PaymentDetailsType> paymentDetails = new List <PaymentDetailsType>();
                paymentDetails.Add(paymentDetail);

                DoExpressCheckoutPaymentRequestType doExpressCheckoutPaymentRequestType = new DoExpressCheckoutPaymentRequestType();
                request.Version = "104.0";
                DoExpressCheckoutPaymentRequestDetailsType requestDetails = new DoExpressCheckoutPaymentRequestDetailsType();
                requestDetails.PaymentDetails = paymentDetails;
                requestDetails.Token          = Request["token"];
                requestDetails.PayerID        = Request["PayerID"];
                doExpressCheckoutPaymentRequestType.DoExpressCheckoutPaymentRequestDetails = requestDetails;

                DoExpressCheckoutPaymentReq doExpressCheckoutPaymentReq = new DoExpressCheckoutPaymentReq();
                doExpressCheckoutPaymentReq.DoExpressCheckoutPaymentRequest = doExpressCheckoutPaymentRequestType;

                s = new PayPalAPIInterfaceServiceService(sdkConfig);
                DoExpressCheckoutPaymentResponseType doECResponse = s.DoExpressCheckoutPayment(doExpressCheckoutPaymentReq);

                if (doECResponse.Ack.HasValue &&
                    doECResponse.Ack.Value.ToString() != "FAILURE" &&
                    doECResponse.Errors.Count == 0)
                {
                    //create payment object for invoice
                    PaymentService       paymentService       = new PaymentService(this.db);
                    PaymentMethodService paymentMethodService = new PaymentMethodService(this.db);
                    var ccPymtMethod = paymentMethodService.GetCreditCardPaymentMethod(UserContact);

                    if (ccPymtMethod == null)
                    {
                        try
                        {
                            PaymentMethodTypeService paymentMethodTypeService = new PaymentMethodTypeService(this.db);
                            string ccTypeCode = GNPaymentMethodType.Types.CREDIT_CARD.GetCode();
                            var    ccType     = this.db.GNPaymentMethodTypes
                                                .Where(pt => pt.Name == ccTypeCode).FirstOrDefault();

                            await paymentMethodService.Insert(UserContact, new GNPaymentMethod
                            {
                                GNAccountId           = UserContact.GNOrganization.Account.Id,
                                GNPaymentMethodTypeId = ccType.Id,
                                Description           = "PAYPAL",
                                IsDefault             = true,
                                IsActive = true,
                                UsedForRecurrentPayments = false,
                                PCITokenId     = "X",
                                LastFourDigits = "X",
                                ExpirationDate = DateTime.MaxValue,
                                CreateDateTime = DateTime.Now,
                                CreatedBy      = UserContact.Id
                            });
                        }
                        catch (Exception e)
                        {
                            LogUtil.Error(logger, "Error adding PayPal Credit Card payment method!!", e);
                        }

                        ccPymtMethod = paymentMethodService.GetCreditCardPaymentMethod(UserContact);

                        if (ccPymtMethod == null)
                        {
                            throw new Exception("Credit Card Payment Method Not Found!!");
                        }
                    }

                    var ecPaymentInfo = doECResponse.DoExpressCheckoutPaymentResponseDetails.PaymentInfo.FirstOrDefault();

                    double grossAmount = 0.0;
                    double.TryParse(ecPaymentInfo.GrossAmount.value, out grossAmount);

                    if (grossAmount != 0.0)
                    {
                        try
                        {
                            var payment = new GNPayment
                            {
                                Id                = Guid.NewGuid(),
                                GNInvoiceId       = invoiceId,
                                GNPaymentMethodId = ccPymtMethod.Id,
                                PaymentDate       = DateTime.Now,
                                TotalAmount       = grossAmount,
                                Status            = ecPaymentInfo.PaymentStatus.Value.ToString(),
                                ExternalTxnId     = ecPaymentInfo.TransactionID,
                                CreateDateTime    = DateTime.Now,
                                CreatedBy         = UserContact.Id
                            };

                            this.AddInvoiceToPayment(payment);

                            await paymentService.Insert(UserContact, payment);
                        }
                        catch (Exception e)
                        {
                            LogUtil.Error(logger, "Error inserting payment!!", e);
                        }
                    }
                    else
                    {
                        throw new Exception("Payment Amount of 0.0 Not Allowed!!");
                    }
                }
            }

            return(RedirectToAction("MyBillingPayments", "Account"));
        }
Esempio n. 29
0
    protected void Page_Load(object sender, EventArgs e)
    {
        HttpContext CurrContext = HttpContext.Current;

        // Create the DoExpressCheckoutPaymentResponseType object
        DoExpressCheckoutPaymentResponseType responseDoExpressCheckoutPaymentResponseType = new DoExpressCheckoutPaymentResponseType();

        try
        {
            // Create the DoExpressCheckoutPaymentReq object
            DoExpressCheckoutPaymentReq doExpressCheckoutPayment = new DoExpressCheckoutPaymentReq();
            DoExpressCheckoutPaymentRequestDetailsType doExpressCheckoutPaymentRequestDetails = new DoExpressCheckoutPaymentRequestDetailsType();
            // The timestamped token value that was returned in the
            // `SetExpressCheckout` response and passed in the
            // `GetExpressCheckoutDetails` request.
            doExpressCheckoutPaymentRequestDetails.Token = (string)(Session["EcToken"]);
            // Unique paypal buyer account identification number as returned in
            // `GetExpressCheckoutDetails` Response
            doExpressCheckoutPaymentRequestDetails.PayerID = (string)(Session["PayerId"]);

            // # Payment Information
            // list of information about the payment
            List <PaymentDetailsType> paymentDetailsList = new List <PaymentDetailsType>();
            // information about the payment
            PaymentDetailsType    paymentDetails      = new PaymentDetailsType();
            CurrencyCodeType      currency_code_type  = (CurrencyCodeType)(Session["currency_code_type"]);
            PaymentActionCodeType payment_action_type = (PaymentActionCodeType)(Session["payment_action_type"]);
            //Pass the order total amount which was already set in session
            string          total_amount = (string)(Session["Total_Amount"]);
            BasicAmountType orderTotal   = new BasicAmountType(currency_code_type, total_amount);
            paymentDetails.OrderTotal    = orderTotal;
            paymentDetails.PaymentAction = payment_action_type;

            //BN codes to track all transactions
            paymentDetails.ButtonSource = BNCode;

            // Unique identifier for the merchant.
            SellerDetailsType sellerDetails = new SellerDetailsType();
            sellerDetails.PayPalAccountID = (string)(Session["SellerEmail"]);
            paymentDetails.SellerDetails  = sellerDetails;

            paymentDetailsList.Add(paymentDetails);
            doExpressCheckoutPaymentRequestDetails.PaymentDetails = paymentDetailsList;

            DoExpressCheckoutPaymentRequestType doExpressCheckoutPaymentRequest = new DoExpressCheckoutPaymentRequestType(doExpressCheckoutPaymentRequestDetails);
            doExpressCheckoutPayment.DoExpressCheckoutPaymentRequest = doExpressCheckoutPaymentRequest;
            // Create the service wrapper object to make the API call
            PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService();
            // # API call
            // Invoke the DoExpressCheckoutPayment method in service wrapper object
            responseDoExpressCheckoutPaymentResponseType = service.DoExpressCheckoutPayment(doExpressCheckoutPayment);
            if (responseDoExpressCheckoutPaymentResponseType != null)
            {
                // Response envelope acknowledgement
                string acknowledgement = "DoExpressCheckoutPayment API Operation - ";
                acknowledgement += responseDoExpressCheckoutPaymentResponseType.Ack.ToString();
                //logger.Info(acknowledgement + "\n");
                System.Diagnostics.Debug.WriteLine(acknowledgement + "\n");
                // # Success values
                if (responseDoExpressCheckoutPaymentResponseType.Ack.ToString().Trim().ToUpper().Equals("SUCCESS"))
                {
                    // Transaction identification number of the transaction that was
                    // created.
                    // This field is only returned after a successful transaction
                    // for DoExpressCheckout has occurred.
                    if (responseDoExpressCheckoutPaymentResponseType.DoExpressCheckoutPaymentResponseDetails.PaymentInfo != null)
                    {
                        IEnumerator <PaymentInfoType> paymentInfoIterator = responseDoExpressCheckoutPaymentResponseType.DoExpressCheckoutPaymentResponseDetails.PaymentInfo.GetEnumerator();
                        while (paymentInfoIterator.MoveNext())
                        {
                            PaymentInfoType paymentInfo = paymentInfoIterator.Current;
                            //logger.Info("Transaction ID : " + paymentInfo.TransactionID + "\n");

                            Session["Transaction_Id"]       = paymentInfo.TransactionID;
                            Session["Transaction_Type"]     = paymentInfo.TransactionType;
                            Session["Payment_Status"]       = paymentInfo.PaymentStatus;
                            Session["Payment_Type"]         = paymentInfo.PaymentType;
                            Session["Payment_Total_Amount"] = paymentInfo.GrossAmount.value;

                            System.Diagnostics.Debug.WriteLine("Transaction ID : " + paymentInfo.TransactionID + "\n");
                        }
                    }
                }
                // # Error Values
                else
                {
                    List <ErrorType> errorMessages = responseDoExpressCheckoutPaymentResponseType.Errors;
                    string           errorMessage  = "";
                    foreach (ErrorType error in errorMessages)
                    {
                        //logger.Debug("API Error Message : " + error.LongMessage);
                        System.Diagnostics.Debug.WriteLine("API Error Message : " + error.LongMessage + "\n");
                        errorMessage = errorMessage + error.LongMessage;
                    }
                    //Redirect to error page in case of any API errors
                    CurrContext.Items.Add("APIErrorMessage", errorMessage);
                    Server.Transfer("~/Response.aspx");
                }
            }
        }
        catch (System.Exception ex)
        {
            // Log the exception message
            //logger.Debug("Error Message : " + ex.Message);
            System.Diagnostics.Debug.WriteLine("Error Message : " + ex.Message);
        }
    }
Esempio n. 30
0
        public static String ProcessEC(ShoppingCart cart, decimal OrderTotal, int OrderNumber, String PayPalToken, String PayerID, String TransactionMode, out String AuthorizationResult, out String AuthorizationTransID)
        {
            PayPalAPISoapBinding   IPayPalRefund;
            PayPalAPIAASoapBinding IPayPal;

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

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

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

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

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

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

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

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

            varECRequest.Version = API_VER;

            ECPaymentDetails.OrderTotal = ECPaymentOrderTotal;

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

            ECPaymentDetailsList.Add(ECPaymentDetails);

            varECRequestDetails.PaymentDetails = ECPaymentDetailsList.ToArray();

            ECResponse = IPayPal.DoExpressCheckoutPayment(ECRequest);

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

            return(result);
        }
Esempio n. 31
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);
     }
 }
Esempio n. 32
0
        public PaymentResponse Payment(string token, string payerId)
        {
            // Configuration map containing signature credentials and other required configuration.
            // For a full list of configuration parameters refer in wiki page
            // [https://github.com/paypal/sdk-core-dotnet/wiki/SDK-Configuration-Parameters]

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

            GetExpressCheckoutDetailsReq getECWrapper = new GetExpressCheckoutDetailsReq();

            // (Required) A timestamped token, the value of which was returned by SetExpressCheckout response.
            // Character length and limitations: 20 single-byte characters
            getECWrapper.GetExpressCheckoutDetailsRequest = new GetExpressCheckoutDetailsRequestType(token);
            // # API call
            // Invoke the GetExpressCheckoutDetails method in service wrapper object
            GetExpressCheckoutDetailsResponseType getECResponse = service.GetExpressCheckoutDetails(getECWrapper);

            // Create request object
            DoExpressCheckoutPaymentRequestType        request        = new DoExpressCheckoutPaymentRequestType();
            DoExpressCheckoutPaymentRequestDetailsType requestDetails = new DoExpressCheckoutPaymentRequestDetailsType();

            request.DoExpressCheckoutPaymentRequestDetails = requestDetails;

            requestDetails.ButtonSource = "PTSH";

            requestDetails.PaymentDetails = getECResponse.GetExpressCheckoutDetailsResponseDetails.PaymentDetails;
            // (Required) The timestamped token value that was returned in the SetExpressCheckout response and passed in the GetExpressCheckoutDetails request.
            requestDetails.Token = token;
            // (Required) Unique PayPal buyer account identification number as returned in the GetExpressCheckoutDetails response
            requestDetails.PayerID = payerId;
            // (Required) How you want to obtain payment. It is one of the following values:
            // * Authorization – This payment is a basic authorization subject to settlement with PayPal Authorization and Capture.
            // * Order – This payment is an order authorization subject to settlement with PayPal Authorization and Capture.
            // * Sale – This is a final sale for which you are requesting payment.
            // Note: You cannot set this value to Sale in the SetExpressCheckout request and then change this value to Authorization in the DoExpressCheckoutPayment request.
            requestDetails.PaymentAction = PaymentActionCodeType.SALE;

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

            wrapper.DoExpressCheckoutPaymentRequest = request;
            // # API call
            // Invoke the DoExpressCheckoutPayment method in service wrapper object
            DoExpressCheckoutPaymentResponseType doECResponse = service.DoExpressCheckoutPayment(wrapper);

            // Check for API return status

            if (doECResponse.Ack.Equals(AckCodeType.FAILURE) ||
                (doECResponse.Errors != null && doECResponse.Errors.Any()))
            {
                return(null);
            }
            string transactionId = doECResponse.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].TransactionID;

            if (doECResponse.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].PendingReason != null && doECResponse.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].PendingReason != PendingStatusCodeType.NONE)
            {
                CancelTransaction(transactionId);

                throw new Exception(
                          doECResponse.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].PendingReason.ToString() + transactionId);
            }
            return(new PaymentResponse
            {
                TransactionId = transactionId,
                Price = float.Parse(requestDetails.PaymentDetails[0].OrderTotal.value)
            });
        }
Esempio n. 33
0
        public virtual async Task <VerifyPaymentResult> VerifyPayment(TblInvoices invoice)
        {
            var result = new VerifyPaymentResult();
            var token  = invoice.PaymentGatewayToken;

            var request = HttpContext.Current.Request;

            if (string.IsNullOrWhiteSpace(request.QueryString["Status"]) ||
                string.IsNullOrWhiteSpace(request.QueryString["token"]))
            {
                result.ErrorMessage = _localizationService.GetResource("Plugin.PaymentMethod.PayPal.StatusOrTokenInvalid");
                return(result);
            }
            if (!request.QueryString["Status"].Equals("OK"))
            {
                result.ErrorMessage = _localizationService.GetResource("Plugin.PaymentMethod.PayPal.StatusFieldIsNotOK");
                return(result);
            }

            await Task.Run(() =>
            {
                try
                {
                    var service      = new PayPalAPIInterfaceServiceService(GetPayPalConfig());
                    var getEcWrapper = new GetExpressCheckoutDetailsReq
                    {
                        GetExpressCheckoutDetailsRequest = new GetExpressCheckoutDetailsRequestType(token)
                    };
                    var getEcResponse  = service.GetExpressCheckoutDetails(getEcWrapper);
                    var ecRequest      = new DoExpressCheckoutPaymentRequestType();
                    var requestDetails = new DoExpressCheckoutPaymentRequestDetailsType();
                    ecRequest.DoExpressCheckoutPaymentRequestDetails = requestDetails;
                    requestDetails.PaymentDetails = getEcResponse.GetExpressCheckoutDetailsResponseDetails.PaymentDetails;
                    requestDetails.Token          = token;
                    requestDetails.PayerID        = getEcResponse.GetExpressCheckoutDetailsResponseDetails.PayerInfo.PayerID;
                    requestDetails.PaymentAction  = PaymentActionCodeType.SALE;
                    var wrapper = new DoExpressCheckoutPaymentReq {
                        DoExpressCheckoutPaymentRequest = ecRequest
                    };
                    var doEcResponse = service.DoExpressCheckoutPayment(wrapper);

                    if (doEcResponse.Ack == AckCodeType.SUCCESS)
                    {
                        result.IsSuccess     = true;
                        result.TransactionId = doEcResponse.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].TransactionID;
                    }
                    else
                    {
                        foreach (var error in doEcResponse.Errors)
                        {
                            result.ErrorMessage +=
                                $"[{error.SeverityCode}] {error.ErrorCode} : {error.LongMessage} </br>";
                        }
                    }
                }
                catch
                {
                    result.ErrorMessage = _localizationService.GetResource("Plugin.PaymentMethod.PayPal.ServiceUnavailable");
                }
            });

            return(result);
        }
        //public PaypalPayer GetExpressCheckout(IPaymentGatewaySettings settings,string token)
        //{
            
        //    GetExpressCheckoutDetailsReq req = new GetExpressCheckoutDetailsReq();
        //    GetExpressCheckoutDetailsRequestType request = new GetExpressCheckoutDetailsRequestType();
        //    req.GetExpressCheckoutDetailsRequest = request;
        //    CustomSecurityHeaderType securityHeader = GetCustomSecurityHeader(settings);
        //    request.Token = token;
        //    request.Version = API_VERSION;

        //    GetExpressCheckoutDetailsResponseType response = GetPayPalAAInterfaceClient(settings).GetExpressCheckoutDetails(ref securityHeader, req);

        //    if (response.Ack != AckCodeType.Success || response.Ack != AckCodeType.SuccessWithWarning)
        //        throw new PaymentServiceException(String.Format("Could not obtain Express Checkoutinformation. PayPal response was : {0}",
        //            String.Join(response.Errors.Select(n => String.Format("Error Code: {0} Error Message: {1};", n.ErrorCode, n.LongMessage)).ToArray())));
        //    if (!PaypalHelper.CheckSuccess(response, out error))
        //        throw new NopException(error);

        //    PaypalPayer payer = new PaypalPayer();
        //    payer.PayerEmail = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Payer;
        //    payer.FirstName = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.PayerName.FirstName;
        //    payer.LastName = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.PayerName.LastName;
        //    payer.CompanyName = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.PayerBusiness;
        //    payer.Address1 = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.Street1;
        //    payer.Address2 = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.Street2;
        //    payer.City = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.CityName;
        //    payer.State = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.StateOrProvince;
        //    payer.Zipcode = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.PostalCode;
        //    payer.Phone = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.ContactPhone;
        //    payer.PaypalCountryName = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.CountryName;
        //    payer.CountryCode = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.Country.ToString();
        //    payer.PayerID = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.PayerID;
        //    payer.Token = response.GetExpressCheckoutDetailsResponseDetails.Token;
        //    return payer;
        //}
        void DoExpressCheckout(string token)
        {
            DoExpressCheckoutPaymentReq req = new DoExpressCheckoutPaymentReq();
            DoExpressCheckoutPaymentRequestType request = new DoExpressCheckoutPaymentRequestType();
            req.DoExpressCheckoutPaymentRequest = request;
            request.Version = API_VERSION;
            DoExpressCheckoutPaymentRequestDetailsType details = new DoExpressCheckoutPaymentRequestDetailsType();
            request.DoExpressCheckoutPaymentRequestDetails = details;
            details.PaymentAction = _PaymentActionCodeType;
            details.PaymentActionSpecified = true;
            details.Token = token;
            
        }