Beispiel #1
0
        // GET: PayPal
        public ActionResult Index(int? id)
        {
            

            Bids bid = db.Bids.Find(id);
            ReceiverList receiverList = new ReceiverList();
            receiverList.receiver = new List<Receiver>();
            Receiver receiver = new Receiver(bid.bid); 
            var query = from v in db.Ventures where v.Id == bid.ventureID select v.investorID;
            string receiverID = query.ToList().ElementAt(0);
            ApplicationUser recvUser = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(receiverID.ToString());
            receiver.email = recvUser.Email;
            receiverList.receiver.Add(receiver);
            
            RequestEnvelope requestEnvelope = new RequestEnvelope("en_US");
            string actionType = "PAY";
           
            string successUrl = "http://"+System.Web.HttpContext.Current.Request.Url.Authority + "/PayPal/SuccessView/{0}";
            string failureUrl = "http://"+System.Web.HttpContext.Current.Request.Url.Authority + "/PayPal/FailureView/{0}";
            successUrl = String.Format(successUrl, id);
            failureUrl = String.Format(failureUrl, id);
            string returnUrl = successUrl;
            string cancelUrl = failureUrl;

            string currencyCode = "USD";
            PayRequest payRequest = new PayRequest(requestEnvelope, actionType, cancelUrl, currencyCode, receiverList, returnUrl);
            payRequest.ipnNotificationUrl = "http://replaceIpnUrl.com";

            Dictionary<string, string> sdkConfig = new Dictionary<string, string>();
            sdkConfig.Add("mode", "sandbox");
            sdkConfig.Add("account1.apiUsername", "mattjheller-facilitator_api1.yahoo.com"); //PayPal.Account.APIUserName
            sdkConfig.Add("account1.apiPassword", "DG6GB55TRBWLESWG"); //PayPal.Account.APIPassword
            sdkConfig.Add("account1.apiSignature", "AFcWxV21C7fd0v3bYYYRCpSSRl31AafAKKwBsAp2EBV9PExGkablGWhj"); //.APISignature
            sdkConfig.Add("account1.applicationId", "APP-80W284485P519543T"); //.ApplicatonId

            AdaptivePaymentsService adaptivePaymentsService = new AdaptivePaymentsService(sdkConfig);
            PayResponse payResponse = adaptivePaymentsService.Pay(payRequest);
            ViewData["paykey"] = payResponse.payKey;
            //string payKey = payResponse.payKey; ////////
            //string paymentExecStatus = payResponse.paymentExecStatus;
            //string payURL = String.Format("https://www.sandbox.paypal.com/webscr?cmd=_ap-payment&paykey={0}", payKey);
            
            return View();
        }
    // # Payment
    public PayRequest Payment()
    {
        // # PayRequest
        // The code for the language in which errors are returned
        RequestEnvelope envelopeRequest = new RequestEnvelope();
        envelopeRequest.errorLanguage = "en_US";

        List<Receiver> listReceiver = new List<Receiver>();

        // Amount to be credited to the receiver's account
        Receiver receive = new Receiver(Convert.ToDecimal("4.00"));

        // A receiver's email address
        receive.email = "*****@*****.**";
        listReceiver.Add(receive);
        ReceiverList listOfReceivers = new ReceiverList(listReceiver);

        // PayRequest which takes mandatory params:
        //  
        // * `Request Envelope` - Information common to each API operation, such
        // as the language in which an error message is returned.
        // * `Action Type` - The action for this request. Possible values are:
        // * PAY - Use this option if you are not using the Pay request in
        // combination with ExecutePayment.
        // * CREATE - Use this option to set up the payment instructions with
        // SetPaymentOptions and then execute the payment at a later time with
        // the ExecutePayment.
        // * PAY_PRIMARY - For chained payments only, specify this value to delay
        // payments to the secondary receivers; only the payment to the primary
        // receiver is processed.
        // * `Cancel URL` - URL to redirect the sender's browser to after
        // canceling the approval for a payment; it is always required but only
        // used for payments that require approval (explicit payments)
        // * `Currency Code` - The code for the currency in which the payment is
        // made; you can specify only one currency, regardless of the number of
        // receivers
        // * `Recevier List` - List of receivers
        // * `Return URL` - URL to redirect the sender's browser to after the
        // sender has logged into PayPal and approved a payment; it is always
        // required but only used if a payment requires explicit approval
        PayRequest requestPay = new PayRequest(envelopeRequest, "PAY", "http://localhost/cancel", "USD", listOfReceivers, "http://localhost/return");
        return requestPay;
    }
 /**
  	  * Constructor with arguments
  	  */
 public RefundRequest(RequestEnvelope requestEnvelope)
 {
     this.requestEnvelope = requestEnvelope;
 }
        public ActionResult GetPaypalPreapprovalCancel()
        {
            var api = GoPlayApi.Instance;

            var paypalPreapproval = api.FindPaypalPreapproval(true).Data.SingleOrDefault();
            if (paypalPreapproval != null)
            {
                var headers = PaypalHelper.GetHeader();

                RequestEnvelope requestEnvelope = new RequestEnvelope("en_US");

                CancelPreapprovalRequest cancelPreapprovalRequest = new CancelPreapprovalRequest
                {
                    requestEnvelope = requestEnvelope,
                    preapprovalKey = paypalPreapproval.preapproval_key
                };


                AdaptivePaymentsService adaptivePaymentsService = new AdaptivePaymentsService(headers);
                CancelPreapprovalResponse cancelPreapprovalResponse = adaptivePaymentsService.CancelPreapproval(cancelPreapprovalRequest);
                if (cancelPreapprovalResponse.responseEnvelope.ack.HasValue && cancelPreapprovalResponse.responseEnvelope.ack.Value.ToString().ToLower() == "success")
                {
                    paypalPreapproval.is_active = false;
                    api.UpdatePaypalPreapproval(paypalPreapproval.id, false);
                    this.Flash("Transaction is successful.", FlashLevel.Success);
                    return Json(new { success = true });
                }
                else
                {
                    return Json(new { error = cancelPreapprovalResponse.error[0].message });
                }
            }
            return RedirectToAction("index", "paypal");
        }
    // # ConvertCurrency API Operation  
    // The ConvertCurrency API operation to request the current foreign exchange (FX) rate for a specific amount and currency      
    public ConvertCurrencyResponse ConvertCurrencyAPIOperation()
    {
        // Create the ConvertCurrencyResponse object
        ConvertCurrencyResponse responseConvertCurrency = new ConvertCurrencyResponse();

        try
        {
            // # ConvertCurrencyRequest 
            // The ConvertCurrencyRequest message enables you to have your  
            // application get an estimated exchange rate for a list of amounts 
            // This API operation does not affect PayPal balances   
            // The code for the language in which errors are returned
            RequestEnvelope envelopeRequest = new RequestEnvelope();
            envelopeRequest.errorLanguage = "en_US";

            // CurrencyTypeList which takes two arguments:  
            //  
            // * `CurrencyCodeType` - The currency code. Allowable values are:  
            // * Australian Dollar - AUD    
            // * Brazilian Real - BRL   
            // `Note:   
            // The Real is supported as a payment currency and currency balance only for Brazilian PayPal accounts.`  
            //  
            // * Canadian Dollar - CAD  
            // * Czech Koruna - CZK 
            // * Danish Krone - DKK 
            // * Euro - EUR 
            // * Hong Kong Dollar - HKD 
            // * Hungarian Forint - HUF 
            // * Israeli New Sheqel - ILS   
            // * Japanese Yen - JPY 
            // * Malaysian Ringgit - MYR    
            // `Note:   
            // The Ringgit is supported as a payment currency and currency balance only for Malaysian PayPal accounts.`
            //  
            // * Mexican Peso - MXN 
            // * Norwegian Krone - NOK  
            // * New Zealand Dollar - NZD   
            // * Philippine Peso - PHP  
            // * Polish Zloty - PLN 
            // * Pound Sterling - GBP   
            // * Singapore Dollar - SGD 
            // * Swedish Krona - SEK    
            // * Swiss Franc - CHF  
            // * Taiwan New Dollar - TWD    
            // * Thai Baht - THB    
            // * Turkish Lira - TRY 
            // `Note:   
            // The Turkish Lira is supported as a payment currency and currency balance only for Turkish PayPal accounts.`
            //  
            // * U.S. Dollar - USD  
            // * `amount`   
            List<CurrencyType> currencyTypeList = new List<CurrencyType>();
            CurrencyType currency = new CurrencyType("USD", Convert.ToDecimal("4.00"));
            currencyTypeList.Add(currency);
            CurrencyList baseAmountList = new CurrencyList(currencyTypeList);

            // CurrencyCodeList which contains  
            //  
            // * `Currency Code` - Allowable values are:    
            // * Australian Dollar - AUD    
            // * Brazilian Real - BRL   
            // `Note:   
            // The Real is supported as a payment currency and currency balance only for Brazilian PayPal accounts.`  
            // * Canadian Dollar - CAD  
            // * Czech Koruna - CZK 
            // * Danish Krone - DKK 
            // * Euro - EUR 
            // * Hong Kong Dollar - HKD 
            // * Hungarian Forint - HUF 
            // * Israeli New Sheqel - ILS   
            // * Japanese Yen - JPY 
            // * Malaysian Ringgit - MYR    
            // `Note:   
            // The Ringgit is supported as a payment currency and currency balance  only for Malaysian PayPal accounts.` 
            // * Mexican Peso - MXN 
            // * Norwegian Krone - NOK  
            // * New Zealand Dollar - NZD   
            // * Philippine Peso - PHP  
            // * Polish Zloty - PLN 
            // * Pound Sterling - GBP   
            // * Singapore Dollar - SGD 
            // * Swedish Krona - SEK    
            // * Swiss Franc - CHF  
            // * Taiwan New Dollar - TWD    
            // * Thai Baht - THB    
            // * Turkish Lira - TRY 
            // `Note:   
            // The Turkish Lira is supported as a payment currency and currency balance only for Turkish PayPal accounts.`   
            //  
            // * U.S. Dollar - USD  
            List<String> currencyCodeList = new List<String>();
            currencyCodeList.Add("GBP");
            CurrencyCodeList convertToCurrencyList = new CurrencyCodeList(currencyCodeList);

            // ConvertCurrencyRequest which takes params:   
            //
            // * `Request Envelope` - Information common to each API operation, such    
            // as the language in which an error message is returned    
            // * `BaseAmountList` - A list of amounts with associated currencies to 
            // be converted.    
            // * `ConvertToCurrencyList` - A list of currencies to convert to.  
            ConvertCurrencyRequest requestConvertCurrency = new ConvertCurrencyRequest(envelopeRequest, baseAmountList, convertToCurrencyList);
            
            // # Create the service wrapper object to make the API call   
            AdaptivePaymentsService service = new AdaptivePaymentsService();

            // # API call   
            // Invoke the ConvertCurrency method in service wrapper object  
            responseConvertCurrency = service.ConvertCurrency(requestConvertCurrency);

            if (responseConvertCurrency != null)
            {
                // Response envelope acknowledgement
                string acknowledgement = "ConvertCurrency API operation - ";
                acknowledgement += responseConvertCurrency.responseEnvelope.ack.ToString();
                logger.Info(acknowledgement + "\n");
                Console.WriteLine(acknowledgement + "\n");
 
                // # Success values   
                if (responseConvertCurrency.responseEnvelope.ack.ToString().Trim().ToUpper().Equals("SUCCESS"))
                {
                    if (responseConvertCurrency.estimatedAmountTable.currencyConversionList != null
                        && responseConvertCurrency.estimatedAmountTable.currencyConversionList.Count > 0)
                    {
                        IEnumerator<CurrencyConversionList> iterator = responseConvertCurrency.estimatedAmountTable.currencyConversionList.GetEnumerator();

                        while (iterator.MoveNext())
                        {
                            CurrencyConversionList currencyConversion = iterator.Current;
                            logger.Info("Amount to be Converted : " + currencyConversion.baseAmount.amount + currencyConversion.baseAmount.code + "\n");
                            Console.WriteLine("Amount to be Converted : " + currencyConversion.baseAmount.amount + currencyConversion.baseAmount.code + "\n");

                            IEnumerator<CurrencyType> currencyIterator = currencyConversion.currencyList.currency.GetEnumerator();

                            while (currencyIterator.MoveNext())
                            {
                                CurrencyType currencyType = currencyIterator.Current;
                                logger.Info("Converted amount : " + currencyType.amount + currencyType.code + "\n");
                                Console.WriteLine("Converted amount : " + currencyType.amount + currencyType.code + "\n");
                            }
                        }
                    }
                }
                // # Error Values 
                else
                {
                    List<ErrorData> errorMessages = responseConvertCurrency.error;
                    foreach (ErrorData error in errorMessages)
                    {
                        logger.Debug("API Error Message : " + error.message);
                        Console.WriteLine("API Error Message : " + error.message + "\n");
                    }
                }
            }
        }
        // # Exception log    
        catch (System.Exception ex)
        {
            // Log the exception message       
            logger.Debug("Error Message : " + ex.Message);
            Console.WriteLine("Error Message : " + ex.Message);
        }

        return responseConvertCurrency;
    }
 /**
  	  * Constructor with arguments
  	  */
 public CancelPreapprovalRequest(RequestEnvelope requestEnvelope, string preapprovalKey)
 {
     this.requestEnvelope = requestEnvelope;
     this.preapprovalKey = preapprovalKey;
 }
 /**
  	  * Constructor with arguments
  	  */
 public PreapprovalDetailsRequest(RequestEnvelope requestEnvelope, string preapprovalKey)
 {
     this.requestEnvelope = requestEnvelope;
     this.preapprovalKey = preapprovalKey;
 }
        public PreapprovalResponse PaypalPreapprovalRequest(paypal_preapproval obj)
        {
            var headers = PaypalHelper.GetHeader();

            RequestEnvelope requestEnvelope = new RequestEnvelope("en_US");

            PreapprovalRequest payRequest = new PreapprovalRequest
            {
                requestEnvelope = requestEnvelope,
                returnUrl = ConfigurationManager.AppSettings["PAYPAL_CONFIRM_RETURN_URL"] + obj.flag,
                cancelUrl = ConfigurationManager.AppSettings["PAYPAL_CONFIRM_CANCEL_URL"],
                pinType = "NOT_REQUIRED",
                currencyCode = ConfigurationManager.AppSettings["DEFAULT_PAYPAL_CURRENCY"],
                maxAmountPerPayment = obj.max_amount_per_payment,
                maxNumberOfPayments = obj.max_number_of_payments,
                maxTotalAmountOfAllPayments = obj.max_total_amount_of_all_payments,
                senderEmail = obj.sender_email,
                startingDate = obj.starting_date.ToString("yyyy-MM-dd'T'HH:mm:ss.000zzz"),
                endingDate = obj.ending_date.ToString("yyyy-MM-dd'T'HH:mm:ss.000zzz")
            };


            AdaptivePaymentsService adaptivePaymentsService = new AdaptivePaymentsService(headers);
            PreapprovalResponse payResponse = adaptivePaymentsService.Preapproval(payRequest);
            return payResponse;
        }
 /**
  	  * Constructor with arguments
  	  */
 public GetUserLimitsRequest(RequestEnvelope requestEnvelope, AccountIdentifier user, string country, string currencyCode, List<string> limitType)
 {
     this.requestEnvelope = requestEnvelope;
     this.user = user;
     this.country = country;
     this.currencyCode = currencyCode;
     this.limitType = limitType;
 }
        // # PreapprovalDetails API Operation
        // Use the PreapprovalDetails API operation to obtain information about an agreement between you and a sender for making payments on the sender’s behalf.
        public PreapprovalDetailsResponse PreapprovalDetailsAPIOperation(string preapprovalKey)
        {
            // Create the PreapprovalDetailsResponse object
            var responsePreapprovalDetails = new PreapprovalDetailsResponse();

            try
            {
                // # PreapprovaDetailslRequest
                // The code for the language in which errors are returned
                var envelopeRequest = new RequestEnvelope {errorLanguage = "en_US"};

                // PreapprovalDetailsRequest object which takes mandatory params:
                //
                // * `Request Envelope` - Information common to each API operation, such
                // as the language in which an error message is returned.
                // * `Preapproval Key` - A preapproval key that identifies the
                // preapproval for which you want to retrieve details. The preapproval
                // key is returned in the PreapprovalResponse message.
                var preapprovDetailsRequest = new PreapprovalDetailsRequest(
                envelopeRequest, preapprovalKey);

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

                // # API call
                // Invoke the PreapprovalDetails method in service wrapper object
                responsePreapprovalDetails = service.PreapprovalDetails(preapprovDetailsRequest);

                if (responsePreapprovalDetails != null)
                {

                    // # Success values
                    if (responsePreapprovalDetails.responseEnvelope != null && responsePreapprovalDetails.responseEnvelope.ack.ToString().Trim().ToUpper().Equals("SUCCESS"))
                    {
                        // First date for which the preapproval is valid.
                        Console.WriteLine("Starting Date : " + responsePreapprovalDetails.startingDate + "\n");
                    }
                    // # Error Values
                    else
                    {
                        List<ErrorData> errorMessages = responsePreapprovalDetails.error;
                        foreach (ErrorData error in errorMessages)
                        {
                            Console.WriteLine("API Error Message : " + error.message + "\n");
                        }
                    }
                }
            }
            // # Exception log
            catch (Exception ex)
            {
                // Log the exception message
                Console.WriteLine("Error Message : " + ex.Message);
            }
            return responsePreapprovalDetails;
        }
 /**
  	  * Constructor with arguments
  	  */
 public GetAllowedFundingSourcesRequest(RequestEnvelope requestEnvelope, string key)
 {
     this.requestEnvelope = requestEnvelope;
     this.key = key;
 }
        /// <summary>
        /// Handles Preapproval API calls
        /// </summary>
        /// <param name="contextHttp"></param>
        private void Preapproval(HttpContext contextHttp)
        {
            NameValueCollection parameters = contextHttp.Request.Params;
            PreapprovalRequest request = new PreapprovalRequest();

            RequestEnvelope requestEnvelope = new RequestEnvelope("en_US");
            request.requestEnvelope = requestEnvelope;

            // (Optional) Sender's email address. Maximum length: 127 characters
            if (parameters["senderEmail"] != null && parameters["senderEmail"].Trim() != string.Empty)
            {
                request.senderEmail = "*****@*****.**";
            }

            // (Optional) The day of the month on which a monthly payment is to be made.
            // Allowable values are numbers between 0 and 31.
            // A number between 1 and 31 indicates the date of the month.
            // Specifying 0 indicates that payment can be made on any day of the month. 
            if (parameters["dateOfMonth"] != null && parameters["dateOfMonth"].Trim() != string.Empty)
            {
                request.dateOfMonth = Convert.ToInt32(parameters["dateOfMonth"]);
            }

            // (Optional) The day of the week that a weekly payment is to be made. Allowable values are: 
            // NO_DAY_SPECIFIED
            // SUNDAY
            // MONDAY
            // TUESDAY
            // WEDNESDAY
            // THURSDAY
            // FRIDAY
            // SATURDAY
            if (parameters["dayOfWeek"] != null && parameters["dayOfWeek"].Trim() != string.Empty)
            {
                request.dayOfWeek = (PayPal.AdaptivePayments.Model.DayOfWeek)
                        Enum.Parse(typeof(PayPal.AdaptivePayments.Model.DayOfWeek), parameters["dayOfWeek"]);
            }

            // (Optional) Whether to display the maximum total amount of this preapproval. It is one of the following values:
            // TRUE – Display the amount
            // FALSE – Do not display the amount (default)
            if (parameters["displayMaxTotalAmount"] != null && parameters["displayMaxTotalAmount"].Trim() != string.Empty)
            {
                request.displayMaxTotalAmount = Convert.ToBoolean(parameters["displayMaxTotalAmount"]);
            }

            // (Optional) The URL to which you want all IPN messages for this preapproval to be sent.
            // This URL supersedes the IPN notification URL in your profile.
            // Maximum length: 1024 characters
            if (parameters["ipnNotificationURL"] != null && parameters["ipnNotificationURL"].Trim() != string.Empty)
            {
                request.ipnNotificationUrl = parameters["ipnNotificationURL"];
            }

            // (Optional) The preapproved maximum amount per payment.
            // It cannot exceed the preapproved maximum total amount of all payments. 
            if (parameters["maxAmountPerPayment"] != null && parameters["maxAmountPerPayment"].Trim() != string.Empty)
            {
                request.maxAmountPerPayment = Convert.ToDecimal(parameters["maxAmountPerPayment"]);
            }

            // (Optional) The preapproved maximum number of payments.
            // It cannot exceed the preapproved maximum total number of all payments. 
            if (parameters["maxNumberOfPayments"] != null && parameters["maxNumberOfPayments"].Trim() != string.Empty)
            {
                request.maxNumberOfPayments = Convert.ToInt32(parameters["maxNumberOfPayments"]);
            }
            
            // (Optional) The preapproved maximum number of all payments per period. 
            // You must specify a value unless you have specific permission from PayPal.
            if (parameters["maxNumberOfPaymentsPerPeriod"] != null && parameters["maxNumberOfPaymentsPerPeriod"].Trim() != string.Empty)
            {
                request.maxNumberOfPaymentsPerPeriod = Convert.ToInt32(parameters["maxNumberOfPaymentsPerPeriod"]);
            }

            // (Optional) The preapproved maximum total amount of all payments.
            // It cannot exceed $2,000 USD or its equivalent in other currencies.
            if (parameters["totalAmountOfAllPayments"] != null && parameters["totalAmountOfAllPayments"].Trim() != string.Empty)
            {
                request.maxTotalAmountOfAllPayments = Convert.ToDecimal(parameters["totalAmountOfAllPayments"]);
            }

            // (Optional) The payment period. It is one of the following values:
            // NO_PERIOD_SPECIFIED
            // DAILY – Each day
            // WEEKLY – Each week
            // BIWEEKLY – Every other week
            // SEMIMONTHLY – Twice a month
            // MONTHLY – Each month
            // ANNUALLY – Each year
            if (parameters["paymentPeriod"] != null && parameters["paymentPeriod"].Trim() != string.Empty)
            {
                request.paymentPeriod = parameters["paymentPeriod"];
            }

            // (Optional) Sender's email address. If not specified,
            // the email address of the sender who logs in to approve
            // the request becomes the email address associated with the preapproval key.
            // Maximum length: 127 characters
            if (parameters["senderEmail"] != null && parameters["senderEmail"].Trim() != string.Empty)
            {
                request.senderEmail = parameters["senderEmail"];
            }

            // The code for the currency in which the payment is made; 
            // you can specify only one currency, regardless of the number of receivers.
            if (parameters["currencyCode"] != null && parameters["currencyCode"].Trim() != string.Empty)
            {
                request.currencyCode = parameters["currencyCode"];
            }

            // URL to redirect the sender's browser to after canceling the preapproval 
            if (parameters["cancelURL"] != null && parameters["cancelURL"].Trim() != string.Empty)
            {
                request.cancelUrl = parameters["cancelURL"];
            }
            
            // URL to redirect the sender's browser
            // to after the sender has logged into PayPal and confirmed the preapproval.
            if (parameters["returnURL"] != null && parameters["returnURL"].Trim() != string.Empty)
            {
                request.returnUrl = parameters["returnURL"];
            }

            request.requestEnvelope = requestEnvelope;

            // First date for which the preapproval is valid. 
            // It cannot be before today's date or after the ending date.
            if (parameters["startingDate"] != null && parameters["startingDate"].Trim() != string.Empty)
            {
                request.startingDate = parameters["startingDate"];
            }

            // Last date for which the preapproval is valid. 
            // It cannot be later than one year from the starting date. 
            // Contact PayPal if you do not want to specify an ending date.
            if (parameters["endingDate"] != null && parameters["endingDate"].Trim() != string.Empty)
            {
                request.endingDate = parameters["endingDate"];
            }

            AdaptivePaymentsService service = null;
            PreapprovalResponse response = null;
            try
            {
                // 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();

                // Creating service wrapper object to make an API call and loading
                // configuration map for your credentials and endpoint
                service = new AdaptivePaymentsService(configurationMap);
                response = service.Preapproval(request);
            }
            catch (System.Exception ex)
            {
                contextHttp.Response.Write(ex.Message);
                return;
            }

            Dictionary<string, string> responseValues = new Dictionary<string, string>();
            string redirectUrl = null;

            if (!response.responseEnvelope.ack.ToString().Trim().ToUpper().Equals(AckCode.FAILURE.ToString()) && !response.responseEnvelope.ack.ToString().Trim().ToUpper().Equals(AckCode.FAILUREWITHWARNING.ToString()))
            {
                // A preapproval key that identifies the preapproval requested.
                responseValues.Add("Preapproval Key", response.preapprovalKey);
                redirectUrl = ConfigurationManager.AppSettings["PAYPAL_REDIRECT_URL"] + "_ap-preapproval&preapprovalkey=" + response.preapprovalKey;
                Session["preapprovalKey"] = response.preapprovalKey;
            }

            responseValues.Add("Acknowledgement", response.responseEnvelope.ack.ToString().Trim().ToUpper());

            Display(contextHttp, "Preapproval", "AdaptivePayments", responseValues, service.getLastRequest(), service.getLastResponse(), response.error, redirectUrl);
        }
        // # Preapproval API Operation
        // Use the Preapproval API operation to set up an agreement between yourself and a sender for making payments on the sender’s behalf. You set up a preapprovals for a specific maximum amount over a specific period of time and, optionally, by any of the following constraints: the number of payments, a maximum per-payment amount, a specific day of the week or the month, and whether or not a PIN is required for each payment request.
        public PreapprovalResponse GeneratePreapproval(Preapproval preapproval)
        {
            // Create the PreapprovalResponse object
            var responsePreapproval = new PreapprovalResponse();

            try
            {
                // # PreapprovalRequest
                // The code for the language in which errors are returned
                var envelopeRequest = new RequestEnvelope {errorLanguage = "en_US"};

                const string pattern = "yyyy-MM-dd";

                var requestPreapproval = new PreapprovalRequest(envelopeRequest, preapproval.CancelURL, "USD", preapproval.ReturnURL, "2013-07-15")
                    {ipnNotificationUrl = preapproval.IPNHost};

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

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

                // # API call
                // Invoke the Preapproval method in service wrapper object
                responsePreapproval = service.Preapproval(requestPreapproval);

                if (responsePreapproval != null)
                {
                    // Response envelope acknowledgement
                    string acknowledgement = "Preapproval API Operation - ";
                    acknowledgement += responsePreapproval.responseEnvelope.ack.ToString();
                    Console.WriteLine(acknowledgement + "\n");

                    // # Success values
                    if (responsePreapproval.responseEnvelope != null && responsePreapproval.responseEnvelope.ack.ToString().Trim().ToUpper().Equals("SUCCESS"))
                    {
                        var preApprovalDetails = PreapprovalDetailsAPIOperation(responsePreapproval.preapprovalKey);
                        _preApprovalService = DependencyResolver.Current.GetService<IPreApprovalService>();
                        _preApprovalService.SaveOrUpdate(new PreApproval
                            {
                                Approved =  preApprovalDetails.approved != null && preApprovalDetails.approved.Value,
                                ContractStartDate = DateTime.Parse(preApprovalDetails.startingDate),
                                ContractEndDate = DateTime.Parse(preApprovalDetails.endingDate),
                                PreApprovalKey = responsePreapproval.preapprovalKey,
                                Userd = UserProfile.Current.UserId
                            });
                    }
                    // # Error Values
                    else
                    {
                        List<ErrorData> errorMessages = responsePreapproval.error;
                        foreach (ErrorData error in errorMessages)
                        {
                            Console.WriteLine("API Error Message : " + error.message + "\n");
                        }
                    }
                }
            }
            // # Exception log
            catch (Exception ex)
            {
                // Log the exception message
                Console.WriteLine("Error Message : " + ex.Message);
            }
            return responsePreapproval;
        }
        /// <summary>
        /// Handles Deferred Pay API calls
        /// </summary>
        /// <param name="contextHttp"></param>
        private void DeferredPayment(HttpContext contextHttp)
        {
            NameValueCollection parameters = contextHttp.Request.Params;
            ReceiverList receiverList = new ReceiverList();
            receiverList.receiver = new List<Receiver>();
            PayRequest request = new PayRequest();
            Receiver rec = new Receiver();

            RequestEnvelope requestEnvelope = new RequestEnvelope("en_US");
            request.requestEnvelope = requestEnvelope;

            // (Required) Amount to be paid to the receiver
            if (parameters["amount"] != null && parameters["amount"].Trim() != string.Empty)
            {
                rec.amount = Convert.ToDecimal(parameters["amount"]);
            }
            
            // Receiver's email address. This address can be unregistered with
            // paypal.com. If so, a receiver cannot claim the payment until a PayPal
            // account is linked to the email address. The PayRequest must pass
            // either an email address or a phone number. Maximum length: 127 characters
            if (parameters["mail"] != null && parameters["mail"].Trim() != string.Empty)
            {
                rec.email = parameters["mail"];
            }

            receiverList.receiver.Add(rec);

            ReceiverList receiverlst = new ReceiverList(receiverList.receiver);
            request.receiverList = receiverlst;

            // (Optional) Sender's email address. Maximum length: 127 characters
            if (parameters["senderEmail"] != null && parameters["senderEmail"].Trim() != string.Empty)
            {
                request.senderEmail = parameters["senderEmail"];
            }
            
            // The action for this request. Possible values are: PAY – Use this
            // option if you are not using the Pay request in combination with
            // ExecutePayment. CREATE – Use this option to set up the payment
            // instructions with SetPaymentOptions and then execute the payment at a
            // later time with the ExecutePayment. PAY_PRIMARY – For chained
            // payments only, specify this value to delay payments to the secondary
            // receivers; only the payment to the primary receiver is processed.
            if (parameters["actionType"] != null && parameters["actionType"].Trim() != string.Empty)
            {
                request.actionType = parameters["actionType"];
            }
            
            // URL to redirect the sender's browser to after canceling the approval
            // for a payment; it is always required but only used for payments that
            // require approval (explicit payments)
            if (parameters["cancelURL"] != null && parameters["cancelURL"].Trim() != string.Empty)
            {
                request.cancelUrl = parameters["cancelURL"];
            }

            // The code for the currency in which the payment is made; you can
            // specify only one currency, regardless of the number of receivers
            if (parameters["currencyCode"] != null && parameters["currencyCode"].Trim() != string.Empty)
            {
                request.currencyCode = parameters["currencyCode"];
            }

            // URL to redirect the sender's browser to after the sender has logged
            // into PayPal and approved a payment; it is always required but only
            // used if a payment requires explicit approval
            if (parameters["returnURL"] != null && parameters["returnURL"].Trim() != string.Empty)
            {
                request.returnUrl = parameters["returnURL"];
            }

            request.requestEnvelope = requestEnvelope;
            
            // (Optional) The URL to which you want all IPN messages for this
            // payment to be sent. Maximum length: 1024 characters
            if (parameters["ipnNotificationURL"] != null && parameters["ipnNotificationURL"].Trim() != string.Empty)
            {
                request.ipnNotificationUrl = parameters["ipnNotificationURL"];
            }

            AdaptivePaymentsService service = null;
            PayResponse response = null;
            try
            {
                // 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();

                // Creating service wrapper object to make an API call and loading
                // configuration map for your credentials and endpoint
                service = new AdaptivePaymentsService(configurationMap);

                response = service.Pay(request);
            }
            catch (System.Exception ex)
            {
                contextHttp.Response.Write(ex.Message);
                return;
            }

            Dictionary<string, string> responseValues = new Dictionary<string, string>();
            string redirectUrl = null;

            if (!response.responseEnvelope.ack.ToString().Trim().ToUpper().Equals(AckCode.FAILURE.ToString()) && !response.responseEnvelope.ack.ToString().Trim().ToUpper().Equals(AckCode.FAILUREWITHWARNING.ToString()))
            {
                redirectUrl = ConfigurationManager.AppSettings["PAYPAL_REDIRECT_URL"] + "_ap-payment&paykey=" + response.payKey;

                // The pay key, which is a token you use in other Adaptive Payment APIs 
                // (such as the Refund Method) to identify this payment. 
                // The pay key is valid for 3 hours; the payment must be approved while the 
                // pay key is valid. 
                responseValues.Add("Pay Key", response.payKey);

                // The status of the payment. Possible values are:
                // CREATED – The payment request was received; funds will be transferred once the payment is approved
                // COMPLETED – The payment was successful
                // INCOMPLETE – Some transfers succeeded and some failed for a parallel payment or, for a delayed chained payment, secondary receivers have not been paid
                // ERROR – The payment failed and all attempted transfers failed or all completed transfers were successfully reversed
                // REVERSALERROR – One or more transfers failed when attempting to reverse a payment
                // PROCESSING – The payment is in progress
                // PENDING – The payment is awaiting processing
                responseValues.Add("Payment Execution Status", response.paymentExecStatus);

                if (response.defaultFundingPlan != null && response.defaultFundingPlan.senderFees != null)
                {
                    //Fees to be paid by the sender.
                    responseValues.Add("Sender Fees", response.defaultFundingPlan.senderFees.amount + response.defaultFundingPlan.senderFees.code);
                }
            }

            responseValues.Add("Acknowledgement", response.responseEnvelope.ack.ToString().Trim().ToUpper());

            Display(contextHttp, "DeferredPayment", "AdaptivePayments", responseValues, service.getLastRequest(), service.getLastResponse(), response.error, redirectUrl);
        }
        /// <summary>
        /// Handles Preapproval Pay API calls
        /// </summary>
        /// <param name="contextHttp"></param>
        private void PreapprovalPayment(HttpContext contextHttp)
        {
            NameValueCollection parameters = contextHttp.Request.Params;
            PayRequest request = new PayRequest();
            RequestEnvelope requestEnvelope = new RequestEnvelope("en_US");
            request.requestEnvelope = requestEnvelope;

            List<Receiver> receiverList = new List<Receiver>();
            Receiver sampleReceiver = new Receiver();

            // (Required) Amount to be paid to the receiver
            if (parameters["amount"] != null && parameters["amount"].Trim() != string.Empty)
            {
                sampleReceiver.amount = Convert.ToDecimal(parameters["amount"]);
            }           
            
            // Receiver's email address. This address can be unregistered with
            // paypal.com. If so, a receiver cannot claim the payment until a PayPal
            // account is linked to the email address. The PayRequest must pass
            // either an email address or a phone number. Maximum length: 127 characters
            if (parameters["mail"] != null && parameters["mail"].Trim() != string.Empty)
            {
                sampleReceiver.email = parameters["mail"];
            }   

            receiverList.Add(sampleReceiver);

            ReceiverList receiverlst = new ReceiverList(receiverList);
            request.receiverList = receiverlst;

            // Preapproval key for the approval set up between you and the sender
            if (parameters["preapprovalKey"] != null && parameters["preapprovalKey"].Trim() != string.Empty)
            {
                request.preapprovalKey = parameters["preapprovalKey"];
            } 
                       
            // The action for this request. Possible values are: PAY – Use this
            // option if you are not using the Pay request in combination with
            // ExecutePayment. CREATE – Use this option to set up the payment
            // instructions with SetPaymentOptions and then execute the payment at a
            // later time with the ExecutePayment. PAY_PRIMARY – For chained
            // payments only, specify this value to delay payments to the secondary
            // receivers; only the payment to the primary receiver is processed.
            if (parameters["actionType"] != null && parameters["actionType"].Trim() != string.Empty)
            {
                request.actionType = parameters["actionType"];
            }

            // URL to redirect the sender's browser to after canceling the approval
            // for a payment; it is always required but only used for payments that
            // require approval (explicit payments)            
            if (parameters["cancelURL"] != null && parameters["cancelURL"].Trim() != string.Empty)
            {
                request.cancelUrl = parameters["cancelURL"];
            }
            
            // The code for the currency in which the payment is made; you can
            // specify only one currency, regardless of the number of receivers
            if (parameters["currencyCode"] != null && parameters["currencyCode"].Trim() != string.Empty)
            {
                request.currencyCode = parameters["currencyCode"];
            }
               
            // URL to redirect the sender's browser to after the sender has logged
            // into PayPal and approved a payment; it is always required but only
            // used if a payment requires explicit approval
            if (parameters["returnURL"] != null && parameters["returnURL"].Trim() != string.Empty)
            {
                request.returnUrl = parameters["returnURL"];
            }
            
            // (Optional) The URL to which you want all IPN messages for this
            // payment to be sent. Maximum length: 1024 characters
            if (parameters["ipnNotificationURL"] != null && parameters["ipnNotificationURL"].Trim() != string.Empty)
            {
                request.ipnNotificationUrl = parameters["ipnNotificationURL"];
            }
           
            AdaptivePaymentsService service = null;
            PayResponse response = null;
            try
            {
                // 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();

                // Creating service wrapper object to make an API call and loading
                // configuration map for your credentials and endpoint
                service = new AdaptivePaymentsService(configurationMap);
                response = service.Pay(request);
            }
            catch (System.Exception ex)
            {
                contextHttp.Response.Write(ex.Message);
                return;
            }

            Dictionary<string, string> responseValues = new Dictionary<string, string>();
            string redirectUrl = null;
            responseValues.Add("Acknowledgement", response.responseEnvelope.ack.ToString().Trim().ToUpper());
   
            Display(contextHttp, "PreapprovalPayment", "AdaptivePayments", responseValues, service.getLastRequest(), service.getLastResponse(), response.error, redirectUrl);
        }
    // # Preapproval API Operation 
    // Use the Preapproval API operation to set up an agreement between yourself and a sender for making payments on the sender’s behalf. You set up a preapprovals for a specific maximum amount over a specific period of time and, optionally, by any of the following constraints: the number of payments, a maximum per-payment amount, a specific day of the week or the month, and whether or not a PIN is required for each payment request. 
    public PreapprovalResponse PreapprovalAPIOperation()
    {
        // Create the PreapprovalResponse object
        PreapprovalResponse responsePreapproval = new PreapprovalResponse();

        try
        {
            // # PreapprovalRequest
            // The code for the language in which errors are returned
            RequestEnvelope envelopeRequest = new RequestEnvelope();
            envelopeRequest.errorLanguage = "en_US";

            // PreapprovalRequest takes mandatory params:
            //      
            // * `RequestEnvelope` - Information common to each API operation, such
            // as the language in which an error message is returned.
            // * `Cancel URL` - URL to redirect the sender's browser to after
            // canceling the preapproval
            // * `Currency Code` - The code for the currency in which the payment is
            // made; you can specify only one currency, regardless of the number of
            // receivers
            // * `Return URL` - URL to redirect the sender's browser to after the
            // sender has logged into PayPal and confirmed the preapproval
            // * `Starting Date` - First date for which the preapproval is valid. It
            // cannot be before today's date or after the ending date.
            PreapprovalRequest requestPreapproval = new PreapprovalRequest(envelopeRequest, "http://localhost/cancel", "USD", "http://localhost/return", "2013-12-18");

            // 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        
            requestPreapproval.ipnNotificationUrl = "http://IPNhost";

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

            // # API call
            // Invoke the Preapproval method in service wrapper object
            responsePreapproval = service.Preapproval(requestPreapproval);

            if (responsePreapproval != null)
            {
                // Response envelope acknowledgement
                string acknowledgement = "Preapproval API Operation - ";
                acknowledgement += responsePreapproval.responseEnvelope.ack.ToString();
                logger.Info(acknowledgement + "\n");
                Console.WriteLine(acknowledgement + "\n");

                // # Success values
                if (responsePreapproval.responseEnvelope.ack.ToString().Trim().ToUpper().Equals("SUCCESS"))
                {
                    logger.Info("Preapproval Key : " + responsePreapproval.preapprovalKey + "\n");
                    Console.WriteLine("Preapproval Key : " + responsePreapproval.preapprovalKey + "\n");

                    // Once you get success response, user has to redirect to PayPal
                    // to preapprove the payment. Construct redirectURL as follows,
                    // `redirectURL=https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_ap-preapproval&preapprovalkey="
                    // + responsePreapproval.preapprovalKey;`                    
                }
                // # Error Values
                else
                {
                    List<ErrorData> errorMessages = responsePreapproval.error;
                    foreach (ErrorData error in errorMessages)
                    {
                        logger.Debug("API Error Message : " + error.message);
                        Console.WriteLine("API Error Message : " + error.message + "\n");
                    }
                }
            }
        }
        // # Exception log    
        catch (System.Exception ex)
        {
            // Log the exception message       
            logger.Debug("Error Message : " + ex.Message);
            Console.WriteLine("Error Message : " + ex.Message);
        }
        return responsePreapproval;
    }
 /**
  	  * Constructor with arguments
  	  */
 public ConvertCurrencyRequest(RequestEnvelope requestEnvelope, CurrencyList baseAmountList, CurrencyCodeList convertToCurrencyList)
 {
     this.requestEnvelope = requestEnvelope;
     this.baseAmountList = baseAmountList;
     this.convertToCurrencyList = convertToCurrencyList;
 }
 /**
  	  * Constructor with arguments
  	  */
 public GetPaymentOptionsRequest(RequestEnvelope requestEnvelope, string payKey)
 {
     this.requestEnvelope = requestEnvelope;
     this.payKey = payKey;
 }
 /**
  	  * Constructor with arguments
  	  */
 public ExecutePaymentRequest(RequestEnvelope requestEnvelope, string payKey)
 {
     this.requestEnvelope = requestEnvelope;
     this.payKey = payKey;
 }
        public ActionResult paypalPaymentExecute(string id)
        {
            var api = GoPlayApi.Instance;
            var transaction = api.GetGcoinTransaction(id);
            if (transaction.HasData)
            {
                var headers = PaypalHelper.GetHeader();

                RequestEnvelope requestEnvelope = new RequestEnvelope("en_US");

                ExecutePaymentRequest executePayment = new ExecutePaymentRequest
                {
                    requestEnvelope = requestEnvelope,
                    payKey = transaction.Data.pay_key
                };

                AdaptivePaymentsService adaptivePaymentsService = new AdaptivePaymentsService(headers);
                ExecutePaymentResponse executePaymentResponse = adaptivePaymentsService.ExecutePayment(executePayment);

                if (executePaymentResponse.responseEnvelope.ack.Value.ToString().ToLower() == "success" && executePaymentResponse.paymentExecStatus == "COMPLETED" && executePaymentResponse.error[0].errorId.Value.ToString() == "580022")
                {
                    transaction.Data.status = "success";
                    //update trans

                    api.UpdateGCoinTransaction(transaction.Data);

                    logger.Fatal("update payment success");

                    this.Flash("Transaction is successful.", FlashLevel.Success);
                    return Json(new { success = true });
                }
                else
                {
                    var error_msg = executePaymentResponse.error[0].message;
                    logger.Fatal(error_msg);

                    this.Flash(error_msg, FlashLevel.Error);
                }
                return RedirectToAction("gcoinTransactionIndex", "paypal");
            }
            return Json(new { success = false });
        }
 /**
  	  * Constructor with arguments
  	  */
 public GetFundingPlansRequest(RequestEnvelope requestEnvelope, string payKey)
 {
     this.requestEnvelope = requestEnvelope;
     this.payKey = payKey;
 }
    // # SetPaymentOptions API Operation
    // You use the SetPaymentOptions API operation to specify settings for a payment of the actionType CREATE. This actionType is specified in the PayRequest message. 
    public SetPaymentOptionsResponse SetPaymentOptionsAPIOperation()
    {
        // Create the SetPaymentOptionsResponse object
        SetPaymentOptionsResponse responseSetPaymentOptions = new SetPaymentOptionsResponse();

        try
        {
            // # SetPaymentOptionsRequest
            // The code for the language in which errors are returned
            RequestEnvelope envelopeRequest = new RequestEnvelope();
            envelopeRequest.errorLanguage = "en_US";

            // SetPaymentOptionsRequest which takes,
            //
            // * `Request Envelope` - Information common to each API operation, such
            // as the language in which an error message is returned.
            // * `Pay Key` - The pay key that identifies the payment for which you
            // want to set payment options. This is the pay key returned in the
            // PayResponse message. Action Type in PayRequest must be `CREATE`
            SetPaymentOptionsRequest requestSetPaymentOptions = new SetPaymentOptionsRequest(envelopeRequest, "AP-1VB65877N5917862M");

            // Specifies display items in payment flows and emails.
            DisplayOptions displayOptions = new DisplayOptions();

            // The business name to display      
            // The name cannot exceed 128 characters    
            displayOptions.businessName = "Toy Shop";
            requestSetPaymentOptions.displayOptions = displayOptions;

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

            // # API call
            // Invoke the SetPaymentOptions method in service wrapper object
            responseSetPaymentOptions = service.SetPaymentOptions(requestSetPaymentOptions);

            if (responseSetPaymentOptions != null)
            {
                // Response envelope acknowledgement
                string acknowledgement = "SetPaymentOptions API Operation - ";
                acknowledgement += responseSetPaymentOptions.responseEnvelope.ack.ToString();
                logger.Info(acknowledgement + "\n");
                Console.WriteLine(acknowledgement + "\n");

                // # Success values
                if (responseSetPaymentOptions.responseEnvelope.ack.ToString().Trim().ToUpper().Equals("SUCCESS"))
                {
                    responseSetPaymentOptions.responseEnvelope.ack.ToString();
                }
                // # Error Values                
                else
                {
                    List<ErrorData> errorMessages = responseSetPaymentOptions.error;
                    foreach (ErrorData error in errorMessages)
                    {
                        logger.Debug("API Error Message : " + error.message);
                        Console.WriteLine("API Error Message : " + error.message + "\n");
                    }
                }
            }
        }
        // # Exception log    
        catch (System.Exception ex)
        {
            // Log the exception message       
            logger.Debug("Error Message : " + ex.Message);
            Console.WriteLine("Error Message : " + ex.Message);
        }
        return responseSetPaymentOptions;
    }
 /**
  	  * Constructor with arguments
  	  */
 public GetShippingAddressesRequest(RequestEnvelope requestEnvelope, string key)
 {
     this.requestEnvelope = requestEnvelope;
     this.key = key;
 }
    // # GetPaymentOptions API Operation    
    // You use the GetPaymentOptions API operation to retrieve the payment options passed with the SetPaymentOptionsRequest. 
    public GetPaymentOptionsResponse GetPaymentOptionsAPIOperation()
    {
        // Create the  GetPaymentOptionsResponse object
        GetPaymentOptionsResponse responseGetPaymentOptions = new GetPaymentOptionsResponse();

        try
        {
            // Request envelope object
            RequestEnvelope envelopeRequest = new RequestEnvelope();

            // The code for the language in which errors are returned
            envelopeRequest.errorLanguage = "en_US";

            // GetPaymentOptionsRequest which takes,    
            //  
            // * `Request Envelope` - Information common to each API operation, such
            // as the language in which an error message is returned.
            // * `Pay Key` - The pay key that identifies the payment for which you
            // want to set payment options. This is the pay key returned in the
            // PayResponse message. Action Type in PayRequest must be `CREATE`
            GetPaymentOptionsRequest getPaymentOptionsRequest = new GetPaymentOptionsRequest(
            envelopeRequest, "AP-1VB65877N5917862M");

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

            // # API call   
            // Invoke the GetPaymentOptions method in service wrapper object
            responseGetPaymentOptions = service.GetPaymentOptions(getPaymentOptionsRequest);

            // Response envelope acknowledgement
            string acknowledgement = "GetPaymentOptions API Operation - ";
            acknowledgement += responseGetPaymentOptions.responseEnvelope.ack.ToString();
            logger.Info(acknowledgement + "\n");
            Console.WriteLine(acknowledgement + "\n");

            // # Success values
            if (responseGetPaymentOptions.responseEnvelope.ack.ToString().Trim().ToUpper().Equals("SUCCESS"))
            {
                // Response envelope acknowledgement
                acknowledgement = responseGetPaymentOptions.responseEnvelope.ack.ToString().Trim().ToUpper();
                logger.Info(acknowledgement + "\n");
                Console.WriteLine(acknowledgement + "\n");

                // # Success values
                if (acknowledgement.Equals("SUCCESS"))
                {
                    // Business Name you set in SetPaymentOptions
                    logger.Info("Business Name : " + responseGetPaymentOptions.displayOptions.businessName + "\n");
                    Console.WriteLine("Business Name : " + responseGetPaymentOptions.displayOptions.businessName + "\n");
                }
                // # Error Values
                else
                {
                    List<ErrorData> errorMessages = responseGetPaymentOptions.error;
                    foreach (ErrorData error in errorMessages)
                    {
                        logger.Debug("API Error Message : " + error.message);
                        Console.WriteLine("API Error Message : " + error.message + "\n");
                    }
                }
            }
        }
        // # Exception log    
        catch (System.Exception ex)
        {
            // Log the exception message       
            logger.Debug("Error Message : " + ex.Message);
            Console.WriteLine("Error Message : " + ex.Message);
        }
        return responseGetPaymentOptions;
    }
 /**
  	  * Constructor with arguments
  	  */
 public PaymentDetailsRequest(RequestEnvelope requestEnvelope)
 {
     this.requestEnvelope = requestEnvelope;
 }
        public ActionResult Pay()
        {
            var detail = Session["Detail"] as DetailModel;

            NameValueCollection parameters = new NameValueCollection();

            ReceiverList receiverList = new ReceiverList();
            receiverList.receiver = new List<Receiver>();
            PayRequest request = new PayRequest();

            RequestEnvelope requestEnvelope = new RequestEnvelope("en_US");
            request.requestEnvelope = requestEnvelope;

            Receiver merchant = new Receiver();
            // (Required) Amount to be paid to the receiver
            merchant.amount = detail.Booking.TotalCharge;
            // Receiver's email address. This address can be unregistered with
            // paypal.com. If so, a receiver cannot claim the payment until a PayPal
            // account is linked to the email address. The PayRequest must pass
            // either an email address or a phone number. Maximum length: 127 characters
            merchant.email = detail.Hotel.MerchantEmail;

            //This receiver is the primary receiver,who pay the fees
            //merchant.primary = false;

            merchant.paymentType = "SERVICE";

            receiverList.receiver.Add(merchant);

            ReceiverList receiverLst = new ReceiverList(receiverList.receiver);
            request.receiverList = receiverLst;

            // The action for this request. Possible values are: PAY – Use this
            // option if you are not using the Pay request in combination with
            // ExecutePayment. CREATE – Use this option to set up the payment
            // instructions with SetPaymentOptions and then execute the payment at a
            // later time with the ExecutePayment. PAY_PRIMARY – For chained
            // payments only, specify this value to delay payments to the secondary
            // receivers; only the payment to the primary receiver is processed.
            request.actionType = "PAY";

            // The code for the currency in which the payment is made; you can
            // specify only one currency, regardless of the number of receivers
            request.currencyCode = "USD";

            // URL to redirect the sender's browser to after canceling the approval
            // for a payment; it is always required but only used for payments that
            // require approval (explicit payments)
            request.cancelUrl = ConfigurationManager.AppSettings["CANCEL_URL"];

            // URL to redirect the sender's browser to after the sender has logged
            // into PayPal and approved a payment; it is always required but only
            // used if a payment requires explicit approval
            request.returnUrl = ConfigurationManager.AppSettings["RETURN_URL"];

            //Possible fee payer: //SENDER,PRIMARYRECEIVER,SECONDARYONLY,EACHRECEIVER
            request.feesPayer = "EACHRECEIVER";

            AdaptivePaymentsService service = null;
            PayResponse response = null;
            try
            {
                // Configuration map containing signature credentials and other required configuration.
                Dictionary<string, string> configurationMap = Configuration.GetAcctAndConfig();

                // Creating service wrapper object to make an API call and loading
                // configuration map for your credentials and endpoint
                service = new AdaptivePaymentsService(configurationMap);

                response = service.Pay(request);
            }
            catch(System.Exception ex)
            {
                return RedirectToAction("Error", new { message = ex.Message });
            }

            Dictionary<string, string> responseValues = new Dictionary<string, string>();
            string redirectUrl = null;

            if (!response.responseEnvelope.ack.ToString().Trim().ToUpper().Equals(AckCode.FAILURE.ToString()) && !response.responseEnvelope.ack.ToString().Trim().ToUpper().Equals(AckCode.FAILUREWITHWARNING.ToString()))
            {
                redirectUrl = ConfigurationManager.AppSettings["PAYPAL_REDIRECT_URL"] + "_ap-payment&paykey=" + response.payKey;
                // The pay key, which is a token you use in other Adaptive Payment APIs
                // (such as the Refund Method) to identify this payment.
                // The pay key is valid for 3 hours; the payment must be approved while the
                // pay key is valid.
                responseValues.Add("Pay Key", response.payKey);

                // The status of the payment. Possible values are:
                // CREATED – The payment request was received; funds will be transferred once the payment is approved
                // COMPLETED – The payment was successful
                // INCOMPLETE – Some transfers succeeded and some failed for a parallel payment or, for a delayed chained payment, secondary receivers have not been paid
                // ERROR – The payment failed and all attempted transfers failed or all completed transfers were successfully reversed
                // REVERSALERROR – One or more transfers failed when attempting to reverse a payment
                // PROCESSING – The payment is in progress
                // PENDING – The payment is awaiting processing
                responseValues.Add("Payment Execution Status", response.paymentExecStatus);

            }

            responseValues.Add("Acknowledgement", response.responseEnvelope.ack.ToString().Trim().ToUpper());

            return Redirect(redirectUrl);
        }
 /**
  	  * Constructor with arguments
  	  */
 public PayRequest(RequestEnvelope requestEnvelope, string actionType, string cancelUrl, string currencyCode, ReceiverList receiverList, string returnUrl)
 {
     this.requestEnvelope = requestEnvelope;
     this.actionType = actionType;
     this.cancelUrl = cancelUrl;
     this.currencyCode = currencyCode;
     this.receiverList = receiverList;
     this.returnUrl = returnUrl;
 }
    // # ExecutePayment API Operation
    // The ExecutePayment API operation lets you execute a payment set up with the Pay API operation with the actionType CREATE. To pay receivers identified in the Pay call, set the pay key from the PayResponse message in the ExecutePaymentRequest message. 
    public ExecutePaymentResponse ExecutePaymentAPIOperation()
    {
        // Create the ExecutePaymentResponse object
        ExecutePaymentResponse responseExecutePayment = new ExecutePaymentResponse();

        try
        {
            // # ExecutePaymentRequest
            // The code for the language in which errors are returned
            RequestEnvelope envelopeRequest = new RequestEnvelope();
            envelopeRequest.errorLanguage = "en_US";

            // ExecutePaymentRequest which takes,
            //
            // * `Request Envelope` - Information common to each API operation, such
            // as the language in which an error message is returned.
            // * `Pay Key` - The pay key that identifies the payment for which you
            // want to set payment options. This is the pay key returned in the
            // PayResponse message. Action Type in PayRequest must be `CREATE`
            ExecutePaymentRequest requestExecutePayment = new ExecutePaymentRequest(envelopeRequest, "AP-1VB65877N5917862M");

            // The ID of the funding plan from which to make this payment.
            requestExecutePayment.fundingPlanId = "0";

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

            // # API call           
            // Invoke the ExecutePayment method in service wrapper object
            responseExecutePayment = service.ExecutePayment(requestExecutePayment);

            if (responseExecutePayment != null)
            {
                // Response envelope acknowledgement
                string acknowledgement = "ExecutePayment API operation - ";
                acknowledgement += responseExecutePayment.responseEnvelope.ack.ToString();
                logger.Info(acknowledgement + "\n");
                Console.WriteLine(acknowledgement + "\n");

                // # Success values
                if (responseExecutePayment.responseEnvelope.ack.ToString().Trim().ToUpper().Equals("SUCCESS"))
                {
                    // The status of the payment. Possible values are:
                    //
                    // * CREATED - The payment request was received; funds will be
                    // transferred once the payment is approved
                    // * COMPLETED - The payment was successful
                    // * INCOMPLETE - Some transfers succeeded and some failed for a
                    // parallel payment
                    // * ERROR - The payment failed and all attempted transfers failed
                    // or all completed transfers were successfully reversed
                    // * REVERSALERROR - One or more transfers failed when attempting
                    // to reverse a payment
                    logger.Info("Payment Execution Status: " + responseExecutePayment.paymentExecStatus + "\n");
                    Console.WriteLine("Payment Execution Status : " + responseExecutePayment.paymentExecStatus + "\n");

                }
                // # Error Values 
                else
                {
                    List<ErrorData> errorMessages = responseExecutePayment.error;
                    foreach (ErrorData error in errorMessages)
                    {
                        logger.Debug("API Error Message : " + error.message);
                        Console.WriteLine("API Error Message : " + error.message + "\n");
                    }
                }
            }
        }
        // # Exception log    
        catch (System.Exception ex)
        {
            // Log the exception message       
            logger.Debug("Error Message : " + ex.Message);
            Console.WriteLine("Error Message : " + ex.Message);
        }
        return responseExecutePayment;
    }
 /**
  	  * Constructor with arguments
  	  */
 public PreapprovalRequest(RequestEnvelope requestEnvelope, string cancelUrl, string currencyCode, string returnUrl, string startingDate)
 {
     this.requestEnvelope = requestEnvelope;
     this.cancelUrl = cancelUrl;
     this.currencyCode = currencyCode;
     this.returnUrl = returnUrl;
     this.startingDate = startingDate;
 }
    // # Refund API Operation
    // Use the Refund API operation to refund all or part of a payment. You can specify the amount of the refund and identify the accounts to receive the refund by the payment key or tracking ID, and optionally, by transaction ID or the receivers of the original payment. 
    public RefundResponse RefundAPIOperation()
    {
        // Create the RefundResponse object
        RefundResponse responseRefund = new RefundResponse();

        try
        {
            // # RefundRequest
            // The code for the language in which errors are returned
            RequestEnvelope envelopeRequest = new RequestEnvelope();
            envelopeRequest.errorLanguage = "en_US";

            // RefundRequest which takes,
            // `Request Envelope` - Information common to each API operation, such
            // as the language in which an error message is returned.
            RefundRequest requestRefund = new RefundRequest(envelopeRequest);

            // You must specify either,
            //
            // * `Pay Key` - The pay key that identifies the payment for which you
            // want to retrieve details. This is the pay key returned in the
            // PayResponse message.
            // * `Transaction ID` - The PayPal transaction ID associated with the
            // payment. The IPN message associated with the payment contains the
            // transaction ID.
            // `requestRefund.transactionId = transactionId`
            // * `Tracking ID` - The tracking ID that was specified for this payment
            // in the PayRequest message.
            // `requestRefund.trackingId = trackingId`
            requestRefund.payKey = "AP-86H50830VE600922B";

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

            // # API call
            // Invoke the Refund method in service wrapper object
            responseRefund = service.Refund(requestRefund);

            if (responseRefund != null)
            {
                // Response envelope acknowledgement
                string acknowledgement = "Refund API Operation - ";
                acknowledgement += responseRefund.responseEnvelope.ack.ToString();
                logger.Info(acknowledgement + "\n");
                Console.WriteLine(acknowledgement + "\n");

                // # Success values
                if (responseRefund.responseEnvelope.ack.ToString().Trim().ToUpper().Equals("SUCCESS"))
                {
                    // List of refunds associated with the payment.
                    IEnumerator<RefundInfo> iterator = responseRefund.refundInfoList.refundInfo.GetEnumerator();

                    while (iterator.MoveNext())
                    {
                        // Represents the refund attempt made to a receiver of a
                        // PayRequest.
                        RefundInfo refundInfo = iterator.Current;

                        // Status of the refund. It is one of the following values:
                        //
                        // * REFUNDED - Refund successfully completed
                        // * REFUNDED_PENDING - Refund awaiting transfer of funds; for
                        // example, a refund paid by eCheck.
                        // * NOT_PAID - Payment was never made; therefore, it cannot
                        // be refunded.
                        // * ALREADY_REVERSED_OR_REFUNDED - Request rejected because
                        // the refund was already made, or the payment was reversed
                        // prior to this request.
                        // * NO_API_ACCESS_TO_RECEIVER - Request cannot be completed
                        // because you do not have third-party access from the
                        // receiver to make the refund.
                        // * REFUND_NOT_ALLOWED - Refund is not allowed.
                        // * INSUFFICIENT_BALANCE - Request rejected because the
                        // receiver from which the refund is to be paid does not
                        // have sufficient funds or the funding source cannot be
                        // used to make a refund.
                        // * AMOUNT_EXCEEDS_REFUNDABLE - Request rejected because you
                        // attempted to refund more than the remaining amount of the
                        // payment; call the PaymentDetails API operation to
                        // determine the amount already refunded.
                        // * PREVIOUS_REFUND_PENDING - Request rejected because a
                        // refund is currently pending for this part of the payment
                        // * NOT_PROCESSED - Request rejected because it cannot be
                        // processed at this time
                        // * REFUND_ERROR - Request rejected because of an internal
                        // error
                        // * PREVIOUS_REFUND_ERROR - Request rejected because another
                        // part of this refund caused an internal error.
                        logger.Info("Refund Status : " + refundInfo.refundStatus + "\n");
                        Console.WriteLine("Refund Status : " + refundInfo.refundStatus + "\n");
                    }
                }
                // # Error Values
                else
                {
                    List<ErrorData> errorMessages = responseRefund.error;
                    foreach (ErrorData error in errorMessages)
                    {
                        logger.Debug("API Error Message : " + error.message);
                        Console.WriteLine("API Error Message : " + error.message + "\n");
                    }
                }
            }
        }
        // # Exception log    
        catch (System.Exception ex)
        {
            // Log the exception message       
            logger.Debug("Error Message : " + ex.Message);
            Console.WriteLine("Error Message : " + ex.Message);
        }
        return responseRefund;
    }