Ejemplo n.º 1
0
        protected void Submit_Click(object sender, EventArgs e)
        {
            // Create request object
            GetExpressCheckoutDetailsRequestType request = new GetExpressCheckoutDetailsRequestType();

            // (Required) A timestamped token, the value of which was returned by SetExpressCheckout response.
            // Character length and limitations: 20 single-byte characters
            request.Token = token.Value;

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

            wrapper.GetExpressCheckoutDetailsRequest = request;

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

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

            // # API call
            // Invoke the GetExpressCheckoutDetails method in service wrapper object
            GetExpressCheckoutDetailsResponseType ecResponse = service.GetExpressCheckoutDetails(wrapper);

            // Check for API return status
            setKeyResponseObjects(service, ecResponse);
        }
    // # GetExpressCheckout API Operation
    // The GetExpressCheckoutDetails API operation obtains information about an Express Checkout transaction
    public GetExpressCheckoutDetailsResponseType GetExpressCheckoutDetailsAPIOperation()
    {
        // Create the GetExpressCheckoutDetailsResponseType object
        GetExpressCheckoutDetailsResponseType responseGetExpressCheckoutDetailsResponseType = new GetExpressCheckoutDetailsResponseType();

        try
        {
            // Create the GetExpressCheckoutDetailsReq object
            GetExpressCheckoutDetailsReq getExpressCheckoutDetails = new GetExpressCheckoutDetailsReq();

            // A timestamped token, the value of which was returned by `SetExpressCheckout` response
            GetExpressCheckoutDetailsRequestType getExpressCheckoutDetailsRequest = new GetExpressCheckoutDetailsRequestType("EC-11U13522TP7143059");
            getExpressCheckoutDetails.GetExpressCheckoutDetailsRequest = getExpressCheckoutDetailsRequest;

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

            // # API call
            // Invoke the GetExpressCheckoutDetails method in service wrapper object
            responseGetExpressCheckoutDetailsResponseType = service.GetExpressCheckoutDetails(getExpressCheckoutDetails);

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

                // # Success values
                if (responseGetExpressCheckoutDetailsResponseType.Ack.ToString().Trim().ToUpper().Equals("SUCCESS"))
                {
                    // Unique PayPal Customer Account identification number. This
                    // value will be null unless you authorize the payment by
                    // redirecting to PayPal after `SetExpressCheckout` call.
                    logger.Info("Payer ID : " + responseGetExpressCheckoutDetailsResponseType.GetExpressCheckoutDetailsResponseDetails.PayerInfo.PayerID + "\n");
                    Console.WriteLine("Payer ID : " + responseGetExpressCheckoutDetailsResponseType.GetExpressCheckoutDetailsResponseDetails.PayerInfo.PayerID + "\n");
                }
                // # Error Values
                else
                {
                    List <ErrorType> errorMessages = responseGetExpressCheckoutDetailsResponseType.Errors;
                    foreach (ErrorType error in errorMessages)
                    {
                        logger.Debug("API Error Message : " + error.LongMessage);
                        Console.WriteLine("API Error Message : " + error.LongMessage + "\n");
                    }
                }
            }
        }
        // # Exception log
        catch (System.Exception ex)
        {
            // Log the exception message
            logger.Debug("Error Message : " + ex.Message);
            Console.WriteLine("Error Message : " + ex.Message);
        }
        return(responseGetExpressCheckoutDetailsResponseType);
    }
Ejemplo n.º 3
0
        public GetExpressCheckoutDetailsResponseType GetExpressCheckoutDetails(string token)
        {
            // Create the request object
            GetExpressCheckoutDetailsRequestType pp_request = new GetExpressCheckoutDetailsRequestType();

            pp_request.Token = token;

            return((GetExpressCheckoutDetailsResponseType)caller.Call("GetExpressCheckoutDetails", pp_request));
        }
        public GetExpressCheckoutDetailsReq Do()
        {
            var request = new GetExpressCheckoutDetailsRequestType
            {
                Version = PayPalConfig.VersionNumber,
                Token   = _token
            };

            return(new GetExpressCheckoutDetailsReq {
                GetExpressCheckoutDetailsRequest = request
            });
        }
 GetExpressCheckoutDetailsResponseType GetExpressCheckoutDetailsRequest(IPaymentGatewaySettings settings, string token)
 {
     GetExpressCheckoutDetailsReq req = new GetExpressCheckoutDetailsReq();
     GetExpressCheckoutDetailsResponseType result = null;
     var request = new GetExpressCheckoutDetailsRequestType();
     req.GetExpressCheckoutDetailsRequest = request;
     request.Token = token;
     request.Version = API_VERSION;
     var service = GetPayPalAAInterfaceClient(settings);
     CustomSecurityHeaderType customSecurityHeader = new CustomSecurityHeaderType();
     GetExpressCheckoutDetailsResponseType response = service.GetExpressCheckoutDetails(ref customSecurityHeader, req);
     result = response;
     return response;
 }
