Example #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);
        }
Example #2
0
        private ViewResult PaymentResponseSuccess(DoExpressCheckoutPaymentResponseType response, Checkout checkout, List <CartItem> cart)
        {
            var failure       = new List <string>();
            var paymentStatus = response.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].PaymentStatus;

            if (paymentStatus == PaymentStatusCodeType.DENIED)
            {
                //change
                failure.Add("Unsuccessful.");
                return(PaymentFailed(failure));
            }
            if (paymentStatus == PaymentStatusCodeType.VOIDED || paymentStatus == PaymentStatusCodeType.EXPIRED)
            {
                //changes
                failure.Add("Expired");
                return(PaymentFailed(failure));
            }
            if (paymentStatus == PaymentStatusCodeType.COMPLETED || paymentStatus == PaymentStatusCodeType.PENDING ||
                paymentStatus == PaymentStatusCodeType.COMPLETEDFUNDSHELD)
            {
                return(PaymentSuccess(response, checkout, cart));
            }
            if (paymentStatus == PaymentStatusCodeType.FAILED)
            {
                failure.Add("Failed");
                return(PaymentFailed(failure));
            }
            throw new InvalidOperationException("Invalid payment operation.");
        }
Example #3
0
        private IPurchaseOrder MakePurchaseOrder(DoExpressCheckoutPaymentResponseType doCheckOutResponse, ICart cart, IPayment payment)
        {
            var orderReference = _orderRepository.SaveAsPurchaseOrder(cart);
            var purchaseOrder  = _orderRepository.Load <IPurchaseOrder>(orderReference.OrderGroupId);

            purchaseOrder.OrderNumber = payment.Properties[PayPalOrderNumberPropertyName] as string;

            // read PayPal's transactionId here, in order to store it, refund ...
            var paymentTransactionId = doCheckOutResponse.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].TransactionID;

            UpdateTransactionIdOfPaymentMethod(purchaseOrder, paymentTransactionId);

            // Update last order date time for CurrentContact
            UpdateLastOrderTimestampOfCurrentContact(CustomerContext.Current.CurrentContact, purchaseOrder.Created);

            AddCartNotesToPurchaseOrder(purchaseOrder, cart);

            AddNoteToPurchaseOrder(string.Empty, $"New order placed by {PrincipalInfo.CurrentPrincipal.Identity.Name} in Public site", Guid.Empty, purchaseOrder);

            AddCartPropertiesToPurchaseOrder(purchaseOrder, cart);

            // Remove old cart
            _orderRepository.Delete(cart.OrderLink);
            purchaseOrder.OrderStatus = OrderStatus.InProgress;

            // Update display name of product by current language
            Utilities.UpdateDisplayNameWithCurrentLanguage(purchaseOrder);

            _orderRepository.Save(purchaseOrder);

            return(purchaseOrder);
        }
Example #4
0
 public static PayPalCompleteResponse ToResponse(this DoExpressCheckoutPaymentResponseType instance)
 {
     return(new PayPalCompleteResponse
     {
         Errors = instance.Errors
                  .Select(x => ErrorTypeExtensions.ToPaypalError(x))
                  .ToList(),
         Status = instance.Ack.ToString()
     });
 }
Example #5
0
    public void DoExpressCheckoutPayment()
    {
        DoExpressCheckoutPaymentSample       sample = new DoExpressCheckoutPaymentSample();
        DoExpressCheckoutPaymentResponseType responseDoExpressCheckoutPaymentResponseType = sample.DoExpressCheckoutPaymentAPIOperation();

        Assert.IsNotNull(responseDoExpressCheckoutPaymentResponseType);
        // Please change the sample inputs according to the documentation in the sample for the following assertions:
        // Assert.AreEqual(responseDoExpressCheckoutPaymentResponseType.Ack.ToString().ToUpper(), "SUCCESS");
        // Assert.IsNotNull(responseDoExpressCheckoutPaymentResponseType.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].TransactionID);
    }
