// # SetExpressCheckout API Operation
    // The SetExpressCheckout API operation initiates an Express Checkout transaction.
    public SetExpressCheckoutResponseType SetExpressCheckoutAPIOperation()
    {
        // Create the SetExpressCheckoutResponseType object
        SetExpressCheckoutResponseType responseSetExpressCheckoutResponseType = new SetExpressCheckoutResponseType();

        try
        {
            // # SetExpressCheckoutReq
            SetExpressCheckoutRequestDetailsType setExpressCheckoutRequestDetails = new SetExpressCheckoutRequestDetailsType();

            // URL to which the buyer's browser is returned after choosing to pay
            // with PayPal. For digital goods, you must add JavaScript to this page
            // to close the in-context experience.
            // `Note:
            // PayPal recommends that the value be the final review page on which
            // the buyer confirms the order and payment or billing agreement.`
            setExpressCheckoutRequestDetails.ReturnURL = "http://localhost/return";

            // URL to which the buyer is returned if the buyer does not approve the
            // use of PayPal to pay you. For digital goods, you must add JavaScript
            // to this page to close the in-context experience.
            // `Note:
            // PayPal recommends that the value be the original page on which the
            // buyer chose to pay with PayPal or establish a billing agreement.`
            setExpressCheckoutRequestDetails.CancelURL = "http://localhost/cancel";

            // # 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";

            // `Address` to which the order is shipped, which takes mandatory params:
            //
            // * `Street Name`
            // * `City`
            // * `State`
            // * `Country`
            // * `Postal Code`
            AddressType shipToAddress1 = new AddressType();
            shipToAddress1.Street1         = "Ape Way";
            shipToAddress1.CityName        = "Austin";
            shipToAddress1.StateOrProvince = "TX";
            shipToAddress1.Country         = CountryCodeType.US;
            shipToAddress1.PostalCode      = "78750";

            paymentDetails1.ShipToAddress = shipToAddress1;

            // IPN URL
            // * PayPal Instant Payment Notification is a call back system that is initiated when a transaction is completed
            // * The transaction related IPN variables will be received on the call back URL specified in the request
            // * The IPN variables have to be sent back to the PayPal system for validation, upon validation PayPal will send a response string "VERIFIED" or "INVALID"
            // * PayPal would continuously resend IPN if a wrong IPN is sent
            paymentDetails1.NotifyURL = "http://IPNhost";

            // 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";

            // IPN URL
            // * PayPal Instant Payment Notification is a call back system that is initiated when a transaction is completed
            // * The transaction related IPN variables will be received on the call back URL specified in the request
            // * The IPN variables have to be sent back to the PayPal system for validation, upon validation PayPal will send a response string "VERIFIED" or "INVALID"
            // * PayPal would continuously resend IPN if a wrong IPN is sent
            paymentDetails2.NotifyURL = "http://IPNhost";

            // `Address` to which the order is shipped, which takes mandatory params:
            //
            // * `Street Name`
            // * `City`
            // * `State`
            // * `Country`
            // * `Postal Code`
            AddressType shipToAddress2 = new AddressType();
            shipToAddress2.Street1         = "Ape Way";
            shipToAddress2.CityName        = "Austin";
            shipToAddress2.StateOrProvince = "TX";
            shipToAddress2.Country         = CountryCodeType.US;
            shipToAddress2.PostalCode      = "78750";
            paymentDetails2.ShipToAddress  = shipToAddress2;

            paymentDetailsList.Add(paymentDetails1);
            paymentDetailsList.Add(paymentDetails2);

            setExpressCheckoutRequestDetails.PaymentDetails = paymentDetailsList;

            SetExpressCheckoutReq         setExpressCheckout        = new SetExpressCheckoutReq();
            SetExpressCheckoutRequestType setExpressCheckoutRequest = new SetExpressCheckoutRequestType(setExpressCheckoutRequestDetails);

            setExpressCheckout.SetExpressCheckoutRequest = setExpressCheckoutRequest;

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

            // # API call
            // Invoke the SetExpressCheckout method in service wrapper object
            responseSetExpressCheckoutResponseType = service.SetExpressCheckout(setExpressCheckout);

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

                // # Success values
                if (responseSetExpressCheckoutResponseType.Ack.ToString().Trim().ToUpper().Equals("SUCCESS"))
                {
                    // # Redirecting to PayPal for authorization
                    // Once you get the "Success" response, needs to authorise the
                    // transaction by making buyer to login into PayPal. For that,
                    // need to construct redirect url using EC token from response.
                    // For example,
                    // `redirectURL="https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token="+setExpressCheckoutResponse.Token;`

                    // Express Checkout Token
                    logger.Info("Express Checkout Token : " + responseSetExpressCheckoutResponseType.Token + "\n");
                    Console.WriteLine("Express Checkout Token : " + responseSetExpressCheckoutResponseType.Token + "\n");
                }
                // # Error Values
                else
                {
                    List <ErrorType> errorMessages = responseSetExpressCheckoutResponseType.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(responseSetExpressCheckoutResponseType);
    }
        // # 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);
        }
Beispiel #3
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);
        }