Ejemplo n.º 6
0
        private GetExpressCheckoutDetailsResponseType GetExpressCheckoutDetailsResponse(FinancialGateway financialGateway, String token, out string errorMessage)
        {
            errorMessage = string.Empty;


            // Create the GetExpressCheckoutDetailsResponseType object
            GetExpressCheckoutDetailsResponseType responseGetExpressCheckoutDetailsResponseType = new GetExpressCheckoutDetailsResponseType();

            try
            {
                // Create the GetExpressCheckoutDetailsReq object
                GetExpressCheckoutDetailsReq getExpressCheckoutDetails = new GetExpressCheckoutDetailsReq();

                // A timestamped token, the value of which was returned by `SetExpressCheckout` response
                GetExpressCheckoutDetailsRequestType getExpressCheckoutDetailsRequest = new GetExpressCheckoutDetailsRequestType(token);
                getExpressCheckoutDetails.GetExpressCheckoutDetailsRequest = getExpressCheckoutDetailsRequest;

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

                // # API call
                // Invoke the GetExpressCheckoutDetails method in service wrapper object
                responseGetExpressCheckoutDetailsResponseType = service.GetExpressCheckoutDetails(getExpressCheckoutDetails);

                if (responseGetExpressCheckoutDetailsResponseType != null)
                {
                    // # Success values
                    if (responseGetExpressCheckoutDetailsResponseType.Ack.ToString().Trim().ToUpper().Equals("SUCCESS"))
                    {
                        return(responseGetExpressCheckoutDetailsResponseType);
                    }
                    // # Error Values
                    else
                    {
                        List <ErrorType> errorMessages = responseGetExpressCheckoutDetailsResponseType.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);
        }
Ejemplo n.º 7
0
        protected void Submit_Click(object sender, EventArgs e)
        {
            // Create request object
            GetExpressCheckoutDetailsRequestType request = new GetExpressCheckoutDetailsRequestType();

            request.Token = token.Value;

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

            wrapper.GetExpressCheckoutDetailsRequest = request;
            PayPalAPIInterfaceServiceService      service    = new PayPalAPIInterfaceServiceService();
            GetExpressCheckoutDetailsResponseType ecResponse = service.GetExpressCheckoutDetails(wrapper);

            // Check for API return status
            setKeyResponseObjects(service, ecResponse);
        }
Ejemplo n.º 8
0
        public Commerce.Common.Address GetExpressCheckout(string token)
        {
            //PayerInfo payer = new PayerInfo();
            Commerce.Common.Address payer = new Commerce.Common.Address();

            PayPalSvc.GetExpressCheckoutDetailsReq         req         = new GetExpressCheckoutDetailsReq();
            PayPalSvc.GetExpressCheckoutDetailsRequestType requestType = new GetExpressCheckoutDetailsRequestType();


            requestType.Token   = token;
            requestType.Version = PayPalServiceUtility.PayPalAPIVersionNumber;

            req.GetExpressCheckoutDetailsRequest = requestType;

            PayPalSvc.GetExpressCheckoutDetailsResponseType response = service2.GetExpressCheckoutDetails(req);

            string sOut = "";

            string errors = this.CheckErrors(response);

            if (errors == string.Empty)
            {
                string ack = response.Ack.ToString();
                payer.Email         = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Payer;
                payer.PayPalPayerID = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.PayerID;
                payer.FirstName     = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.PayerName.FirstName;
                payer.LastName      = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.PayerName.LastName;
                payer.Address1      = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.Street1;
                payer.Address2      = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.Street2;
                payer.City          = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.CityName;
                payer.StateOrRegion = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.StateOrProvince;
                payer.Zip           = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.PostalCode;
                payer.PayPalToken   = response.GetExpressCheckoutDetailsResponseDetails.Token;
                payer.Country       = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.CountryName;
            }
            else
            {
                payer.PayPalPayerID = errors;
            }
            return(payer);
        }
        /// <summary>
        /// Gets a paypal express checkout result
        /// </summary>
        /// <param name="token">paypal express checkout token</param>
        /// <returns>Paypal payer</returns>
        public PaypalPayer GetExpressCheckout(string token)
        {
            InitSettings();
            GetExpressCheckoutDetailsReq         req     = new GetExpressCheckoutDetailsReq();
            GetExpressCheckoutDetailsRequestType request = new GetExpressCheckoutDetailsRequestType();

            req.GetExpressCheckoutDetailsRequest = request;

            request.Token   = token;
            request.Version = this.APIVersion;

            GetExpressCheckoutDetailsResponseType response = service2.GetExpressCheckoutDetails(req);

            string error;

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

            PaypalPayer payer = new PaypalPayer();

            payer.PayerEmail        = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Payer;
            payer.FirstName         = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.PayerName.FirstName;
            payer.LastName          = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.PayerName.LastName;
            payer.CompanyName       = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.PayerBusiness;
            payer.Address1          = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.Street1;
            payer.Address2          = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.Street2;
            payer.City              = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.CityName;
            payer.State             = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.StateOrProvince;
            payer.Zipcode           = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.PostalCode;
            payer.Phone             = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.ContactPhone;
            payer.PaypalCountryName = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.CountryName;
            payer.CountryCode       = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.Country.ToString();
            payer.PayerID           = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.PayerID;
            payer.Token             = response.GetExpressCheckoutDetailsResponseDetails.Token;
            return(payer);
        }
Ejemplo n.º 10
0
        public DoExpressCheckoutPaymentResponseType DoExpressCheckout(HttpResponseBase response, string token)
        {
            var getCheckoutRequest = new GetExpressCheckoutDetailsRequestType();

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

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

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

            wrapper.DoExpressCheckoutPaymentRequest = doRequest;
            return(service.DoExpressCheckoutPayment(wrapper));
        }
Ejemplo n.º 11
0
        public GetExpressCheckoutDetailsResponseType GetExpressCheckoutDetails(string token)
        {
            // Create the request object
            GetExpressCheckoutDetailsRequestType pp_request = new GetExpressCheckoutDetailsRequestType();

            pp_request.Token = token;

            return (GetExpressCheckoutDetailsResponseType)caller.Call("GetExpressCheckoutDetails", pp_request);
        }
        private PayerInfo GetPayerInfo(string token, string payerId)
        {
            var payer   = new PayerInfo();
            var req     = new GetExpressCheckoutDetailsReq();
            var request = new GetExpressCheckoutDetailsRequestType();

            req.GetExpressCheckoutDetailsRequest = request;
            request.Token   = token;
            request.Version = Settings.Version;
            // System.Net.ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            var credentials = PaypalSecurityHeader();
            GetExpressCheckoutDetailsResponseType response = _paypalService2.GetExpressCheckoutDetails(ref credentials, req);

            if (response.Ack == AckCodeType.Success)
            {
                try
                {
                    payer.Email = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Payer;
                }
                catch (Exception)
                {
                    payer.Email = "";
                }

                payer.FirstName = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.PayerName.FirstName;
                payer.LastName  = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.PayerName.LastName;

                if (response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.PayerStatusSpecified == true)
                {
                    if (response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.PayerStatus == PayPalUserStatusCodeType.verified)
                    {
                        payer.IsVerify = true;
                    }
                    payer.AccountVerifyCode = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.PayerStatus.ToString();
                }


                payer.Address1    = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.Street1;
                payer.Address2    = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.Street2;
                payer.City        = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.CityName;
                payer.State       = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.StateOrProvince;
                payer.PostCode    = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.PostalCode;
                payer.PhoneNo     = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.ContactPhone;
                payer.Country     = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.CountryName;
                payer.CountryCode = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.Country.ToString();
                payer.PayerId     = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.PayerID;
                payer.Token       = response.GetExpressCheckoutDetailsResponseDetails.Token;

                //if (response.GetExpressCheckoutDetailsResponseDetails.Note > "")
                //{
                //    payer.note = payer.note + response.GetExpressCheckoutDetailsResponseDetails.Note;
                //}
                //payer.OrderTotal = response.GetExpressCheckoutDetailsResponseDetails.PaymentDetails(0).OrderTotal.Value;
                //payer.IsValid = true;
                if (response.GetExpressCheckoutDetailsResponseDetails.BillingAddress == null)
                {
                    payer.Address1 = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.Street1;
                    payer.Address2 = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.Street2;
                    payer.City     = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.CityName;
                    payer.State    = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.StateOrProvince;
                    payer.PostCode = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.PostalCode;
                    payer.Country  = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.CountryName;

                    if (response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.AddressStatusSpecified == true)
                    {
                        if (response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.AddressStatus == AddressStatusCodeType.Confirmed)
                        {
                            payer.IsValidAddress = true;
                        }
                        payer.AddressVerifyCode = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.AddressStatus.ToString();
                    }
                }
                else
                {
                    payer.Address1 = response.GetExpressCheckoutDetailsResponseDetails.BillingAddress.Street1;
                    payer.Address2 = response.GetExpressCheckoutDetailsResponseDetails.BillingAddress.Street2;
                    payer.City     = response.GetExpressCheckoutDetailsResponseDetails.BillingAddress.CityName;
                    payer.State    = response.GetExpressCheckoutDetailsResponseDetails.BillingAddress.StateOrProvince;
                    payer.PostCode = response.GetExpressCheckoutDetailsResponseDetails.BillingAddress.PostalCode;
                    payer.Country  = response.GetExpressCheckoutDetailsResponseDetails.BillingAddress.CountryName;
                    if (response.GetExpressCheckoutDetailsResponseDetails.BillingAddress.AddressStatusSpecified == true)
                    {
                        if (response.GetExpressCheckoutDetailsResponseDetails.BillingAddress.AddressStatus == AddressStatusCodeType.Confirmed)
                        {
                            payer.IsValidAddress = true;
                        }
                        payer.AddressVerifyCode = response.GetExpressCheckoutDetailsResponseDetails.BillingAddress.AddressStatus.ToString();
                    }
                }

                //Shipping addd-----------------------------

                if (response.GetExpressCheckoutDetailsResponseDetails.PayerInfo == null)
                {
                    payer.Address1    = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.Street1;
                    payer.Address2    = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.Street2;
                    payer.City        = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.CityName;
                    payer.State       = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.StateOrProvince;
                    payer.PostCode    = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.PostalCode;
                    payer.CountryCode = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.Country.ToString();
                }
            }
            return(payer);
        }
Ejemplo n.º 13
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));
        }