Example #6
0
        private ViewResult PaymentSuccess(DoExpressCheckoutPaymentResponseType response, Checkout checkout, List <CartItem> cart)
        {
            var details     = response.DoExpressCheckoutPaymentResponseDetails;
            var transaction = new TransacDetails
            {
                TransId = details.PaymentInfo[0].TransactionID
            };
            var user = Session["User"] as UserLoginDto;

            OrderManagement.RecordPayPalTransaction(checkout, cart, details.PaymentInfo[0].TransactionID, user.Id);
            return(View("PaymentSuccess", transaction));
        }
        /// <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;
            }
        }
Example #8
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())
            });
        }
Example #9
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);
        }
Example #10
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);
        }
Example #11
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);
        }
Example #12
0
        // A helper method used by APIResponse.aspx that returns select response parameters
        // of interest. You must process API response objects as applicable to your application
        private void setKeyResponseObjects(PayPalAPIInterfaceServiceService service, DoExpressCheckoutPaymentResponseType doECResponse)
        {
            Dictionary <string, string> responseParams = new Dictionary <string, string>();

            responseParams.Add("Correlation Id", doECResponse.CorrelationID);
            responseParams.Add("API Result", doECResponse.Ack.ToString());
            HttpContext CurrContext = HttpContext.Current;

            if (doECResponse.Ack.Equals(AckCodeType.FAILURE) ||
                (doECResponse.Errors != null && doECResponse.Errors.Count > 0))
            {
                CurrContext.Items.Add("Response_error", doECResponse.Errors);
            }
            else
            {
                CurrContext.Items.Add("Response_error", null);
                responseParams.Add("EC Token", doECResponse.DoExpressCheckoutPaymentResponseDetails.Token);
                responseParams.Add("Transaction Id", doECResponse.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].TransactionID);
                responseParams.Add("Payment status", doECResponse.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].PaymentStatus.ToString());
                if (doECResponse.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].PendingReason != null)
                {
                    responseParams.Add("Pending reason", doECResponse.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].PendingReason.ToString());
                }
                if (doECResponse.DoExpressCheckoutPaymentResponseDetails.BillingAgreementID != null)
                {
                    responseParams.Add("Billing Agreement Id", doECResponse.DoExpressCheckoutPaymentResponseDetails.BillingAgreementID);
                }
            }

            CurrContext.Items.Add("Response_keyResponseObject", responseParams);
            CurrContext.Items.Add("Response_apiName", "DoExpressChecoutPayment");
            CurrContext.Items.Add("Response_redirectURL", null);
            CurrContext.Items.Add("Response_requestPayload", service.getLastRequest());
            CurrContext.Items.Add("Response_responsePayload", service.getLastResponse());
            Server.Transfer("../APIResponse.aspx");
        }
Example #13
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);
        }
        private void SavePayPalTransactionSuccessfulyConfirmed(DoExpressCheckoutPaymentResponseType response)
        {
            string responseStr = JSONHelper.Serialize(response);
            var details = response.DoExpressCheckoutPaymentResponseDetails;

            Log.InfoFormat("Saving confirmed PayPal transaction: token={0}, response={1}", details.Token, responseStr);

            try
            {
                using (var conn = new SqlConnection(Settings.Default.PayPalDb))
                using (var cmd = conn.CreateCommand())
                {
                    cmd.CommandText = "INSERT INTO PayPalExpressCheckoutConfirmed (Token, Response)" +
                                      "VALUES (@token, @response)";
                    var tokenParam = cmd.Parameters.Add("@token", SqlDbType.VarChar);
                    tokenParam.Value = details.Token;

                    var responseParam = cmd.Parameters.Add("@response", SqlDbType.VarChar);
                    responseParam.Value = responseStr;

                    conn.Open();
                    int rows = cmd.ExecuteNonQuery();

                    if (rows != 1)
                        throw new ApplicationException("Inserting a transaction returned rows != 1: " + rows);
                }
            }
            catch (Exception e)
            {
                Log.Error("Saving transaction failed. ", e);
                // we don't rethrow the exception. We'll try to complete the transaction.
            }
        }