Beispiel #4
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);
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        HttpContext CurrContext = HttpContext.Current;

        // Create the SetExpressCheckoutResponseType object
        SetExpressCheckoutResponseType responseSetExpressCheckoutResponseType = new SetExpressCheckoutResponseType();

        try
        {
            // Check if the EC methos is shorcut or mark
            string ecMethod = "";
            if (Request.QueryString["ExpressCheckoutMethod"] != null)
            {
                ecMethod = Request.QueryString["ExpressCheckoutMethod"];
            }
            else if ((string)(Session["ExpressCheckoutMethod"]) != null)
            {
                ecMethod = (string)(Session["ExpressCheckoutMethod"]);
            }
            string item_name     = "";
            string item_id       = "";
            string item_desc     = "";
            string item_quantity = "";
            string item_amount   = "";
            //string tax_amount = "";
            //string shipping_amount = "";
            //string handling_amount = "";
            //string shipping_discount_amount = "";
            //string insurance_amount = "";
            string total_amount  = "";
            string currency_code = "";
            string payment_type  = "";
            string roundedtotal  = "";
            string roundeditmamt = "";

            // From Marck EC Page
            //string shipping_rate = "";
            string first_name  = "";
            string last_name   = "";
            string street1     = "";
            string street2     = "";
            string city        = "";
            string state       = "";
            string postal_code = "";
            string country     = "";
            string phone       = "";
            //Double new_total_rate = 0.00;
            AddressType shipToAddress = new AddressType();
            if (ecMethod != null && ecMethod == "ShorcutExpressCheckout")
            {
                // Get parameters from index page (shorcut express checkout)
                item_name     = Request.Form["item_name"];
                item_id       = Request.Form["item_id"];
                item_desc     = Request.Form["item_desc"];
                item_quantity = Request.Form["item_quantity"];
                item_amount   = Request.Form["item_amount"];

                total_amount            = Request.Form["total_amount"];
                currency_code           = Request.Form["currency_code_type"];
                payment_type            = Request.Form["payment_type"];
                Session["Total_Amount"] = total_amount;

                roundeditmamt = (Math.Round(double.Parse(item_amount), 2)).ToString();
                roundedtotal  = (Math.Round(double.Parse(total_amount), 2)).ToString();
            }
            else if (ecMethod != null && ecMethod == "MarkExpressCheckout")
            {
                // Get parameters from mark ec page
                //shipping_rate = Request.Form["shipping_method"].ToString();

                item_name     = Request.Form["item_name"];
                item_id       = Request.Form["item_id"];
                item_desc     = Request.Form["item_desc"];
                item_quantity = Request.Form["item_quantity"];
                item_amount   = Request.Form["item_amount"];
                //tax_amount = Request.Form["tax_amount"];
                //shipping_amount = Request.Form["shipping_amount"];
                //handling_amount = Request.Form["handling_amount"];
                //shipping_discount_amount = Request.Form["shipping_discount_amount"];
                //insurance_amount = Request.Form["insurance_amount"];
                total_amount  = Request.Form["total_amount"];
                currency_code = Request.Form["currency_code"];
                payment_type  = Request.Form["payment_type"];

                first_name  = Request.Form["FIRST_NAME"];
                last_name   = Request.Form["LAST_NAME"];
                street1     = Request.Form["STREET_1"];
                street2     = Request.Form["STREET_2"];
                city        = Request.Form["CITY"];
                state       = Request.Form["STATE"];
                postal_code = Request.Form["POSTAL_CODE"];
                country     = Request.Form["COUNTRY"];
                phone       = Request.Form["PHONE"];

                roundeditmamt = (Math.Round(double.Parse(item_amount), 2)).ToString();
                roundedtotal  = (Math.Round(double.Parse(total_amount), 2)).ToString();

                // Set the details of new shipping address
                //shipToAddress.Name = first_name + " " + last_name;
                //shipToAddress.Street1 = street1;
                //if (!street2.Equals(""))
                //{
                //    shipToAddress.Street2 = street2;
                //}
                //shipToAddress.CityName = city;
                //shipToAddress.StateOrProvince = state;
                //string countrycode = country;
                //CountryCodeType countryCodeType = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), countrycode, true);
                //shipToAddress.Country = countryCodeType;
                //shipToAddress.PostalCode = postal_code;
                //if (!phone.Equals(""))
                //{
                //    shipToAddress.Phone = phone;
                //}

                //Double total_rate = Convert.ToDouble(total_amount);
                //Double old_shipping_rate = Convert.ToDouble(shipping_amount);
                //Double new_shipping_rate = Convert.ToDouble(shipping_rate);

                // Calculate new order total based on shipping method selected
                //new_total_rate = total_rate - old_shipping_rate + new_shipping_rate;
                //Session["Total_Amount"] = new_total_rate.ToString();
                //total_amount = new_total_rate.ToString();
                //shipping_amount = new_shipping_rate.ToString();
            }

            Session["SellerEmail"] = SellerEmail;
            CurrencyCodeType currencyCode_Type = (CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), currency_code, true);
            Session["currency_code_type"] = currencyCode_Type;
            PaymentActionCodeType payment_ActionCode_Type = (PaymentActionCodeType)Enum.Parse(typeof(PaymentActionCodeType), payment_type, true);
            Session["payment_action_type"] = payment_ActionCode_Type;
            // SetExpressCheckoutRequestDetailsType object
            SetExpressCheckoutRequestDetailsType setExpressCheckoutRequestDetails = new SetExpressCheckoutRequestDetailsType();
            // (Required) URL to which the buyer's browser is returned after choosing to pay with PayPal.
            setExpressCheckoutRequestDetails.ReturnURL = ReturnUrl;
            //(Required) URL to which the buyer is returned if the buyer does not approve the use of PayPal to pay you
            setExpressCheckoutRequestDetails.CancelURL = CancelUrl;
            // A URL to your logo image. Use a valid graphics format, such as .gif, .jpg, or .png
            setExpressCheckoutRequestDetails.cppLogoImage = LogoUrl;
            // To display the border in your principal identifying color, set the "cppCartBorderColor" parameter to the 6-digit hexadecimal value of that color
            // setExpressCheckoutRequestDetails.cppCartBorderColor = "0000CD";

            //Item details
            PaymentDetailsItemType itemDetails = new PaymentDetailsItemType();
            itemDetails.Name        = item_name;
            itemDetails.Amount      = new BasicAmountType(currencyCode_Type, roundeditmamt);
            itemDetails.Quantity    = Convert.ToInt32(item_quantity);
            itemDetails.Description = item_desc;
            itemDetails.Number      = item_id;

            //Add more items if necessary by using the class 'PaymentDetailsItemType'

            // Payment Information
            List <PaymentDetailsType> paymentDetailsList = new List <PaymentDetailsType>();

            PaymentDetailsType paymentDetails = new PaymentDetailsType();
            paymentDetails.PaymentAction = payment_ActionCode_Type;
            paymentDetails.ItemTotal     = new BasicAmountType(currencyCode_Type, roundeditmamt);//item amount
            //paymentDetails.TaxTotal = new BasicAmountType(currencyCode_Type, tax_amount); //tax amount;
            //paymentDetails.ShippingTotal = new BasicAmountType(currencyCode_Type, shipping_amount); //shipping amount
            //paymentDetails.HandlingTotal = new BasicAmountType(currencyCode_Type, handling_amount); //handling amount
            //paymentDetails.ShippingDiscount = new BasicAmountType(currencyCode_Type, shipping_discount_amount); //shipping discount
            //paymentDetails.InsuranceTotal = new BasicAmountType(currencyCode_Type, insurance_amount); //insurance amount
            paymentDetails.OrderTotal = new BasicAmountType(currencyCode_Type, roundedtotal); // order total amount

            paymentDetails.PaymentDetailsItem.Add(itemDetails);

            // Unique identifier for the merchant.
            SellerDetailsType sellerDetails = new SellerDetailsType();
            sellerDetails.PayPalAccountID = SellerEmail;
            paymentDetails.SellerDetails  = sellerDetails;

            if (ecMethod != null && ecMethod == "MarkExpressCheckout")
            {
                paymentDetails.ShipToAddress = shipToAddress;
            }
            paymentDetailsList.Add(paymentDetails);
            setExpressCheckoutRequestDetails.PaymentDetails = paymentDetailsList;

            // Collect Shipping details if MARK express checkout

            SetExpressCheckoutReq         setExpressCheckout        = new SetExpressCheckoutReq();
            SetExpressCheckoutRequestType setExpressCheckoutRequest = new SetExpressCheckoutRequestType(setExpressCheckoutRequestDetails);
            setExpressCheckout.SetExpressCheckoutRequest = setExpressCheckoutRequest;

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

            // API call
            // Invoke the SetExpressCheckout method in service wrapper object
            responseSetExpressCheckoutResponseType = service.SetExpressCheckout(setExpressCheckout);

            if (responseSetExpressCheckoutResponseType != null)
            {
                // Response envelope acknowledgement
                string acknowledgement = "SetExpressCheckout API Operation - ";
                acknowledgement += responseSetExpressCheckoutResponseType.Ack.ToString();
                //logger.Debug(acknowledgement + "\n");
                System.Diagnostics.Debug.WriteLine(acknowledgement + "\n");
                // # Success values
                if (responseSetExpressCheckoutResponseType.Ack.ToString().Trim().ToUpper().Equals("SUCCESS"))
                {
                    // # Redirecting to PayPal for authorization
                    // Once you get the "Success" response, needs to authorise the
                    // transaction by making buyer to login into PayPal. For that,
                    // need to construct redirect url using EC token from response.
                    // Express Checkout Token
                    string EcToken = responseSetExpressCheckoutResponseType.Token;
                    //logger.Info("Express Checkout Token : " + EcToken + "\n");
                    System.Diagnostics.Debug.WriteLine("Express Checkout Token : " + EcToken + "\n");
                    // Store the express checkout token in session to be used in GetExpressCheckoutDetails & DoExpressCheckout API operations
                    Session["EcToken"] = EcToken;
                    Response.Redirect(RedirectUrl + HttpUtility.UrlEncode(EcToken), false);
                    Context.ApplicationInstance.CompleteRequest();
                }
                // # Error Values
                else
                {
                    List <ErrorType> errorMessages = responseSetExpressCheckoutResponseType.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);
        }
    }