Ejemplo n.º 14
0
    protected void Page_Load(object sender, EventArgs e)
    {
        HttpContext CurrContext = HttpContext.Current;

        // Create the GetExpressCheckoutDetailsResponseType object
        GetExpressCheckoutDetailsResponseType responseGetExpressCheckoutDetailsResponseType = new GetExpressCheckoutDetailsResponseType();

        try
        {
            // Create the GetExpressCheckoutDetailsReq object
            GetExpressCheckoutDetailsReq getExpressCheckoutDetails = new GetExpressCheckoutDetailsReq();
            // A timestamped token, the value of which was returned by `SetExpressCheckout` API response
            string EcToken = (string)(Session["EcToken"]);
            GetExpressCheckoutDetailsRequestType getExpressCheckoutDetailsRequest = new GetExpressCheckoutDetailsRequestType(EcToken);
            getExpressCheckoutDetails.GetExpressCheckoutDetailsRequest = getExpressCheckoutDetailsRequest;
            // Create the service wrapper object to make the API call
            PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService();
            // # API call
            // Invoke the GetExpressCheckoutDetails method in service wrapper object
            responseGetExpressCheckoutDetailsResponseType = service.GetExpressCheckoutDetails(getExpressCheckoutDetails);
            if (responseGetExpressCheckoutDetailsResponseType != null)
            {
                // Response envelope acknowledgement
                string acknowledgement = "GetExpressCheckoutDetails API Operation - ";
                acknowledgement += responseGetExpressCheckoutDetailsResponseType.Ack.ToString();
                //logger.Info(acknowledgement + "\n");
                System.Diagnostics.Debug.WriteLine(acknowledgement + "\n");
                // # Success values
                if (responseGetExpressCheckoutDetailsResponseType.Ack.ToString().Trim().ToUpper().Equals("SUCCESS"))
                {
                    // Unique PayPal Customer Account identification number. This
                    // value will be null unless you authorize the payment by
                    // redirecting to PayPal after `SetExpressCheckout` call.
                    string PayerId = responseGetExpressCheckoutDetailsResponseType.GetExpressCheckoutDetailsResponseDetails.PayerInfo.PayerID;
                    // Store PayerId in session to be used in DoExpressCheckout API operation
                    Session["PayerId"] = PayerId;

                    List <PaymentDetailsType> paymentDetails = responseGetExpressCheckoutDetailsResponseType.GetExpressCheckoutDetailsResponseDetails.PaymentDetails;
                    foreach (PaymentDetailsType paymentdetail in paymentDetails)
                    {
                        AddressType ShippingAddress = paymentdetail.ShipToAddress;
                        if (ShippingAddress != null)
                        {
                            Session["Address_Name"]            = ShippingAddress.Name;
                            Session["Address_Street"]          = ShippingAddress.Street1 + " " + ShippingAddress.Street2;
                            Session["Address_CityName"]        = ShippingAddress.CityName;
                            Session["Address_StateOrProvince"] = ShippingAddress.StateOrProvince;
                            Session["Address_CountryName"]     = ShippingAddress.CountryName;
                            Session["Address_PostalCode"]      = ShippingAddress.PostalCode;
                        }
                        Session["Currency_Code"]  = paymentdetail.OrderTotal.currencyID;
                        Session["Order_Total"]    = paymentdetail.OrderTotal.value;
                        Session["Shipping_Total"] = paymentdetail.ShippingTotal.value;
                        List <PaymentDetailsItemType> itemList = paymentdetail.PaymentDetailsItem;
                        foreach (PaymentDetailsItemType item in itemList)
                        {
                            Session["Product_Quantity"] = item.Quantity;
                            Session["Product_Name"]     = item.Name;
                        }
                    }
                }
                // # Error Values
                else
                {
                    List <ErrorType> errorMessages = responseGetExpressCheckoutDetailsResponseType.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");
                }
            }
            //Redirect to DoExpressCheckoutPayment.aspx page if the method chosen is MarkExpressCheckout
            //The buyer need not review the shipping address and shipping method as it's already provided
            string ecMethod = (string)(Session["ExpressCheckoutMethod"]);
            if (ecMethod.Equals("MarkExpressCheckout"))
            {
                Response.Redirect("DoExpressCheckoutPayment.aspx", false);
                Context.ApplicationInstance.CompleteRequest();
            }
        }
        // # Exception log
        catch (System.Exception ex)
        {
            // Log the exception message
            //logger.Debug("Error Message : " + ex.Message);
            System.Diagnostics.Debug.WriteLine("Error Message : " + ex.Message);
        }
    }