Example #16
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");
            }
        }
        public override PostProcessPaymentResult PostProcessPayment(PostProcessPaymentEvaluationContext context)
        {
            var retVal = new PostProcessPaymentResult();

            if (context == null && context.Payment == null)
            {
                throw new ArgumentNullException("paymentEvaluationContext");
            }

            if (context.Order == null)
            {
                throw new NullReferenceException("no order with this id");
            }

            retVal.OrderId = context.Order.Id;

            if (!(context.Store != null && !string.IsNullOrEmpty(context.Store.Url)))
            {
                throw new NullReferenceException("no store with this id");
            }

            var config = GetConfigMap(context.Store);

            var service = new PayPalAPIInterfaceServiceService(config);

            GetExpressCheckoutDetailsResponseType response   = null;
            DoExpressCheckoutPaymentResponseType  doResponse = null;

            var getExpressCheckoutDetailsRequest = GetGetExpressCheckoutDetailsRequest(context.OuterId);

            try
            {
                response = service.GetExpressCheckoutDetails(getExpressCheckoutDetailsRequest);

                CheckResponse(response);

                var status = response.GetExpressCheckoutDetailsResponseDetails.CheckoutStatus;

                if (!status.Equals("PaymentActionCompleted"))
                {
                    var doExpressCheckoutPaymentRequest = GetDoExpressCheckoutPaymentRequest(response, context.OuterId);
                    doResponse = service.DoExpressCheckoutPayment(doExpressCheckoutPaymentRequest);

                    CheckResponse(doResponse);

                    response = service.GetExpressCheckoutDetails(getExpressCheckoutDetailsRequest);
                    status   = response.GetExpressCheckoutDetailsResponseDetails.CheckoutStatus;
                }
                if (status.Equals("PaymentActionCompleted"))
                {
                    retVal.IsSuccess        = true;
                    retVal.NewPaymentStatus = PaymentStatus.Paid;
                }
            }
            catch (System.Exception ex)
            {
                retVal.Error            = ex.Message;
                retVal.NewPaymentStatus = PaymentStatus.Pending;
            }

            return(retVal);
        }
        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);
        }
Example #19
0
        private ActionResult ProcessingResult_PayPal(ProcessingResultModel model)
        {
            if (model == null)
            {
                throw new System.ArgumentNullException("model");
            }
            PaymentResultContext context = new PaymentResultContext();

            context.Order = model.order;
            if (model.success == true)
            {
                if (model.token == null)
                {
                    throw new System.ArgumentNullException("token");
                }
                if (model.payerID == null)
                {
                    throw new System.ArgumentNullException("payerID");
                }
                GetExpressCheckoutDetailsRequestType request = new GetExpressCheckoutDetailsRequestType();
                request.Version = "104.0";
                request.Token   = model.token;
                GetExpressCheckoutDetailsReq wrapper = new GetExpressCheckoutDetailsReq();
                wrapper.GetExpressCheckoutDetailsRequest = request;
                System.Collections.Generic.Dictionary <string, string> config = PaymentController.PayPal_CreateConfig();
                PayPalAPIInterfaceServiceService      service    = new PayPalAPIInterfaceServiceService(config);
                GetExpressCheckoutDetailsResponseType ecResponse = service.GetExpressCheckoutDetails(wrapper);
                if (ecResponse == null)
                {
                    throw new System.Exception("checkout details result is null");
                }
                if (ecResponse.Errors != null && ecResponse.Errors.Count > 0)
                {
                    ecResponse.Errors.ForEach(delegate(ErrorType m)
                    {
                        context.Errors.Add(m.LongMessage);
                    });
                }
                if (ecResponse.Ack == AckCodeType.SUCCESS || ecResponse.Ack == AckCodeType.SUCCESSWITHWARNING)
                {
                    GetExpressCheckoutDetailsResponseDetailsType details = ecResponse.GetExpressCheckoutDetailsResponseDetails;
                    if (details == null)
                    {
                        throw new System.Exception("details object is null");
                    }
                    if (string.IsNullOrEmpty(details.InvoiceID))
                    {
                        throw new System.Exception("invoiceID not found");
                    }
                    if (details.PaymentDetails == null)
                    {
                        throw new System.Exception("payment details is null");
                    }
                    System.Collections.Generic.List <PaymentDetailsType> paymentDetails = new System.Collections.Generic.List <PaymentDetailsType>();
                    foreach (PaymentDetailsType payment in details.PaymentDetails)
                    {
                        paymentDetails.Add(new PaymentDetailsType
                        {
                            NotifyURL     = null,
                            PaymentAction = payment.PaymentAction,
                            OrderTotal    = payment.OrderTotal
                        });
                    }
                    DoExpressCheckoutPaymentRequestType paymentRequest = new DoExpressCheckoutPaymentRequestType();
                    paymentRequest.Version = "104.0";
                    paymentRequest.DoExpressCheckoutPaymentRequestDetails = new DoExpressCheckoutPaymentRequestDetailsType
                    {
                        PaymentDetails = paymentDetails,
                        Token          = model.token,
                        PayerID        = model.payerID
                    };
                    DoExpressCheckoutPaymentResponseType doECResponse = service.DoExpressCheckoutPayment(new DoExpressCheckoutPaymentReq
                    {
                        DoExpressCheckoutPaymentRequest = paymentRequest
                    });
                    if (doECResponse == null)
                    {
                        throw new System.Exception("payment result is null");
                    }
                    if (doECResponse.Errors != null && doECResponse.Errors.Count > 0)
                    {
                        doECResponse.Errors.ForEach(delegate(ErrorType m)
                        {
                            context.Errors.Add(m.LongMessage);
                        });
                    }
                    if (doECResponse.Ack == AckCodeType.SUCCESS || doECResponse.Ack == AckCodeType.SUCCESSWITHWARNING)
                    {
                        ConfirmInvoiceResult invoiceResult = BookingProvider.ConfirmInvoice(details.InvoiceID.Trim());
                        Tracing.DataTrace.TraceEvent(TraceEventType.Information, 0, "PAYPAL transaction: invoice: '{0}', invoice confirmation: '{1}'", new object[]
                        {
                            details.InvoiceID,
                            invoiceResult.IsSuccess ? "SUCCESS" : "FAILED"
                        });
                        if (!invoiceResult.IsSuccess)
                        {
                            context.Errors.Add(string.Format("invoice confirmation error: {0}", invoiceResult.ErrorMessage));
                        }
                        else
                        {
                            context.Success = true;

                            BookingProvider.AcceptInvoice(Convert.ToInt32(context.Order));
                        }
                    }
                }
            }
            else
            {
                context.Errors.Add(PaymentStrings.PaymentCancelled);
            }
            return(base.View("_ProcessingResult", context));
        }
