コード例 #1
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);
        }
コード例 #2
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);
        }
コード例 #3
0
        protected void Submit_Click(object sender, EventArgs e)
        {
            // Create request object
            DoUATPExpressCheckoutPaymentRequestType    request        = new DoUATPExpressCheckoutPaymentRequestType();
            DoExpressCheckoutPaymentRequestDetailsType paymentDetails = new DoExpressCheckoutPaymentRequestDetailsType();

            request.DoExpressCheckoutPaymentRequestDetails = paymentDetails;
            paymentDetails.PayerID       = payerID.Value;
            paymentDetails.Token         = token.Value;
            paymentDetails.PaymentAction = (PaymentActionCodeType)
                                           Enum.Parse(typeof(PaymentActionCodeType), paymentAction.SelectedValue);

            // Set payment amount
            CurrencyCodeType currency = (CurrencyCodeType)
                                        Enum.Parse(typeof(CurrencyCodeType), currencyID.Value);

            paymentDetails.PaymentDetails.Add(new PaymentDetailsType());
            paymentDetails.PaymentDetails[0].OrderTotal =
                new BasicAmountType(currency, amount.Value);

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

            wrapper.DoUATPExpressCheckoutPaymentRequest = request;
            PayPalAPIInterfaceServiceService         service  = new PayPalAPIInterfaceServiceService();
            DoUATPExpressCheckoutPaymentResponseType response = service.DoUATPExpressCheckoutPayment(wrapper);

            // Check for API return status
            setKeyResponseObjects(service, response);
        }
コード例 #4
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()
                }
            });
        }
    }
コード例 #5
0
        /// <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;
            }
        }
コード例 #6
0
        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));
        }
コード例 #7
0
ファイル: PayPalService.cs プロジェクト: RemSoftDev/GeekWear
        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())
            });
        }
コード例 #8
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);
        }
コード例 #9
0
        private DoExpressCheckoutPaymentRequestDetailsType CreateExpressCheckoutPaymentRequest(GetExpressCheckoutDetailsResponseType getDetailsResponse, IOrderGroup orderGroup, IPayment payment)
        {
            var checkoutDetailsResponse = getDetailsResponse.GetExpressCheckoutDetailsResponseDetails;

            var doExpressChkOutPaymentReqDetails = new DoExpressCheckoutPaymentRequestDetailsType
            {
                Token   = payment.Properties[PayPalExpTokenPropertyName] as string,
                PayerID = checkoutDetailsResponse.PayerInfo.PayerID
            };

            if (Enum.TryParse(_paymentMethodConfiguration.PaymentAction, out TransactionType transactionType))
            {
                if (transactionType == TransactionType.Authorization)
                {
                    doExpressChkOutPaymentReqDetails.PaymentAction = PaymentActionCodeType.AUTHORIZATION;
                }
                else if (transactionType == TransactionType.Sale)
                {
                    doExpressChkOutPaymentReqDetails.PaymentAction = PaymentActionCodeType.SALE;
                }
            }

            var sentDetails = _payPalAPIHelper.GetPaymentDetailsType(payment, orderGroup, payment.Properties[PayPalOrderNumberPropertyName] as string, _notifyUrl);

            doExpressChkOutPaymentReqDetails.PaymentDetails = new List <PaymentDetailsType>()
            {
                sentDetails
            };

            var newShippingAddressFromPayPal = checkoutDetailsResponse.PaymentDetails[0].ShipToAddress;

            if (newShippingAddressFromPayPal != null)
            {
                doExpressChkOutPaymentReqDetails.PaymentDetails[0].ShipToAddress = newShippingAddressFromPayPal;
            }

            return(doExpressChkOutPaymentReqDetails);
        }
コード例 #10
0
        public DoExpressCheckoutPaymentReq Do()
        {
            var paymentDetail = new PaymentDetailsType();

            paymentDetail.PaymentAction = PaymentActionCodeType.SALE;
            paymentDetail.OrderTotal    = new BasicAmountType(CurrencyCodeType.NZD, _details.Amount.ToCurrencyString());

            var request = new DoExpressCheckoutPaymentRequestType {
                Version = PayPalConfig.VersionNumber
            };
            var requestDetails = new DoExpressCheckoutPaymentRequestDetailsType
            {
                PaymentDetails = paymentDetail.PutIntoList(),
                Token          = _details.Token,
                PayerID        = _details.PayerId
            };

            request.DoExpressCheckoutPaymentRequestDetails = requestDetails;

            return(new DoExpressCheckoutPaymentReq {
                DoExpressCheckoutPaymentRequest = request
            });
        }
コード例 #11
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));
        }
コード例 #12
0
        protected void Submit_Click(object sender, EventArgs e)
        {
            // Create request object
            DoUATPExpressCheckoutPaymentRequestType    request        = new DoUATPExpressCheckoutPaymentRequestType();
            DoExpressCheckoutPaymentRequestDetailsType paymentDetails = new DoExpressCheckoutPaymentRequestDetailsType();

            request.DoExpressCheckoutPaymentRequestDetails = paymentDetails;
            paymentDetails.PayerID       = payerID.Value;
            paymentDetails.Token         = token.Value;
            paymentDetails.PaymentAction = (PaymentActionCodeType)
                                           Enum.Parse(typeof(PaymentActionCodeType), paymentAction.SelectedValue);

            // Set payment amount
            CurrencyCodeType currency = (CurrencyCodeType)
                                        Enum.Parse(typeof(CurrencyCodeType), currencyID.Value);

            paymentDetails.PaymentDetails.Add(new PaymentDetailsType());
            paymentDetails.PaymentDetails[0].OrderTotal =
                new BasicAmountType(currency, amount.Value);

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

            wrapper.DoUATPExpressCheckoutPaymentRequest = request;

            // Configuration map containing signature credentials and other required configuration.
            // For a full list of configuration parameters refer in wiki page
            // [https://github.com/paypal/sdk-core-dotnet/wiki/SDK-Configuration-Parameters]
            Dictionary <string, string> configurationMap = Configuration.GetAcctAndConfig();

            PayPalAPIInterfaceServiceService         service  = new PayPalAPIInterfaceServiceService(configurationMap);
            DoUATPExpressCheckoutPaymentResponseType response = service.DoUATPExpressCheckoutPayment(wrapper);

            // Check for API return status
            setKeyResponseObjects(service, response);
        }