Ejemplo n.º 15
0
        public static string GetECDetails(string payPalToken, int customerId)
        {
            var payPalRefund  = new PayPalAPISoapBinding();
            var payPalBinding = new PayPalAPIAASoapBinding();
            var payerId       = string.Empty;
            var addressStatus = string.Empty;
            var request       = new GetExpressCheckoutDetailsReq();
            var requestType   = new GetExpressCheckoutDetailsRequestType();
            var response      = new GetExpressCheckoutDetailsResponseType();
            var responseType  = new GetExpressCheckoutDetailsResponseDetailsType();

            GetPaypalRequirements(out payPalRefund, out payPalBinding);

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

            response = payPalBinding.GetExpressCheckoutDetails(request);

            var payerInfo = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo;

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

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

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

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

            var customer = new Customer(customerId, true);

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

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

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

            return(payerId);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Processes the successful transaction, was called when PayPal.com redirect back.
        /// </summary>
        /// <param name="orderGroup">The order group that was processed.</param>
        /// <param name="payment">The order payment.</param>
        /// <param name="acceptUrl">The redirect url when finished.</param>
        /// <param name="cancelUrl">The redirect url when error happens.</param>
        /// <returns>The url redirection after process.</returns>
        public string ProcessSuccessfulTransaction(IOrderGroup orderGroup, IPayment payment, string acceptUrl, string cancelUrl)
        {
            if (HttpContext.Current == null)
            {
                return(cancelUrl);
            }

            if (HttpContext.Current.Session != null)
            {
                HttpContext.Current.Session.Remove("LastCouponCode");
            }

            if (!(orderGroup is ICart cart))
            {
                // return to the shopping cart page immediately and show error messages
                return(ProcessUnsuccessfulTransaction(cancelUrl, Utilities.Translate("CommitTranErrorCartNull")));
            }

            string redirectionUrl;

            using (var scope = new TransactionScope())
            {
                SetSecurityProtocolToTls12();

                var getDetailRequest = new GetExpressCheckoutDetailsRequestType
                {
                    Token = payment.Properties[PayPalExpTokenPropertyName] as string // Add request-specific fields to the request.
                };

                // Execute the API operation and obtain the response.
                var caller             = PayPalApiHelper.GetPayPalApiCallerServices(_paymentMethodConfiguration);
                var getDetailsResponse = caller.GetExpressCheckoutDetails(new GetExpressCheckoutDetailsReq
                {
                    GetExpressCheckoutDetailsRequest = getDetailRequest
                });

                var errorCheck = _payPalApiHelper.CheckErrors(getDetailsResponse);
                if (!string.IsNullOrEmpty(errorCheck))
                {
                    RestoreSecurityProtocol();

                    // unsuccessful get detail call
                    return(ProcessUnsuccessfulTransaction(cancelUrl, errorCheck));
                }

                var expressCheckoutDetailsResponse = getDetailsResponse.GetExpressCheckoutDetailsResponseDetails;
                // get commerceOrderId from what we put to PayPal instead of getting from cookie
                payment.Properties[PayPalOrderNumberPropertyName] = expressCheckoutDetailsResponse.InvoiceID;

                //process details sent from paypal, changing addresses if required
                string emptyAddressMsg;

                //process billing address
                var payPalBillingAddress = expressCheckoutDetailsResponse.BillingAddress;
                if (payPalBillingAddress != null && AddressHandling.IsAddressChanged(payment.BillingAddress, payPalBillingAddress))
                {
                    emptyAddressMsg = _payPalApiHelper.ProcessOrderAddress(expressCheckoutDetailsResponse.PayerInfo, payPalBillingAddress, payment.BillingAddress, CustomerAddressTypeEnum.Billing, "CommitTranErrorPayPalBillingAddressEmpty");
                    if (!string.IsNullOrEmpty(emptyAddressMsg))
                    {
                        RestoreSecurityProtocol();

                        return(ProcessUnsuccessfulTransaction(cancelUrl, emptyAddressMsg));
                    }
                }

                //process shipping address
                var payPalShippingAddress = expressCheckoutDetailsResponse.PaymentDetails[0].ShipToAddress;
                if (payPalShippingAddress != null && AddressHandling.IsAddressChanged(cart.GetFirstShipment().ShippingAddress, payPalShippingAddress))
                {
                    //when address was changed on PayPal site, it might cause changing tax value changed and changing order value also.
                    var taxValueBefore = _taxCalculator.GetTaxTotal(cart, cart.Market, cart.Currency);

                    var shippingAddress = orderGroup.CreateOrderAddress("address");

                    emptyAddressMsg = _payPalApiHelper.ProcessOrderAddress(expressCheckoutDetailsResponse.PayerInfo, payPalShippingAddress, shippingAddress, CustomerAddressTypeEnum.Shipping, "CommitTranErrorPayPalShippingAddressEmpty");
                    if (!string.IsNullOrEmpty(emptyAddressMsg))
                    {
                        RestoreSecurityProtocol();

                        return(ProcessUnsuccessfulTransaction(cancelUrl, emptyAddressMsg));
                    }

                    cart.GetFirstShipment().ShippingAddress = shippingAddress;

                    var taxValueAfter = _taxCalculator.GetTaxTotal(cart, cart.Market, cart.Currency);
                    if (taxValueBefore != taxValueAfter)
                    {
                        RestoreSecurityProtocol();

                        _orderRepository.Save(cart); // Saving cart to submit order address changed.
                        scope.Complete();
                        return(ProcessUnsuccessfulTransaction(cancelUrl, Utilities.Translate("ProcessPaymentTaxValueChangedWarning")));
                    }
                }

                // Add request-specific fields to the request.
                // Create the request details object.
                var doExpressChkOutPaymentReqDetails = CreateExpressCheckoutPaymentRequest(getDetailsResponse, orderGroup, payment);

                // Execute the API operation and obtain the response.
                var doCheckOutResponse = caller.DoExpressCheckoutPayment(new DoExpressCheckoutPaymentReq
                {
                    DoExpressCheckoutPaymentRequest = new DoExpressCheckoutPaymentRequestType(doExpressChkOutPaymentReqDetails)
                });

                errorCheck = _payPalApiHelper.CheckErrors(doCheckOutResponse);
                if (!string.IsNullOrEmpty(errorCheck))
                {
                    RestoreSecurityProtocol();

                    // unsuccessful doCheckout response
                    return(ProcessUnsuccessfulTransaction(cancelUrl, errorCheck));
                }

                // everything is fine, this is a flag to tell ProcessPayment know about this case: redirect back from PayPal with accepted payment
                var errorMessages = new List <string>();
                var cartCompleted = DoCompletingCart(cart, errorMessages);

                if (!cartCompleted)
                {
                    RestoreSecurityProtocol();

                    return(UriSupport.AddQueryString(cancelUrl, "message", string.Join(";", errorMessages.Distinct().ToArray())));
                }

                // Place order
                var purchaseOrder = MakePurchaseOrder(doCheckOutResponse, cart, payment);

                // Commit changes
                scope.Complete();

                redirectionUrl = CreateRedirectionUrl(purchaseOrder, acceptUrl, payment.BillingAddress.Email);

                RestoreSecurityProtocol();
            }

            _logger.Information($"PayPal transaction succeeds, redirect end user to {redirectionUrl}");
            return(redirectionUrl);
        }
        public GetExpressCheckoutResult GetExpressCheckout()
        {
            HttpContext            context         = HttpContext.Current;
            ExpressCheckoutSession existingSession = ExpressCheckoutSession.Current;

            if (existingSession == null)
            {
                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 GetExpressCheckoutResult(null, customErrorList));
            }
            context.Trace.Write("Detected PayPal Token:" + existingSession.Token);
            context.Trace.Write("Token Expiration:" + existingSession.TokenExpiration.ToLongDateString());

            GetExpressCheckoutDetailsRequestType expressCheckoutRequest = new GetExpressCheckoutDetailsRequestType();

            expressCheckoutRequest.Token   = existingSession.Token;
            expressCheckoutRequest.Version = "1.0";

            //EXECUTE REQUEST
            GetExpressCheckoutDetailsResponseType expressCheckoutResponse;

            expressCheckoutResponse = (GetExpressCheckoutDetailsResponseType)SoapCall("GetExpressCheckoutDetails", expressCheckoutRequest);
            if (expressCheckoutResponse == null)
            {
                ErrorType[] customErrorList = 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.";
                customErrorList[0]       = customError;
                return(new GetExpressCheckoutResult(null, customErrorList));
            }

            //IF ERRORS ARE IN RESPONSE, RETURN THEM AND EXIT PROCESS
            if (expressCheckoutResponse.Errors != null)
            {
                return(new GetExpressCheckoutResult(null, expressCheckoutResponse.Errors));
            }

            //GET THE DETAILS OF THE REQUEST
            GetExpressCheckoutDetailsResponseDetailsType expressCheckoutDetails;

            expressCheckoutDetails = expressCheckoutResponse.GetExpressCheckoutDetailsResponseDetails;

            //MAKE SURE CUSTOMER IDS MATCH
            User currentUser = Token.Instance.User;

            if (expressCheckoutDetails.Custom != ("UID" + currentUser.UserId.ToString()))
            {
                ErrorType[] customErrorList = new ErrorType[1];
                ErrorType   customError     = new ErrorType();
                customError.ErrorCode    = "USER";
                customError.ShortMessage = "User Mismatch";
                customError.LongMessage  = "The PayPal basket did not have the expected user context.";
                customErrorList[0]       = customError;
                Logger.Warn("Error in PayPal GetExpressCheckout.  User ID detected in PayPal response: " + expressCheckoutDetails.Custom + ", Customer User ID: " + currentUser.UserId.ToString());
                return(new GetExpressCheckoutResult(null, customErrorList));
            }

            //CHECK WHETHER AN EXISTING USER IS ASSOCIATED WITH THE RETURNED PAYPAL ID
            //IF THE CURRENT USER DOES NOT MATCH, LOG IN THE PAYPAL USER ACCOUNT
            string paypalEmail   = expressCheckoutDetails.PayerInfo.Payer;
            string paypalPayerID = expressCheckoutDetails.PayerInfo.PayerID;
            //PAYER ID IS SUPPOSED TO BE UNIQUE REGARDLESS OF EMAIL ADDRESS, LOOK FOR ASSOCIATED ACCT
            User paypalUser = UserDataSource.LoadForPayPalId(paypalPayerID);

            //IF NOT FOUND, SEE IF AN ACCOUNT EXISTS WITH THAT EMAIL AS USERNAME
            if (paypalUser == null)
            {
                paypalUser = UserDataSource.LoadForUserName(paypalEmail);
            }
            if (paypalUser != null)
            {
                //WE FOUND AN ACCOUNT FOR THIS PAYPAL USER
                context.Trace.Write(this.GetType().ToString(), "PAYPAL USER FOUND IN DATABASE");
                if (currentUser.UserId != paypalUser.UserId)
                {
                    //THE PAYPAL USER IS NOT THE CURRENT USER CONTEXT, SO TRANSFER THE BASKET
                    context.Trace.Write(this.GetType().ToString(), "MOVE BASKET TO " + paypalUser.UserName);
                    Basket.Transfer(currentUser.UserId, paypalUser.UserId, true);
                    //REMOVE PAYPAL EXPRESS SESSION FROM OLD USER SESSION
                    ExpressCheckoutSession.Delete(currentUser);
                }
            }
            else
            {
                //WE DID NOT FIND AN ACCOUNT
                context.Trace.Write(this.GetType().ToString(), "PAYPAL USER NOT FOUND IN DATABASE");
                if (currentUser.IsAnonymous)
                {
                    //CURRENT USER IS ANON, REGISTER A NEW USER ACCOUNT
                    context.Trace.Write(this.GetType().ToString(), "REGISTERING " + paypalEmail);
                    MembershipCreateStatus status;
                    paypalUser          = UserDataSource.CreateUser(paypalEmail, paypalEmail, StringHelper.RandomString(8), string.Empty, string.Empty, true, 0, out status);
                    paypalUser.PayPalId = paypalPayerID;
                    paypalUser.Save();
                    Basket.Transfer(currentUser.UserId, paypalUser.UserId, true);
                    //REMOVE PAYPAL EXPRESS SESSION FROM OLD USER SESSION
                    ExpressCheckoutSession.Delete(currentUser);
                }
                else
                {
                    //UPDATE THE PAYPAL ID OF THE CURRENTLY AUTHENTICATED USER
                    context.Trace.Write(this.GetType().ToString(), "ASSIGNING CURRENT USER TO " + paypalEmail);
                    paypalUser          = currentUser;
                    paypalUser.PayPalId = paypalPayerID;
                    paypalUser.Save();
                }
            }

            //PAYPAL HAS AUTHENTICATED THE USER
            FormsAuthentication.SetAuthCookie(paypalUser.UserName, false);
            //UPDATE THE PRIMARY ADDRESS INFORMATION FOR THE USER
            Address billingAddress = paypalUser.PrimaryAddress;

            billingAddress.FirstName   = expressCheckoutDetails.PayerInfo.PayerName.FirstName;
            billingAddress.LastName    = expressCheckoutDetails.PayerInfo.PayerName.LastName;
            billingAddress.Company     = expressCheckoutDetails.PayerInfo.PayerBusiness;
            billingAddress.Address1    = expressCheckoutDetails.PayerInfo.Address.Street1;
            billingAddress.Address2    = expressCheckoutDetails.PayerInfo.Address.Street2;
            billingAddress.City        = expressCheckoutDetails.PayerInfo.Address.CityName;
            billingAddress.Province    = expressCheckoutDetails.PayerInfo.Address.StateOrProvince;
            billingAddress.PostalCode  = expressCheckoutDetails.PayerInfo.Address.PostalCode;
            billingAddress.CountryCode = expressCheckoutDetails.PayerInfo.Address.Country.ToString();
            if (!string.IsNullOrEmpty(expressCheckoutDetails.ContactPhone))
            {
                billingAddress.Phone = expressCheckoutDetails.ContactPhone;
            }
            billingAddress.Email     = expressCheckoutDetails.PayerInfo.Payer;
            billingAddress.Residence = (!string.IsNullOrEmpty(billingAddress.Company));
            paypalUser.Save();

            //UPDATE THE SHIPPING ADDRESS IN THE BASKET
            Basket basket = paypalUser.Basket;

            basket.Package();
            foreach (BasketShipment shipment in basket.Shipments)
            {
                shipment.AddressId = billingAddress.AddressId;
            }
            basket.Save();

            //PUT PAYPAL DETAILS INTO SESSION
            context.Trace.Write(this.GetType().ToString(), "Saving ExpressCheckoutSession");
            existingSession.Token           = expressCheckoutDetails.Token;
            existingSession.TokenExpiration = DateTime.UtcNow.AddHours(3);
            existingSession.PayerID         = paypalPayerID;
            existingSession.Payer           = expressCheckoutDetails.PayerInfo.Payer;
            existingSession.Save(paypalUser);
            context.Trace.Write("Saved PayPal Token:" + existingSession.Token);
            context.Trace.Write("Token Expiration:" + existingSession.TokenExpiration.ToLongDateString());
            return(new GetExpressCheckoutResult(paypalUser, null));
        }