Example #20
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);
        }
Example #21
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)
            });
        }
        public ExpressCheckoutResult DoExpressCheckout()
        {
            HttpContext            context       = HttpContext.Current;
            TraceContext           trace         = context.Trace;
            string                 traceCategory = this.GetType().ToString();
            ExpressCheckoutSession paypalSession = ExpressCheckoutSession.Current;

            if (paypalSession == null)
            {
                //EXIT WITH EXCEPTION
                ErrorType[] customErrorList = new ErrorType[1];
                ErrorType   customError     = new ErrorType();
                customError.ErrorCode    = "SESSION";
                customError.ShortMessage = "Missing Token";
                customError.LongMessage  = "The PayPal session token was expired or unavailable.  Please try again.";
                customErrorList[0]       = customError;
                return(new ExpressCheckoutResult(0, string.Empty, customErrorList));
            }
            trace.Write(traceCategory, "Detected PayPal Token:" + paypalSession.Token);
            trace.Write(traceCategory, "Token Expiration:" + paypalSession.TokenExpiration.ToLongDateString());

            if (string.IsNullOrEmpty(paypalSession.PayerID))
            {
                //EXIT WITH EXCEPTION
                ErrorType[] customErrorList = new ErrorType[1];
                ErrorType   customError     = new ErrorType();
                customError.ErrorCode    = "SESSION";
                customError.ShortMessage = "Missing Payer ID";
                customError.LongMessage  = "The PayPal Payer ID is not present.";
                customErrorList[0]       = customError;
                return(new ExpressCheckoutResult(0, string.Empty, customErrorList));
            }
            trace.Write(traceCategory, "Detected PayPal Payer ID:" + paypalSession.PayerID);

            //GET THE CURRENCY FOR THE TRANSACTION
            string           storeCurrencyCode = Token.Instance.Store.BaseCurrency.ISOCode;
            CurrencyCodeType baseCurrencyCode  = PayPalProvider.GetPayPalCurrencyType(storeCurrencyCode);

            //CREATE THE EXPRESS CHECKOUT
            DoExpressCheckoutPaymentRequestType expressCheckoutRequest = new DoExpressCheckoutPaymentRequestType();

            expressCheckoutRequest.DoExpressCheckoutPaymentRequestDetails                        = new DoExpressCheckoutPaymentRequestDetailsType();
            expressCheckoutRequest.DoExpressCheckoutPaymentRequestDetails.Token                  = paypalSession.Token;
            expressCheckoutRequest.DoExpressCheckoutPaymentRequestDetails.PaymentAction          = this.UseAuthCapture ? PaymentActionCodeType.Sale : PaymentActionCodeType.Authorization;
            expressCheckoutRequest.DoExpressCheckoutPaymentRequestDetails.PaymentActionSpecified = true;
            expressCheckoutRequest.DoExpressCheckoutPaymentRequestDetails.PayerID                = paypalSession.PayerID;
            expressCheckoutRequest.Version = "1.0";

            //SET THE ORDER TOTAL AMOUNTS
            Basket basket = Token.Instance.User.Basket;

            trace.Write(traceCategory, "Set Order Totals");
            LSDecimal curOrderTotal    = basket.Items.TotalPrice();
            LSDecimal curShippingTotal = basket.Items.TotalPrice(OrderItemType.Shipping) + GetShippingCouponTotal(basket.Items);
            LSDecimal curHandlingTotal = basket.Items.TotalPrice(OrderItemType.Handling);
            LSDecimal curTaxTotal      = basket.Items.TotalPrice(OrderItemType.Tax);
            LSDecimal curItemTotal     = curOrderTotal - (curShippingTotal + curHandlingTotal + curTaxTotal);

            //MAKE SURE OUR BREAKDOWN IS VALID
            if ((curShippingTotal < 0) || (curHandlingTotal < 0) || (curTaxTotal < 0) || (curItemTotal < 0))
            {
                //THE BREAKDOWN IS INVALID, DO NOT INCLUDE IT IN THE REQUEST
                curShippingTotal = 0;
                curHandlingTotal = 0;
                curTaxTotal      = 0;
                curItemTotal     = curOrderTotal;
            }

            //SET THE PAYMENT DETAILS
            expressCheckoutRequest.DoExpressCheckoutPaymentRequestDetails.PaymentDetails    = new PaymentDetailsType[1];
            expressCheckoutRequest.DoExpressCheckoutPaymentRequestDetails.PaymentDetails[0] = new PaymentDetailsType();
            PaymentDetailsType paymentDetails = expressCheckoutRequest.DoExpressCheckoutPaymentRequestDetails.PaymentDetails[0];

            paymentDetails.OrderTotal            = new BasicAmountType();
            paymentDetails.OrderTotal.currencyID = baseCurrencyCode;
            paymentDetails.OrderTotal.Value      = string.Format("{0:##,##0.00}", curOrderTotal);

            paymentDetails.ItemTotal            = new BasicAmountType();
            paymentDetails.ItemTotal.currencyID = baseCurrencyCode;
            paymentDetails.ItemTotal.Value      = string.Format("{0:##,##0.00}", curItemTotal);

            paymentDetails.ShippingTotal            = new BasicAmountType();
            paymentDetails.ShippingTotal.currencyID = baseCurrencyCode;
            paymentDetails.ShippingTotal.Value      = string.Format("{0:##,##0.00}", curShippingTotal);

            paymentDetails.HandlingTotal            = new BasicAmountType();
            paymentDetails.HandlingTotal.currencyID = baseCurrencyCode;
            paymentDetails.HandlingTotal.Value      = string.Format("{0:##,##0.00}", curHandlingTotal);

            paymentDetails.TaxTotal            = new BasicAmountType();
            paymentDetails.TaxTotal.currencyID = baseCurrencyCode;
            paymentDetails.TaxTotal.Value      = string.Format("{0:##,##0.00}", curTaxTotal);

            trace.Write(traceCategory, "Order Total: " + curOrderTotal);
            trace.Write(traceCategory, "Item Total: " + curItemTotal);
            trace.Write(traceCategory, "Shipping Total: " + curShippingTotal);
            trace.Write(traceCategory, "Handling Total: " + curHandlingTotal);
            trace.Write(traceCategory, "Tax Total: " + curTaxTotal);

            //SET THE BUTTON SOURCE
            trace.Write(traceCategory, "Set Button Source");
            paymentDetails.ButtonSource = "ablecommerce-EC";

            //SET THE NOTIFY URL
            string notifyUrl = GetStoreUrl() + "/ProcessPayPal.ashx";

            trace.Write(traceCategory, "IPN Callback URL: " + notifyUrl);
            paymentDetails.NotifyURL = notifyUrl;

            //WE HAVE ALL NECESSARY INFORMATION TO DO EXPRESS CHECKOUT
            //COMMIT THE ORDER BEFORE SUBMITTING THE PAYPAL TRANSACTION

            //CREATE THE ABLECOMMERCE PAYMENT ITEM
            Payment checkoutPayment = new Payment();

            checkoutPayment.PaymentMethodId = GetPayPalPaymentMethodId(false);
            checkoutPayment.Amount          = curOrderTotal;
            checkoutPayment.CurrencyCode    = baseCurrencyCode.ToString();

            //AT THIS POINT, EXECUTE THE CHECKOUT TO SUBMIT THE ORDER
            CheckoutRequest  checkoutRequest  = new CheckoutRequest(checkoutPayment);
            CheckoutResponse checkoutResponse = basket.Checkout(checkoutRequest);
            int orderId = checkoutResponse.OrderId;

            //LOAD THE ORDER AND RE-OBTAIN THE PAYMENT RECORD TO AVOID DATA INCONSISTENCIES
            Order order = OrderDataSource.Load(orderId);

            if (order == null)
            {
                //EXIT WITH EXCEPTION
                ErrorType[] customErrorList = new ErrorType[1];
                ErrorType   customError     = new ErrorType();
                customError.ErrorCode    = "ORDER";
                customError.ShortMessage = "Your order could not be completed at this time.";
                customError.LongMessage  = "Your order could not be completed at this time and payment was not processed. " + string.Join(" ", checkoutResponse.WarningMessages.ToArray());
                customErrorList[0]       = customError;
                return(new ExpressCheckoutResult(0, string.Empty, customErrorList));
            }

            int findPaymentId = checkoutPayment.PaymentId;

            foreach (Payment payment in order.Payments)
            {
                if (payment.PaymentId == findPaymentId)
                {
                    checkoutPayment = payment;
                }
            }

            //SET THE DESCRIPTION
            paymentDetails.OrderDescription = "Order #" + order.OrderNumber.ToString();
            paymentDetails.Custom           = orderId.ToString();

            //EXECUTE PAYPAL REQUEST
            trace.Write(traceCategory, "Do Request");
            DoExpressCheckoutPaymentResponseType expressCheckoutResponse = (DoExpressCheckoutPaymentResponseType)SoapCall("DoExpressCheckoutPayment", expressCheckoutRequest);

            ErrorType[]   responseErrors     = null;
            PaymentStatus finalPaymentStatus = PaymentStatus.Unprocessed;
            bool          isPendingeCheck    = false;

            if (expressCheckoutResponse != null)
            {
                if (expressCheckoutResponse.Errors == null)
                {
                    //CREATE THE PAYPAL TRANSACTION RECORD
                    Transaction     checkoutTransaction = new Transaction();
                    PaymentInfoType paymentInfo         = expressCheckoutResponse.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0];
                    isPendingeCheck = (paymentInfo.PaymentStatus == PaymentStatusCodeType.Pending && paymentInfo.PendingReason == PendingStatusCodeType.echeck);
                    PaymentStatusCodeType paymentStatus = paymentInfo.PaymentStatus;
                    switch (paymentStatus)
                    {
                    case PaymentStatusCodeType.Completed:
                    case PaymentStatusCodeType.Processed:
                    case PaymentStatusCodeType.Pending:
                        if (isPendingeCheck)
                        {
                            finalPaymentStatus = PaymentStatus.CapturePending;
                            checkoutTransaction.ResponseCode    = "PENDING";
                            checkoutTransaction.ResponseMessage = "echeck";
                        }
                        else
                        {
                            finalPaymentStatus = (paymentStatus != PaymentStatusCodeType.Pending) ? PaymentStatus.Captured : PaymentStatus.Authorized;
                        }
                        checkoutTransaction.TransactionStatus = TransactionStatus.Successful;
                        break;

                    default:
                        finalPaymentStatus = PaymentStatus.Unprocessed;
                        checkoutTransaction.TransactionStatus = TransactionStatus.Failed;
                        checkoutTransaction.ResponseCode      = expressCheckoutResponse.Ack.ToString();
                        checkoutTransaction.ResponseMessage   = paymentStatus.ToString().ToUpperInvariant();
                        break;
                    }
                    checkoutTransaction.TransactionType       = this.UseAuthCapture ? TransactionType.Capture : TransactionType.Authorize;
                    checkoutTransaction.Amount                = AlwaysConvert.ToDecimal(paymentInfo.GrossAmount.Value, (Decimal)curOrderTotal);
                    checkoutTransaction.AuthorizationCode     = paymentInfo.TransactionID;
                    checkoutTransaction.AVSResultCode         = "U";
                    checkoutTransaction.ProviderTransactionId = paymentInfo.TransactionID;
                    checkoutTransaction.Referrer              = context.Request.ServerVariables["HTTP_REFERER"];
                    checkoutTransaction.PaymentGatewayId      = this.PaymentGatewayId;
                    checkoutTransaction.RemoteIP              = context.Request.ServerVariables["REMOTE_ADDR"];
                    checkoutPayment.Transactions.Add(checkoutTransaction);

                    //FIND THE WAITING FOR IPN TRANSACTION AND REMOVE
                    int i = checkoutPayment.Transactions.Count - 1;
                    while (i >= 0)
                    {
                        if (string.IsNullOrEmpty(checkoutPayment.Transactions[i].AuthorizationCode))
                        {
                            checkoutPayment.Transactions.DeleteAt(i);
                        }
                        i--;
                    }
                }
                else
                {
                    //SOME SORT OF ERROR ATTEMPTING CHECKOUT
                    responseErrors = expressCheckoutResponse.Errors;
                }
            }
            else
            {
                //NO RESPONSE, GENERATE CUSTOM ERROR
                responseErrors = new ErrorType[1];
                ErrorType customError = new ErrorType();
                customError.ErrorCode    = "NORESP";
                customError.ShortMessage = "No Response From Server";
                customError.LongMessage  = "The PayPal service is unavailable at this time.";
                responseErrors[0]        = customError;
            }
            trace.Write(traceCategory, "Do Request Done");

            //ERRORS IN RESPONSE?
            if ((responseErrors != null) && (responseErrors.Length > 0))
            {
                //CREATE THE PAYPAL TRANSACTION RECORD FOR ERROR
                Transaction checkoutTransaction = new Transaction();
                finalPaymentStatus = PaymentStatus.Unprocessed;
                checkoutTransaction.TransactionStatus = TransactionStatus.Failed;
                checkoutTransaction.Amount            = curOrderTotal;
                checkoutTransaction.AuthorizationCode = string.Empty;
                checkoutTransaction.Referrer          = context.Request.ServerVariables["HTTP_REFERER"];
                checkoutTransaction.PaymentGatewayId  = this.PaymentGatewayId;
                checkoutTransaction.RemoteIP          = context.Request.ServerVariables["REMOTE_ADDR"];
                checkoutTransaction.ResponseCode      = responseErrors[0].ShortMessage;
                checkoutTransaction.ResponseMessage   = responseErrors[0].LongMessage;
                checkoutPayment.Transactions.Add(checkoutTransaction);
            }

            //MAKE SURE PAYMENT STATUS IS CORRECT
            checkoutPayment.ReferenceNumber = paypalSession.Payer;
            checkoutPayment.PaymentStatus   = finalPaymentStatus;
            if (isPendingeCheck)
            {
                checkoutPayment.PaymentStatusReason = "echeck";
            }

            //RECALCULATE THE ORDER STATUS (BUG 6384) AND TRIGGER PAYMENT EVENTS (BUG 8650)
            order.Save(true, true);

            //CLEAR THE TOKENS SET IN SESSION
            paypalSession.Delete();
            return(new ExpressCheckoutResult(orderId, string.Empty, responseErrors));
        }
Example #23
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);
        }
    }
Example #24
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);
        }
Example #25
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"));
        }
Example #26
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);
     }
 }