コード例 #13
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);
        }
コード例 #14
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");
            }
        }
コード例 #15
0
        //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;
            
        }
コード例 #16
0
        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);
        }
コード例 #17
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)
            });
        }
コード例 #18
0
        // # 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);
        }
コード例 #19
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);
        }
コード例 #20
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"));
        }
コード例 #21
0
ファイル: Gateway.cs プロジェクト: ColoradoWebGuy/RockPlugins
        /// <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);
        }
コード例 #22
0
ファイル: APIWrapper.cs プロジェクト: lanekp/LovRubWeb
        public Commerce.Common.Transaction DoExpressCheckout(Commerce.Common.Order order, bool AuthOnly)
        {
            //validate that the token is applied to the BillingAddress
            //same with PayerID
            if (String.IsNullOrEmpty(order.BillingAddress.PayPalPayerID))
            {
                throw new Exception("No payer ID set for the BillingAddress of the order");
            }

            if (String.IsNullOrEmpty(order.BillingAddress.PayPalToken))
            {
                throw new Exception("No Token set for the BillingAddress of the order");
            }

            PayPalSvc.DoExpressCheckoutPaymentReq      checkoutRequest = new DoExpressCheckoutPaymentReq();
            DoExpressCheckoutPaymentRequestType        checkoutReqType = new DoExpressCheckoutPaymentRequestType();
            DoExpressCheckoutPaymentRequestDetailsType checkoutDetails = new DoExpressCheckoutPaymentRequestDetailsType();
            PaymentDetailsType paymentDetails = new PaymentDetailsType();

            if (!AuthOnly)
            {
                checkoutDetails.PaymentAction = PaymentActionCodeType.Sale;
            }
            else
            {
                checkoutDetails.PaymentAction = PaymentActionCodeType.Authorization;
            }
            int roundTo = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalDigits;

            checkoutDetails.Token   = order.BillingAddress.PayPalToken;
            checkoutDetails.PayerID = order.BillingAddress.PayPalPayerID;
            checkoutReqType.Version = PayPalServiceUtility.PayPalAPIVersionNumber;
            decimal dTotal = order.OrderTotal;

            paymentDetails.OrderTotal    = GetBasicAmount(RoundIt(dTotal, roundTo));
            paymentDetails.ShippingTotal = this.GetBasicAmount(RoundIt(order.ShippingAmount, roundTo));
            paymentDetails.TaxTotal      = this.GetBasicAmount(RoundIt(order.TaxAmount, roundTo));
            paymentDetails.Custom        = order.OrderNumber;
            paymentDetails.ItemTotal     = GetBasicAmount(RoundIt(order.CalculateSubTotal(), roundTo));
            //paymentDetails.OrderDescription = orderDescription;


            //This tells PayPal that the dashCommerce is making the call. Please leave this
            //as it helps us keep going :):) (not monetarily, just with some love from PayPal).
            paymentDetails.ButtonSource = EC_BN_ID;
            //load up the payment items
            PaymentDetailsItemType item;

            int itemCount = order.Items.Count;

            PaymentDetailsItemType[] items = new PaymentDetailsItemType[itemCount];

            for (int i = 0; i < itemCount; i++)
            {
                item          = new PaymentDetailsItemType();
                item.Name     = order.Items[i].ProductName;
                item.Number   = order.Items[i].Sku;
                item.Quantity = order.Items[i].Quantity.ToString();
                item.Amount   = GetBasicAmount(RoundIt(order.Items[i].PricePaid, roundTo));
                items[i]      = item;
            }
            paymentDetails.PaymentDetailsItem = items;
            checkoutRequest.DoExpressCheckoutPaymentRequest = checkoutReqType;
            checkoutRequest.DoExpressCheckoutPaymentRequest.DoExpressCheckoutPaymentRequestDetails = checkoutDetails;
            checkoutRequest.DoExpressCheckoutPaymentRequest.DoExpressCheckoutPaymentRequestDetails.PaymentDetails = paymentDetails;
            PayPalSvc.DoExpressCheckoutPaymentResponseType response = service2.DoExpressCheckoutPayment(checkoutRequest);

            string errors = this.CheckErrors(response);
            string sOut   = "";

            Commerce.Common.Transaction trans = new Commerce.Common.Transaction();
            if (errors == string.Empty)
            {
                trans.GatewayResponse   = response.Ack.ToString();
                trans.AuthorizationCode = response.DoExpressCheckoutPaymentResponseDetails.PaymentInfo.TransactionID;
            }
            else
            {
                trans.GatewayResponse = errors;
            }

            //return out the transactionID
            return(trans);
        }
コード例 #23
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);
        }
コード例 #24
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);
        }
    }