Ejemplo n.º 18
0
        protected GetExpressCheckoutDetailsResponseType ECGetExpressCheckoutCode(string token)
        {
            var caller = CreateCaller();

            var pp_request = new GetExpressCheckoutDetailsRequestType
            {
                Version = "51.0",
                Token = token
            };

            return (GetExpressCheckoutDetailsResponseType)caller.Call("GetExpressCheckoutDetails", pp_request);
        }
Ejemplo n.º 19
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"));
        }
        // # GetExpressCheckout API Operation
        // The GetExpressCheckoutDetails API operation obtains information about an Express Checkout transaction
        public GetExpressCheckoutDetailsResponseType GetExpressCheckoutDetailsAPIOperation()
        {
            // Create the GetExpressCheckoutDetailsResponseType object
            GetExpressCheckoutDetailsResponseType responseGetExpressCheckoutDetailsResponseType =
                new GetExpressCheckoutDetailsResponseType();

            try
            {
                // Create the GetExpressCheckoutDetailsReq object
                GetExpressCheckoutDetailsReq getExpressCheckoutDetails = new GetExpressCheckoutDetailsReq();

                // A timestamped token, the value of which was returned by `SetExpressCheckout` response
                GetExpressCheckoutDetailsRequestType getExpressCheckoutDetailsRequest =
                    new GetExpressCheckoutDetailsRequestType("EC-3PG29673CT337061M");
                getExpressCheckoutDetails.GetExpressCheckoutDetailsRequest = getExpressCheckoutDetailsRequest;

                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 GetExpressCheckoutDetails method in service wrapper object
                responseGetExpressCheckoutDetailsResponseType = service.GetExpressCheckoutDetails(getExpressCheckoutDetails);

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

                    // # Success values
                    if (responseGetExpressCheckoutDetailsResponseType.Ack.ToString().Trim().ToUpper().Equals("SUCCESS"))
                    {
                        // Unique PayPal Customer Account identification number. This
                        // value will be null unless you authorize the payment by
                        // redirecting to PayPal after `SetExpressCheckout` call.
                        Console.WriteLine("Payer ID : " +
                                          responseGetExpressCheckoutDetailsResponseType.GetExpressCheckoutDetailsResponseDetails.PayerInfo
                                          .PayerID + "\n");
                    }
                    // # Error Values
                    else
                    {
                        List <ErrorType> errorMessages = responseGetExpressCheckoutDetailsResponseType.Errors;
                        foreach (ErrorType error in errorMessages)
                        {
                            Console.WriteLine("API Error Message : " + error.LongMessage + "\n");
                        }
                    }
                }
            }
            // # Exception log
            catch (System.Exception ex)
            {
                // Log the exception message
                Console.WriteLine("Error Message : " + ex.Message);
            }
            return(responseGetExpressCheckoutDetailsResponseType);
        }