Exemplo n.º 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();
        }
        /// <summary>
        /// Handle ExecutePayment API call
        /// </summary>
        /// <param name="contextHttp"></param>
        private void ExecutePayment(HttpContext contextHttp)
        {
            NameValueCollection parameters = contextHttp.Request.Params;

            // error language : (Required) RFC 3066 language in which error 
            // messages are returned; by default it is en_US, which is the only language currently supported. 
            // paykey : (Optional) The pay key that identifies the payment to be executed. 
            // This is the pay key returned in the PayResponse message. 
            ExecutePaymentRequest request = new ExecutePaymentRequest(new RequestEnvelope("en_US"), parameters["payKey"]);

            // (Optional) The ID of the funding plan from which to make this payment. 
            request.fundingPlanId = parameters["fundingPlanId"];
            
            AdaptivePaymentsService service = null;
            ExecutePaymentResponse 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.ExecutePayment(request);
            }
            catch (System.Exception e)
            {
                contextHttp.Response.Write(e.Message);
                return;
            }

            Dictionary<string, string> responseValues = new Dictionary<string, string>();
            string redirectUrl = null;
            if (!(response.responseEnvelope.ack == AckCode.FAILURE) &&
                !(response.responseEnvelope.ack == AckCode.FAILUREWITHWARNING))
            {
                //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
                // Important: You must test the value of paymentExecStatus for an error even if 
                // responseEnvelope.ack is Success. If the PaymentExecStatus is ERROR, 
                // the Pay Key can no longer be used. 
                responseValues.Add("Payment exeucution status", response.paymentExecStatus);

                
                responseValues.Add("Acknowledgement", response.responseEnvelope.ack.ToString());
            }
            Display(contextHttp, "ExecutePayment", responseValues, service.getLastRequest(), service.getLastResponse(), response.error, redirectUrl);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Handle Refund API call
        /// </summary>
        /// <param name="context"></param>
        private void Refund(HttpContext context)
        {
            NameValueCollection parameters = context.Request.Params;
            RefundRequest req = new RefundRequest(new RequestEnvelope("en_US"));
            // Set optional parameters
            if(parameters["receiverEmail"].Length > 0)
            {
                string[] amt = context.Request.Form.GetValues("receiverAmount");
                string[] receiverEmail = context.Request.Form.GetValues("receiverEmail");
                string[] phoneCountry = context.Request.Form.GetValues("phoneCountry");
                string[] phoneNumber = context.Request.Form.GetValues("phoneNumber");
                string[] phoneExtn = context.Request.Form.GetValues("phoneExtn");
                string[] primaryReceiver = context.Request.Form.GetValues("primaryReceiver");
                string[] invoiceId = context.Request.Form.GetValues("invoiceId");
                string[] paymentType = context.Request.Form.GetValues("paymentType");
                string[] paymentSubType = context.Request.Form.GetValues("paymentSubType");

                List<Receiver> receivers = new List<Receiver>();
                for(int i=0; i<amt.Length; i++) {
                    Receiver r = new Receiver(Decimal.Parse(amt[i]));
                    r.email = receiverEmail[i];
                    r.primary = Boolean.Parse(primaryReceiver[i]);
                    if(invoiceId[i] != "") {
                        r.invoiceId = invoiceId[i];
                    }
                    if(paymentType[i] != "") {
                        r.paymentType = paymentType[i];
                    }
                    if(paymentSubType[i] != "") {
                        r.paymentSubType = paymentSubType[i];
                    }
                    if(phoneCountry[i] != "" && phoneNumber[i] != "") {
                        r.phone = new PhoneNumberType(phoneCountry[i], phoneNumber[i]);
                        if(phoneExtn[i] != "") {
                            r.phone.extension = phoneExtn[i];
                        }
                    }
                    receivers.Add(r);
                }
                req.receiverList = new ReceiverList(receivers);
            }
            if(parameters["currencyCode"] != "") {
                req.currencyCode = parameters["currencyCode"];
            }
            if(parameters["payKey"] != "") {
                req.payKey = parameters["payKey"];
            }
            if(parameters["transactionId"] != "") {
                req.transactionId = parameters["transactionId"];
            }
            if(parameters["trackingId"] != "") {
                req.trackingId = parameters["trackingId"];
            }

            // All set. Fire the request
            AdaptivePaymentsService service = new AdaptivePaymentsService();
            RefundResponse resp = null;
            try
            {
                resp = service.Refund(req);
            }
            catch (System.Exception e)
            {
                context.Response.Write(e.Message);
                return;
            }

            // Display response values.
            Dictionary<string, string> keyResponseParams = new Dictionary<string, string>();
            string redirectUrl = null;
            if (!(resp.responseEnvelope.ack == AckCode.FAILURE) &&
                !(resp.responseEnvelope.ack == AckCode.FAILUREWITHWARNING))
            {
                keyResponseParams.Add("Currency code", resp.currencyCode);
                int idx = 1;
                foreach (RefundInfo refund in resp.refundInfoList.refundInfo)
                {
                    keyResponseParams.Add("Refund receiver " + idx, refund.receiver.email);
                    keyResponseParams.Add("Refund amount " + idx, refund.receiver.amount.ToString());
                    keyResponseParams.Add("Refund status " + idx, refund.refundStatus);

                    //Selenium Test Case
                    keyResponseParams.Add("Acknowledgement", resp.responseEnvelope.ack.ToString());
                }
            }
            displayResponse(context, "Refund", keyResponseParams, service.getLastRequest(), service.getLastResponse(),
                resp.error, redirectUrl);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Handle Preapproval API
        /// </summary>
        /// <param name="context"></param>
        private void Preapproval(HttpContext context)
        {
            NameValueCollection parameters = context.Request.Params;
            PreapprovalRequest req = new PreapprovalRequest(new RequestEnvelope("en_US"), parameters["cancelUrl"],
                    parameters["currencyCode"], parameters["returnUrl"], parameters["startingDate"]);
            // set optional parameters
            if(parameters["dateOfMonth"] != "")
            {
                req.dateOfMonth = Int32.Parse(parameters["dateOfMonth"]);
            }
            if(parameters["dayOfWeek"] != "" && parameters["dayOfWeek"] != "")
            {
                req.dayOfWeek = (PayPal.AdaptivePayments.Model.DayOfWeek)
                        Enum.Parse(typeof(PayPal.AdaptivePayments.Model.DayOfWeek), parameters["dayOfWeek"]);
            }
            if(parameters["dateOfMonth"] != "")
            {
                req.dateOfMonth = Int32.Parse(parameters["dateOfMonth"]);
            }
            if(parameters["endingDate"] != "")
            {
                req.endingDate = parameters["endingDate"];
            }
            if(parameters["maxAmountPerPayment"] != "")
            {
                req.maxAmountPerPayment = Decimal.Parse(parameters["maxAmountPerPayment"]);
            }
            if(parameters["maxNumberOfPayments"] != "" )
            {
                req.maxNumberOfPayments = Int32.Parse(parameters["maxNumberOfPayments"]);
            }
            if(parameters["maxNumberOfPaymentsPerPeriod"] != "")
            {
                req.maxNumberOfPaymentsPerPeriod = Int32.Parse(parameters["maxNumberOfPaymentsPerPeriod"]);
            }
            if(parameters["maxTotalAmountOfAllPayments"] != "")
            {
                req.maxTotalAmountOfAllPayments = Decimal.Parse(parameters["maxTotalAmountOfAllPayments"]);
            }
            if(parameters["paymentPeriod"] != "" && parameters["paymentPeriod"] != "")
            {
                req.paymentPeriod = parameters["paymentPeriod"];
            }
            if(parameters["memo"] != "")
            {
                req.memo = parameters["memo"];
            }
            if(parameters["ipnNotificationUrl"] != "")
            {
                req.ipnNotificationUrl = parameters["ipnNotificationUrl"];
            }
            if(parameters["senderEmail"] != "")
            {
                req.senderEmail = parameters["senderEmail"];
            }
            if(parameters["pinType"] != "" && parameters["pinType"] != "")
            {
                req.pinType = parameters["pinType"];
            }
            if(parameters["feesPayer"] != "")
            {
                req.feesPayer = parameters["feesPayer"];
            }
            if (parameters["displayMaxTotalAmount"] != "")
            {
                req.displayMaxTotalAmount = Boolean.Parse(parameters["displayMaxTotalAmount"]);
            }

            // All set. Fire the request
            AdaptivePaymentsService service = new AdaptivePaymentsService();
            PreapprovalResponse resp = null;
            try
            {
                resp = service.Preapproval(req);
            }
            catch (System.Exception e)
            {
                context.Response.Write(e.Message);
                return;
            }

            // Display response values.
            Dictionary<string, string> keyResponseParams = new Dictionary<string, string>();
            string redirectUrl = null;
            if (!(resp.responseEnvelope.ack == AckCode.FAILURE) &&
                !(resp.responseEnvelope.ack == AckCode.FAILUREWITHWARNING))
            {
                keyResponseParams.Add("Preapproval key", resp.preapprovalKey);

                //Selenium Test Case
                redirectUrl = ConfigurationManager.AppSettings["PAYPAL_REDIRECT_URL"]
                                     + "_ap-preapproval&preapprovalkey=" + resp.preapprovalKey;
                keyResponseParams.Add("Acknowledgement", resp.responseEnvelope.ack.ToString());
                keyResponseParams.Add("Redirect To PayPal", redirectUrl);
            }
            displayResponse(context, "Preapproval", keyResponseParams, service.getLastRequest(), service.getLastResponse(),
                resp.error, redirectUrl);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Handle Pay API calls
        /// </summary>
        /// <param name="context"></param>
        private void Pay(HttpContext context)
        {
            NameValueCollection parameters = context.Request.Params;
            ReceiverList receiverList = new ReceiverList();
            receiverList.receiver = new List<Receiver>();
            string[] amt = context.Request.Form.GetValues("receiverAmount");
            string[] receiverEmail = context.Request.Form.GetValues("receiverEmail");
            string[] phoneCountry = context.Request.Form.GetValues("phoneCountry");
            string[] phoneNumber = context.Request.Form.GetValues("phoneNumber");
            string[] phoneExtn = context.Request.Form.GetValues("phoneExtn");
            string[] primaryReceiver = context.Request.Form.GetValues("primaryReceiver");
            string[] invoiceId = context.Request.Form.GetValues("invoiceId");
            string[] paymentType = context.Request.Form.GetValues("paymentType");
            string[] paymentSubType = context.Request.Form.GetValues("paymentSubType");
            for (int i = 0; i < amt.Length; i++)
            {
                Receiver rec = new Receiver(Decimal.Parse(amt[i]));
                if(receiverEmail[i] != "")
                    rec.email = receiverEmail[i];
                if (phoneCountry[i] != "" && phoneNumber[i] != "")
                {
                    rec.phone = new PhoneNumberType(phoneCountry[i], phoneNumber[i]);
                    if (phoneExtn[i] != "")
                    {
                        rec.phone.extension = phoneExtn[i];
                    }
                }
                if (primaryReceiver[i] != "")
                    rec.primary = Boolean.Parse(primaryReceiver[i]);
                if (invoiceId[i] != "")
                    rec.invoiceId = invoiceId[i];
                if (paymentType[i] != "")
                    rec.paymentType = paymentType[i];
                if (paymentSubType[i] != "")
                    rec.paymentSubType = paymentSubType[i];
                receiverList.receiver.Add(rec);
            }
            PayRequest req = new PayRequest(new RequestEnvelope("en_US"), parameters["actionType"],
                                parameters["cancelUrl"], parameters["currencyCode"],
                                receiverList, parameters["returnUrl"]);

            //Fix for release
            if (parameters["ipnNotificationUrl"] != "")
            {
                req.ipnNotificationUrl = parameters["ipnNotificationUrl"];
            }
            if (parameters["memo"] != "")
            {
                req.memo = parameters["memo"];
            }
            if (parameters["pin"] != "")
            {
                req.pin = parameters["pin"];
            }
            if (parameters["preapprovalKey"] != "")
            {
                req.preapprovalKey = parameters["preapprovalKey"];
            }

            // set optional parameters
            if (parameters["reverseAllParallelPaymentsOnError"] != "")
                req.reverseAllParallelPaymentsOnError =
                    Boolean.Parse(parameters["reverseAllParallelPaymentsOnError"]);
            if (parameters["senderEmail"] != "")
                req.senderEmail = parameters["senderEmail"];
            if (parameters["trackingId"] != "")
                req.trackingId = parameters["trackingId"];
            if (parameters["fundingConstraint"] != "")
            {
                req.fundingConstraint = new FundingConstraint();
                req.fundingConstraint.allowedFundingType = new FundingTypeList();
                req.fundingConstraint.allowedFundingType.fundingTypeInfo.Add(
                    new FundingTypeInfo(parameters["fundingConstraint"]));
            }
            if (parameters["emailIdentifier"] != ""
                || (parameters["senderPhoneCountry"] != "" && parameters["senderPhoneNumber"] != "")
                || parameters["useCredentials"] != "")
            {
                req.sender = new SenderIdentifier();
                if (parameters["emailIdentifier"] != "")
                    req.sender.email = parameters["emailIdentifier"];
                if (parameters["senderPhoneCountry"] != "" && parameters["senderPhoneNumber"] != "")
                {
                    req.sender.phone = new PhoneNumberType(parameters["senderPhoneCountry"], parameters["senderPhoneNumber"]);
                    if (parameters["senderPhoneExtn"] != "")
                        req.sender.phone.extension = parameters["senderPhoneExtn"];
                }
                if (parameters["useCredentials"] != "")
                    req.sender.useCredentials = Boolean.Parse(parameters["useCredentials"]);
            }

            // All set. Fire the request
            AdaptivePaymentsService service = new AdaptivePaymentsService();
            PayResponse resp = null;
            try
            {
                resp = service.Pay(req);
            }
            catch (System.Exception e)
            {
                context.Response.Write(e.Message);
                return;
            }

            // Display response values.
            Dictionary<string, string> keyResponseParams = new Dictionary<string, string>();
            string redirectUrl = null;
            if ( !(resp.responseEnvelope.ack == AckCode.FAILURE) &&
                !(resp.responseEnvelope.ack == AckCode.FAILUREWITHWARNING) )
            {
                redirectUrl = ConfigurationManager.AppSettings["PAYPAL_REDIRECT_URL"]
                                     + "_ap-payment&paykey=" + resp.payKey;
                keyResponseParams.Add("Pay key", resp.payKey);
                keyResponseParams.Add("Payment execution status", resp.paymentExecStatus);
                if (resp.defaultFundingPlan != null && resp.defaultFundingPlan.senderFees != null)
                {
                    keyResponseParams.Add("Sender fees", resp.defaultFundingPlan.senderFees.amount +
                                                resp.defaultFundingPlan.senderFees.code);
                }

                //Selenium Test Case
                keyResponseParams.Add("Acknowledgement", resp.responseEnvelope.ack.ToString());
            }
            displayResponse(context, "Pay", keyResponseParams, service.getLastRequest(), service.getLastResponse(),
                resp.error, redirectUrl);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Handle GetShippingAddresses API call
        /// </summary>
        /// <param name="context"></param>
        private void GetShippingAddresses(HttpContext context)
        {
            NameValueCollection parameters = context.Request.Params;
            GetShippingAddressesRequest req = new GetShippingAddressesRequest(new RequestEnvelope("en_US"),
                parameters["key"]);

            // All set. Fire the request
            AdaptivePaymentsService service = new AdaptivePaymentsService();
            GetShippingAddressesResponse resp = null;
            try
            {
                resp = service.GetShippingAddresses(req);
            }
            catch (System.Exception e)
            {
                context.Response.Write(e.Message);
                return;
            }

            // Display response values.
            Dictionary<string, string> keyResponseParams = new Dictionary<string, string>();
            string redirectUrl = null;
            if (!(resp.responseEnvelope.ack == AckCode.FAILURE) &&
                !(resp.responseEnvelope.ack == AckCode.FAILUREWITHWARNING))
            {
                if (resp.selectedAddress != null)
                {
                    keyResponseParams.Add("Address name", resp.selectedAddress.addresseeName);
                    keyResponseParams.Add("Address Id", resp.selectedAddress.addressId);
                    if (resp.selectedAddress.baseAddress != null)
                    {
                        keyResponseParams.Add("Address line", resp.selectedAddress.baseAddress.line1);
                        keyResponseParams.Add("City", resp.selectedAddress.baseAddress.city);
                        keyResponseParams.Add("State", resp.selectedAddress.baseAddress.state);
                    }
                }
            }
            displayResponse(context, "GetShippingAddresses", keyResponseParams, service.getLastRequest(), service.getLastResponse(),
                resp.error, redirectUrl);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Handle GetFundingPlans API call
        /// </summary>
        /// <param name="context"></param>
        private void GetFundingPlans(HttpContext context)
        {
            NameValueCollection parameters = context.Request.Params;
            GetFundingPlansRequest req = new GetFundingPlansRequest(new RequestEnvelope("en_US"),
                parameters["payKey"]);

            // All set. Fire the request
            AdaptivePaymentsService service = new AdaptivePaymentsService();
            GetFundingPlansResponse resp = null;
            try
            {
                resp = service.GetFundingPlans(req);
            }
            catch (System.Exception e)
            {
                context.Response.Write(e.Message);
                return;
            }

            // Display response values.
            Dictionary<string, string> keyResponseParams = new Dictionary<string, string>();
            string redirectUrl = null;
            if (!(resp.responseEnvelope.ack == AckCode.FAILURE) &&
                !(resp.responseEnvelope.ack == AckCode.FAILUREWITHWARNING))
            {
                int idx = 1;
                foreach (FundingPlan plan in resp.fundingPlan) {
                    keyResponseParams.Add("Funding plan Id " + idx, plan.fundingPlanId);
                    keyResponseParams.Add("Funding plan amount " + idx,
                        plan.fundingAmount.amount + plan.fundingAmount.code );
                    idx++;
                }
            }
            displayResponse(context, "GetFundingPlans", keyResponseParams, service.getLastRequest(), service.getLastResponse(),
                resp.error, redirectUrl);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Handle ConvertCurrency API call
        /// </summary>
        /// <param name="context"></param>
        private void ConvertCurrency(HttpContext context)
        {
            NameValueCollection parameters = context.Request.Params;
            string[] fromCurrencyCodes = context.Request.Form.GetValues("currencyCode");
            string[] fromCurrencyAmounts = context.Request.Form.GetValues("currencyAmount");
            string[] toCurrencyCodes = context.Request.Form.GetValues("toCurrencyCode");

            List<CurrencyType> currencies = new List<CurrencyType>();
            for(int i=0; i<fromCurrencyCodes.Length; i++)
            {
                currencies.Add(
                    new CurrencyType(fromCurrencyCodes[i], decimal.Parse(fromCurrencyAmounts[i]))
                );
            }
            CurrencyList baseAmountList = new CurrencyList(currencies);

            List<String> toCurrencyCodeList = new List<String>();
            for (int i = 0; i < toCurrencyCodes.Length; i++)
                toCurrencyCodeList.Add(toCurrencyCodes[i]);
            CurrencyCodeList convertToCurrencyList = new CurrencyCodeList(toCurrencyCodeList);

            ConvertCurrencyRequest req = new ConvertCurrencyRequest(
                new RequestEnvelope("en_US"), baseAmountList, convertToCurrencyList);
            // Add optional parameters
            if (parameters["countryCode"] != "")
                req.countryCode = parameters["countryCode"];
            if (parameters["conversionType"] != "")
                req.conversionType = parameters["conversionType"];

            // All set. Fire the request
            AdaptivePaymentsService service = new AdaptivePaymentsService();
            ConvertCurrencyResponse resp = null;
            try
            {
                resp = service.ConvertCurrency(req);
            }
            catch (System.Exception e)
            {
                context.Response.Write(e.Message);
                return;
            }

            // Display response values.
            Dictionary<string, string> keyResponseParams = new Dictionary<string, string>();
            string redirectUrl = null;
            if (!(resp.responseEnvelope.ack == AckCode.FAILURE) &&
                !(resp.responseEnvelope.ack == AckCode.FAILUREWITHWARNING))
            {
                if (resp.estimatedAmountTable != null
                    && resp.estimatedAmountTable.currencyConversionList != null)
                {
                    int idx = 1;
                    foreach (CurrencyConversionList list in resp.estimatedAmountTable.currencyConversionList)
                    {
                        keyResponseParams.Add("Base amount " + idx,
                            list.baseAmount.amount + " " + list.baseAmount.code);
                        idx++;
                    }
                }

                //Selenium Test Case
                keyResponseParams.Add("Acknowledgement", resp.responseEnvelope.ack.ToString());
            }
            displayResponse(context, "ConvertCurrency", keyResponseParams, service.getLastRequest(), service.getLastResponse(),
                resp.error, redirectUrl);
        }
        /// <summary>
        /// Handle Pay API calls
        /// </summary>
        /// <param name="contextHttp"></param>
        private void Pay(HttpContext contextHttp)
        {
            NameValueCollection parameters = contextHttp.Request.Params;
            ReceiverList receiverList = new ReceiverList();
            receiverList.receiver = new List<Receiver>();
            //(Required) Amount to be paid to the receiver
            string[] amt = contextHttp.Request.Form.GetValues("receiverAmount");
            // 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 
            string[] receiverEmail = contextHttp.Request.Form.GetValues("receiverEmail");
            //Telephone country code 
            string[] phoneCountry = contextHttp.Request.Form.GetValues("phoneCountry");
            // A type to specify the receiver's phone number.
		    // The PayRequest must pass either an email address or a phone number as the payment receiver. 
            string[] phoneNumber = contextHttp.Request.Form.GetValues("phoneNumber");
            //Telephone extension
            string[] phoneExtn = contextHttp.Request.Form.GetValues("phoneExtn");
            // (Optional) Whether this receiver is the primary receiver, 
		    // which makes the payment a chained payment.You can specify at most one primary receiver. 
		    // Omit this field for simple and parallel payments. Allowable values are:
		    //  true – Primary receiver
		    //  false – Secondary receiver (default)
		    string[] primaryReceiver = contextHttp.Request.Form.GetValues("primaryReceiver");
            //  (Optional) The invoice number for the payment. 
            //  This data in this field shows on the Transaction Details report. 
            //  Maximum length: 127 characters
            string[] invoiceId = contextHttp.Request.Form.GetValues("invoiceId");
            
		    // (Optional) The transaction type for the payment. Allowable values are:
		    // GOODS – This is a payment for non-digital goods
		    // SERVICE – This is a payment for services (default)
		    // PERSONAL – This is a person-to-person payment
		    // CASHADVANCE – This is a person-to-person payment for a cash advance
		    // DIGITALGOODS – This is a payment for digital goods
		    // BANK_MANAGED_WITHDRAWAL – This is a person-to-person payment for bank withdrawals, available only with special permission.
		    string[] paymentType = contextHttp.Request.Form.GetValues("paymentType");
            //(Optional) The transaction subtype for the payment. 
            string[] paymentSubType = contextHttp.Request.Form.GetValues("paymentSubType");
            for (int i = 0; i < amt.Length; i++)
            {
                Receiver rec = new Receiver(Convert.ToDecimal(amt[i]));
                if(receiverEmail[i] != string.Empty)
                    rec.email = receiverEmail[i];
                if (phoneCountry[i] != string.Empty && phoneNumber[i] != string.Empty)
                {
                    rec.phone = new PhoneNumberType(phoneCountry[i], phoneNumber[i]);
                    if (phoneExtn[i] != string.Empty)
                    {
                        rec.phone.extension = phoneExtn[i];
                    }
                }
                if (primaryReceiver[i] != string.Empty)
                    rec.primary = Convert.ToBoolean(primaryReceiver[i]);
                if (invoiceId[i] != string.Empty)
                    rec.invoiceId = invoiceId[i];
                if (paymentType[i] != string.Empty)
                    rec.paymentType = paymentType[i];
                if (paymentSubType[i] != string.Empty)
                    rec.paymentSubType = paymentSubType[i];
                receiverList.receiver.Add(rec);
            }  
          
            PayRequest request = new PayRequest(new RequestEnvelope("en_US"), parameters["actionType"], 
                                parameters["cancelUrl"], parameters["currencyCode"], 
                                receiverList, parameters["returnUrl"]);

            //Fix for release
            if (parameters["ipnNotificationUrl"] != string.Empty)
            {
                request.ipnNotificationUrl = parameters["ipnNotificationUrl"];
            }
            //(Optional) A note associated with the payment (text, not HTML). 
            // Maximum length: 1000 characters, including newline characters 
            if (parameters["memo"] != string.Empty)
            {
                request.memo = parameters["memo"];
            }
            //The sender's personal identification number, which was specified 
            //when the sender signed up for a preapproval. 
            if (parameters["pin"] != string.Empty)
            {
                request.pin = parameters["pin"];
            }
            // (Optional) The key associated with a preapproval for this payment. 
            // The preapproval key is required if this is a preapproved payment.
            // Note: The Preapproval API is unavailable to API callers with Standard permission levels.
            if (parameters["preapprovalKey"] != string.Empty)
            {
                request.preapprovalKey = parameters["preapprovalKey"];
            }

            // set optional parameters
            //(Optional) Whether to reverse parallel payments if an error occurs with a payment. 
            //Allowable values are:
            //true – Each parallel payment is reversed if an error occurs
            //false – Only incomplete payments are reversed (default)
            if (parameters["reverseAllParallelPaymentsOnError"] != string.Empty)
                request.reverseAllParallelPaymentsOnError = 
                 Convert.ToBoolean(parameters["reverseAllParallelPaymentsOnError"]);

            // Sender's email address 
            if (parameters["senderEmail"] != string.Empty)
                request.senderEmail = parameters["senderEmail"];

            //(Optional) A unique ID that you specify to track the payment.
            //Note: You are responsible for ensuring that the ID is unique.
            //Maximum length: 127 characters 
            if (parameters["trackingId"] != string.Empty)
                request.trackingId = parameters["trackingId"];

            // (Optional) Specifies a list of allowed funding types for the payment. 
            // This is a list of funding selections that can be combined in any order 
            // to allow payments to use the indicated funding type. If this Parameter is omitted, 
            // the payment can be funded by any funding type that is supported for Adaptive Payments.
            // Note: FundingConstraint is unavailable to API callers with standard permission levels; 
            // for more information, refer to the section Adaptive Payments Permission Levels.
            if (parameters["fundingConstraint"] != string.Empty)
            {
                request.fundingConstraint = new FundingConstraint();
                request.fundingConstraint.allowedFundingType = new FundingTypeList();
                request.fundingConstraint.allowedFundingType.fundingTypeInfo.Add(
                    new FundingTypeInfo(parameters["fundingConstraint"]));
            }

            if (parameters["emailIdentifier"] != string.Empty
                || (parameters["senderPhoneCountry"] != string.Empty && parameters["senderPhoneNumber"] != string.Empty)
                || parameters["useCredentials"] != string.Empty)
            {
                request.sender = new SenderIdentifier();
                //  (Optional) Sender's email address. Maximum length: 127 characters 
                if (parameters["emailIdentifier"] != string.Empty)
                    request.sender.email = parameters["emailIdentifier"];

                 // Sender Telephone country code
                 // Sender Telephone number
                 // Sender Telephone extension
                if (parameters["senderPhoneCountry"] != string.Empty && parameters["senderPhoneNumber"] != string.Empty)
                {
                    request.sender.phone = new PhoneNumberType(parameters["senderPhoneCountry"], parameters["senderPhoneNumber"]);
                    if (parameters["senderPhoneExtn"] != string.Empty)
                        request.sender.phone.extension = parameters["senderPhoneExtn"];
                }

                // (Optional) If true, use credentials to identify the sender; default is false. 
                if (parameters["useCredentials"] != string.Empty)
                    request.sender.useCredentials = Convert.ToBoolean(parameters["useCredentials"]);
            }
                  
            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 e)
            {
                contextHttp.Response.Write(e.Message);
                return;
            }

            Dictionary<string, string> responseValues = new Dictionary<string, string>();
            string redirectUrl = null;
            if ( !(response.responseEnvelope.ack == AckCode.FAILURE) && 
                !(response.responseEnvelope.ack == AckCode.FAILUREWITHWARNING) )
            {
                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());
            }
            Display(contextHttp, "Pay", responseValues, service.getLastRequest(), service.getLastResponse(), response.error, redirectUrl);            
        }
        /// <summary>
        /// Handle Refund API call
        /// </summary>
        /// <param name="contextHttp"></param>
        private void Refund(HttpContext contextHttp)
        {
            NameValueCollection parameters = contextHttp.Request.Params;

            // error language : (Required) RFC 3066 language in which error messages are returned; by default it is en_US, which is the only language currently supported. 
            RefundRequest request = new RefundRequest(new RequestEnvelope("en_US"));

            // Set optional parameters
            if(parameters["receiverEmail"].Length > 0) 
            {
                //(Required) Amount to be paid to the receiver
                string[] amt = contextHttp.Request.Form.GetValues("receiverAmount");

                // 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
                string[] receiverEmail = contextHttp.Request.Form.GetValues("receiverEmail");

                //Telephone country code 
                string[] phoneCountry = contextHttp.Request.Form.GetValues("phoneCountry");

                // A type to specify the receiver's phone number.
                // The PayRequest must pass either an email address or a phone number as the payment receiver.
                string[] phoneNumber = contextHttp.Request.Form.GetValues("phoneNumber");

                //Telephone extension
                string[] phoneExtn = contextHttp.Request.Form.GetValues("phoneExtn");

                // (Optional) Whether this receiver is the primary receiver, 
                // which makes the payment a chained payment.You can specify at most one primary receiver. 
                // Omit this field for simple and parallel payments. Allowable values are:
                //  true – Primary receiver
                //  false – Secondary receiver (default)
                string[] primaryReceiver = contextHttp.Request.Form.GetValues("primaryReceiver");

                // (Optional) Your own invoice or tracking number.
                //Character length and limitations: 127 single-byte alphanumeric characters
                string[] invoiceId = contextHttp.Request.Form.GetValues("invoiceId");

                // (Optional) The transaction type for the payment. Allowable values are:
                // GOODS – This is a payment for non-digital goods
                // SERVICE – This is a payment for services (default)
                // PERSONAL – This is a person-to-person payment
                // CASHADVANCE – This is a person-to-person payment for a cash advance
                // DIGITALGOODS – This is a payment for digital goods
                // BANK_MANAGED_WITHDRAWAL – This is a person-to-person payment for bank withdrawals, available only with special permission.
                string[] paymentType = contextHttp.Request.Form.GetValues("paymentType");
                //(Optional) The transaction subtype for the payment. 
                string[] paymentSubType = contextHttp.Request.Form.GetValues("paymentSubType");

	            List<Receiver> receivers = new List<Receiver>();
	            for(int i=0; i<amt.Length; i++) {
                    Receiver r = new Receiver(Convert.ToDecimal(amt[i]));
		            r.email = receiverEmail[i];
                    r.primary = Convert.ToBoolean(primaryReceiver[i]);
		            if(invoiceId[i] != string.Empty) {
			            r.invoiceId = invoiceId[i];
		            }
		            if(paymentType[i] != string.Empty) {
			            r.paymentType = paymentType[i];
		            }
		            if(paymentSubType[i] != string.Empty) {
			            r.paymentSubType = paymentSubType[i];
		            }
		            if(phoneCountry[i] != string.Empty && phoneNumber[i] != string.Empty) {
			            r.phone = new PhoneNumberType(phoneCountry[i], phoneNumber[i]);
			            if(phoneExtn[i] != string.Empty) {
				            r.phone.extension = phoneExtn[i];
			            }
		            }
                    receivers.Add(r);
	            }
	            request.receiverList = new ReceiverList(receivers);
            }

            // PayPal uses 3-character ISO-4217 codes for specifying currencies in fields and variables.  
            if(parameters["currencyCode"] != string.Empty) {
	            request.currencyCode = parameters["currencyCode"];
            }

            // The key used to create the payment that you want to refund
            if(parameters["payKey"] != string.Empty) {
	            request.payKey = parameters["payKey"];
            }

            // A PayPal transaction ID associated with the receiver whose payment 
            // you want to refund to the sender. Use field name characters exactly as shown.
            if(parameters["transactionId"] != string.Empty) {
	            request.transactionId = parameters["transactionId"];
            }

            // The tracking ID associated with the payment that you want to refund
            if(parameters["trackingId"] != string.Empty) {
                request.trackingId = parameters["trackingId"];
            }            
          
            AdaptivePaymentsService service = null;
            RefundResponse 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.Refund(request);
            }
            catch (System.Exception e)
            {
                contextHttp.Response.Write(e.Message);
                return;
            }

            Dictionary<string, string> responseValues = new Dictionary<string, string>();
            string redirectUrl = null;
            if (!(response.responseEnvelope.ack == AckCode.FAILURE) &&
                !(response.responseEnvelope.ack == AckCode.FAILUREWITHWARNING))
            {
                responseValues.Add("Currency code", response.currencyCode);
                int idx = 1;
                foreach (RefundInfo refund in response.refundInfoList.refundInfo)
                {
                    //Receiver's email address.Maximum length: 127 characters
                    responseValues.Add("Refund receiver " + idx, refund.receiver.email);
                    // Amount to be refunded to the receiver.
                    responseValues.Add("Refund amount " + idx, refund.receiver.amount.ToString());
                    // 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.
                    responseValues.Add("Refund status " + idx, refund.refundStatus);

                    
                    responseValues.Add("Acknowledgement", response.responseEnvelope.ack.ToString());
                }
            }
            Display(contextHttp, "Refund", responseValues, service.getLastRequest(), service.getLastResponse(), response.error, redirectUrl);
        }
        /// <summary>
        /// Handle ConfirmPreapproval API call
        /// </summary>
        /// <param name="contextHttp"></param>
        private void ConfirmPreapproval(HttpContext contextHttp)
        {
            NameValueCollection parameters = contextHttp.Request.Params;
            // error language : (Required) RFC 3066 language in which error messages are returned; by default it is en_US, which is the only language currently supported. 
            // preapproval key : (Required) A preapproval key that identifies the preapproval for which you want to retrieve details. The preapproval key is returned in the PreapprovalResponse message
            ConfirmPreapprovalRequest request = new ConfirmPreapprovalRequest(new RequestEnvelope("en_US"),
                parameters["preapprovalKey"]);

            // Set optional parameters
            //The sender's personal identification number, which was specified 
            //when the sender signed up for a preapproval.
            if (parameters["pin"] != string.Empty)
                request.pin = parameters["pin"];

            //Funding source ID.
            if (parameters["fundingSourceId"] != string.Empty)
                request.fundingSourceId = parameters["fundingSourceId"];
       
            AdaptivePaymentsService service = null;
            ConfirmPreapprovalResponse 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.ConfirmPreapproval(request);
            }
            catch (System.Exception e)
            {
                contextHttp.Response.Write(e.Message);
                return;
            }

            Dictionary<string, string> responseValues = new Dictionary<string, string>();
            string redirectUrl = null;
            if (!(response.responseEnvelope.ack == AckCode.FAILURE) &&
                !(response.responseEnvelope.ack == AckCode.FAILUREWITHWARNING))
            {
                //nothing to add
            }
            Display(contextHttp, "ConfirmPreapproval", responseValues, service.getLastRequest(), service.getLastResponse(), response.error, redirectUrl);
        }
        /// <summary>
        /// Handle PreapprovalDetails API call
        /// </summary>
        /// <param name="contextHttp"></param>
        private void PreapprovalDetails(HttpContext contextHttp)
        {
            NameValueCollection parameters = contextHttp.Request.Params;
            // error language : (Required) RFC 3066 language in which error messages are returned; by default it is en_US, which is the only language currently supported. 
            // preapproval key : (Required) A preapproval key that identifies the preapproval for which you want to retrieve details. The preapproval key is returned in the PreapprovalResponse message
            PreapprovalDetailsRequest request = new PreapprovalDetailsRequest(new RequestEnvelope("en_US"), 
                parameters["preapprovalKey"]);
            
            //  (Optional) An option that lets you retrieve a list of billing addresses for the sender.
            //     true – Includes the billing address in the response
            //     false – Omits the billing address from the response (default)
            // Note:
            // This field is available only to API callers with advanced permission levels. For information, refer to the section Adaptive Payments Permission Levels.
            if (parameters["getBillingAddress"] != string.Empty)
                request.getBillingAddress = Convert.ToBoolean(parameters["getBillingAddress"]);
           
            AdaptivePaymentsService service = null;
            PreapprovalDetailsResponse 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.PreapprovalDetails(request);
            }
            catch (System.Exception e)
            {
                contextHttp.Response.Write(e.Message);
                return;
            }

            Dictionary<string, string> responseValues = new Dictionary<string, string>();
            string redirectUrl = null;
            if (!(response.responseEnvelope.ack == AckCode.FAILURE) &&
                !(response.responseEnvelope.ack == AckCode.FAILUREWITHWARNING))
            {
                //Whether this preapproval is active, represented by the following values:
                //  ACTIVE – The preapproval is active
                //  CANCELED – The preapproval was explicitly canceled by the sender or by PayPal
                //  DEACTIVATED – The preapproval is not active; you can reactivate it by resetting the personal identification number (PIN) or by contacting PayPal
                responseValues.Add("Status", response.status);

                // First date for which the preapproval is valid.
                responseValues.Add("Starting date", response.startingDate);
                
                // Last date for which the preapproval is valid. Time is currently not supported.
                // Note:
                // You must specify a value unless you have specific permission from PayPal to 
                // omit this value.
                responseValues.Add("Ending date", response.endingDate);

                // 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.
                responseValues.Add("Sender email", response.senderEmail);

                responseValues.Add("Currency code", response.currencyCode);

                // The preapproved maximum total amount of all payments.
                // Note:
                // You must specify a value unless you have specific permission from PayPal to omit this value.
                responseValues.Add("Maximum amount (across all payments)", response.maxTotalAmountOfAllPayments.ToString());

                
                responseValues.Add("Acknowledgement", response.responseEnvelope.ack.ToString());
            }
            Display(contextHttp, "PreapprovalDetails", responseValues, service.getLastRequest(), service.getLastResponse(),
                response.error, redirectUrl);
        }
        /// <summary>
        /// Handle Preapproval API
        /// </summary>
        /// <param name="contextHttp"></param>
        private void Preapproval(HttpContext contextHttp)
        {
            NameValueCollection parameters = contextHttp.Request.Params;
            // error language : (Required) RFC 3066 language in which error messages are returned; by default it is en_US, which is the only language currently supported. 
            // 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 request = new PreapprovalRequest(new RequestEnvelope("en_US"), parameters["cancelUrl"], 
                    parameters["currencyCode"], parameters["returnUrl"], parameters["startingDate"]);
            
            // (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"] != 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"] != string.Empty && parameters["dayOfWeek"] != string.Empty) 
            {
                request.dayOfWeek = (PayPal.AdaptivePayments.Model.DayOfWeek)
                        Enum.Parse(typeof(PayPal.AdaptivePayments.Model.DayOfWeek), parameters["dayOfWeek"]);
            }

            //(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"] != string.Empty) 
            {
	            request.dateOfMonth = Convert.ToInt32(parameters["dateOfMonth"]);
            }

            // xs:dateTime (Optional) Last date for which the preapproval is valid. 
            // It cannot be later than one year from the starting date.
            // Note: You must specify a value unless you have specific permission 
            // from PayPal to omit this value. 
            if(parameters["endingDate"] != string.Empty) 
            {
	            request.endingDate = parameters["endingDate"];
            }

            // (Optional) The preapproved maximum amount per payment. 
            // It cannot exceed the preapproved maximum total amount of all payments. 
            if(parameters["maxAmountPerPayment"] != 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"] != 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"] != string.Empty) 
            {
	            request.maxNumberOfPaymentsPerPeriod = Convert.ToInt32(parameters["maxNumberOfPaymentsPerPeriod"]);
            }

            // The preapproved maximum total amount of all payments. 
            // It cannot exceed $2,000 USD or its equivalent in other currencies. 
            // Contact PayPal if you do not want to specify a maximum amount. 
            if(parameters["maxTotalAmountOfAllPayments"] != string.Empty) 
            {
	            request.maxTotalAmountOfAllPayments = Convert.ToDecimal(parameters["maxTotalAmountOfAllPayments"]);
            }

            //(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"] != string.Empty && parameters["paymentPeriod"] != string.Empty) 
            {
	            request.paymentPeriod = parameters["paymentPeriod"];
            }

            // (Optional) A note about the preapproval. 
            // Maximum length: 1000 characters, including newline characters 
            if(parameters["memo"] != string.Empty) 
            {
	            request.memo = parameters["memo"];
            }

            // 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"] != string.Empty) 
            {
	            request.ipnNotificationUrl = parameters["ipnNotificationUrl"];
            }

            // (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"] != string.Empty) 
            {
	            request.senderEmail = parameters["senderEmail"];
            }

            // (Optional) Whether a personal identification number (PIN) is required. 
            // It is one of the following values:

            //    NOT_REQUIRED – A PIN is not required (default)
            //    REQUIRED – A PIN is required; the sender must specify a PIN when setting up the preapproval on PayPal
            if(parameters["pinType"] != string.Empty && parameters["pinType"] != string.Empty) 
            {
	            request.pinType = parameters["pinType"];
            }

            // (Optional) The payer of PayPal fees. Allowable values are:
            //    SENDER – Sender pays all fees (for personal, implicit simple/parallel payments; do not use for chained or unilateral payments)
            //    PRIMARYRECEIVER – Primary receiver pays all fees (chained payments only)
            //    EACHRECEIVER – Each receiver pays their own fee (default, personal and unilateral payments)
            //    SECONDARYONLY – Secondary receivers pay all fees (use only for chained payments with one secondary receiver)
            if(parameters["feesPayer"] != string.Empty) 
            {
	            request.feesPayer = parameters["feesPayer"];
            }

            //(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"] != string.Empty)
            {
                request.displayMaxTotalAmount = Convert.ToBoolean(parameters["displayMaxTotalAmount"]);
            }
          
            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 e)
            {
                contextHttp.Response.Write(e.Message);
                return;
            }

            Dictionary<string, string> responseValues = new Dictionary<string, string>();
            string redirectUrl = null;
            if (!(response.responseEnvelope.ack == AckCode.FAILURE) &&
                !(response.responseEnvelope.ack == AckCode.FAILUREWITHWARNING))
            {
                //  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;
                responseValues.Add("Acknowledgement", response.responseEnvelope.ack.ToString());
                responseValues.Add("Redirect To PayPal", redirectUrl);
            }
            Display(contextHttp, "Preapproval", responseValues, service.getLastRequest(), service.getLastResponse(), response.error, redirectUrl);
        }
        /// <summary>
        /// Handle PaymentDetails API call
        /// </summary>
        /// <param name="contextHttp"></param>
        private void PaymentDetails(HttpContext contextHttp)
        {
            NameValueCollection parameters = contextHttp.Request.Params;
            PaymentDetailsRequest request = new PaymentDetailsRequest(new RequestEnvelope("en_US")); 
            // set optional parameters
            //(Optional) The pay key that identifies the payment for which 
            // you want to retrieve details. This is the pay key returned in the PayResponse message. 
            if (parameters["payKey"] != string.Empty)
                request.payKey = parameters["payKey"];
            // (Optional) The PayPal transaction ID associated with the payment. 
            // The IPN message associated with the payment contains the transaction ID. 
            if (parameters["transactionId"] != string.Empty)
                request.transactionId = parameters["transactionId"];
            // (Optional) The tracking ID that was specified for this payment 
            // in the PayRequest message. Maximum length: 127 characters 
            if (parameters["trackingId"] != string.Empty)
                request.trackingId = parameters["trackingId"];
          
            AdaptivePaymentsService service = null;
            PaymentDetailsResponse 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.PaymentDetails(request);
            }
            catch (System.Exception e)
            {
                contextHttp.Response.Write(e.Message);
                return;
            }

            Dictionary<string, string> responseValues = new Dictionary<string, string>();
            string redirectUrl = null;
            if (!(response.responseEnvelope.ack == AckCode.FAILURE) &&
                !(response.responseEnvelope.ack == AckCode.FAILUREWITHWARNING))
            {
                //(Optional) The pay key that identifies the payment 
                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.status);

                // The sender's email address. 
                responseValues.Add("Sender email", response.senderEmail);

                //Acknowledgement code. It is one of the following values:
                // Success – The operation completed successfully.
                // Failure – The operation failed.
                // SuccessWithWarning – The operation completed successfully; however, there is a warning message.
                // FailureWithWarning – The operation failed with a warning message.
                responseValues.Add("Acknowledgement", response.responseEnvelope.ack.ToString());

                // Whether the Pay request is set up to create a payment request with the SetPaymentOptions 
                // request, and then fulfill the payment with the ExecutePayment 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.
                responseValues.Add("Action Type", response.actionType);
            }
            Display(contextHttp, "PaymentDetails", responseValues, service.getLastRequest(), service.getLastResponse(), response.error, redirectUrl);
        }
        /// <summary>
        /// Handle GetUserLimits API call
        /// </summary>
        /// <param name="contextHttp"></param>
        private void GetUserLimits(HttpContext contextHttp)
        {
            NameValueCollection parameters = contextHttp.Request.Params;

            List<string> limitType = new List<string>();

            if (parameters["limitType"] != string.Empty)
            {
                limitType.Add(parameters["limitType"]);
            }

            AccountIdentifier accountId = new AccountIdentifier();
            if (parameters["email"] != string.Empty)
            {
                accountId.email = parameters["email"];
            }
            if (parameters["phoneCountry"] != string.Empty && parameters["phoneNumber"] != string.Empty)
            {
                accountId.phone = new PhoneNumberType(parameters["phoneCountry"], parameters["phoneNumber"]);
                if (parameters["phoneExtension"] != string.Empty)
                    accountId.phone.extension = parameters["phoneExtension"];
            }

            GetUserLimitsRequest request = new GetUserLimitsRequest(
                    new RequestEnvelope("en_US"), accountId, parameters["country"], 
                    parameters["currencyCode"], limitType);
         
            AdaptivePaymentsService service = null;
            GetUserLimitsResponse 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.GetUserLimits(request);
            }
            catch (System.Exception e)
            {
                contextHttp.Response.Write(e.Message);
                return;
            }
 
            Dictionary<string, string> responseValues = new Dictionary<string, string>();
            string redirectUrl = null;
            if (!(response.responseEnvelope.ack == AckCode.FAILURE) &&
                !(response.responseEnvelope.ack == AckCode.FAILUREWITHWARNING))
            {
                int idx = 1;
                foreach (UserLimit userLimit in response.userLimit)
                {
                    responseValues.Add("Limit amount " + idx,
                        userLimit.limitAmount.amount + userLimit.limitAmount.code);
                    responseValues.Add("Limit type " + idx, userLimit.limitType);
                    idx++;
                }
            }
            Display(contextHttp, "GetUserLimits", responseValues, service.getLastRequest(), service.getLastResponse(), response.error, redirectUrl);
        }       
Exemplo n.º 16
0
        /// <summary>
        /// Handle CancelPreapproval API call
        /// </summary>
        /// <param name="context"></param>
        private void CancelPreapproval(HttpContext context)
        {
            NameValueCollection parameters = context.Request.Params;
            CancelPreapprovalRequest req = new CancelPreapprovalRequest(new RequestEnvelope("en_US"),
                parameters["preapprovalKey"]);

            // All set. Fire the request
            AdaptivePaymentsService service = new AdaptivePaymentsService();
            CancelPreapprovalResponse resp = null;
            try
            {
                resp = service.CancelPreapproval(req);
            }
            catch (System.Exception e)
            {
                context.Response.Write(e.Message);
                return;
            }

            // Display response values.
            Dictionary<string, string> keyResponseParams = new Dictionary<string, string>();
            string redirectUrl = null;
            if (!(resp.responseEnvelope.ack == AckCode.FAILURE) &&
                !(resp.responseEnvelope.ack == AckCode.FAILUREWITHWARNING))
            {
                //Selenium Test Case
                keyResponseParams.Add("Acknowledgement", resp.responseEnvelope.ack.ToString());
            }
            displayResponse(context, "CancelPreapproval", keyResponseParams, service.getLastRequest(), service.getLastResponse(),
                resp.error, redirectUrl);
        }
Exemplo n.º 17
0
        /// <summary>
        /// Handle ConfirmPreapproval API call
        /// </summary>
        /// <param name="context"></param>
        private void ConfirmPreapproval(HttpContext context)
        {
            NameValueCollection parameters = context.Request.Params;
            ConfirmPreapprovalRequest req = new ConfirmPreapprovalRequest(new RequestEnvelope("en_US"),
                parameters["preapprovalKey"]);
            // Set optional parameters
            if (parameters["pin"] != "")
                req.pin = parameters["pin"];
            if (parameters["fundingSourceId"] != "")
                req.fundingSourceId = parameters["fundingSourceId"];

            // All set. Fire the request
            AdaptivePaymentsService service = new AdaptivePaymentsService();
            ConfirmPreapprovalResponse resp = null;
            try
            {
                resp = service.ConfirmPreapproval(req);
            }
            catch (System.Exception e)
            {
                context.Response.Write(e.Message);
                return;
            }

            // Display response values.
            Dictionary<string, string> keyResponseParams = new Dictionary<string, string>();
            string redirectUrl = null;
            if (!(resp.responseEnvelope.ack == AckCode.FAILURE) &&
                !(resp.responseEnvelope.ack == AckCode.FAILUREWITHWARNING))
            {
                //nothing to add
            }
            displayResponse(context, "ConfirmPreapproval", keyResponseParams, service.getLastRequest(), service.getLastResponse(),
                resp.error, redirectUrl);
        }
        /// <summary>
        /// Handle ConvertCurrency API call
        /// </summary>
        /// <param name="contextHttp"></param>
        private void ConvertCurrency(HttpContext contextHttp)
        {
            NameValueCollection parameters = contextHttp.Request.Params;
            // (Required) The currency code
            string[] fromCurrencyCodes = contextHttp.Request.Form.GetValues("currencyCode");

            //(Required) The amount to be converted.
            string[] fromCurrencyAmounts = contextHttp.Request.Form.GetValues("currencyAmount");

            // (Required) The currency code
            string[] toCurrencyCodes = contextHttp.Request.Form.GetValues("toCurrencyCode");

            List<CurrencyType> currencies = new List<CurrencyType>();
            for(int i=0; i<fromCurrencyCodes.Length; i++)
            {
                currencies.Add(
                    new CurrencyType(fromCurrencyCodes[i], Convert.ToDecimal(fromCurrencyAmounts[i]))
                );
            }
            CurrencyList baseAmountList = new CurrencyList(currencies);

            List<string> toCurrencyCodeList = new List<string>();
            for (int i = 0; i < toCurrencyCodes.Length; i++)
                toCurrencyCodeList.Add(toCurrencyCodes[i]);
            CurrencyCodeList convertToCurrencyList = new CurrencyCodeList(toCurrencyCodeList);

            ConvertCurrencyRequest request = new ConvertCurrencyRequest(
                new RequestEnvelope("en_US"), baseAmountList, convertToCurrencyList);
            
            // (Optional)The two-character ISO code for the country where the
		    // function is supposed to happen. The default value is US.
            if (parameters["countryCode"] != string.Empty)
                request.countryCode = parameters["countryCode"];

            // (Optional)The conversion type allows you to determine the converted amounts 
            // for a PayPal user in different currency conversion scenarios, e.g., 
            // sending a payment in a different currency than what this user holds, 
            // accepting payment in a different currency than what the user holds, 
            // or converting a balance to a different currency than the user holds.. 
            // The default value is SENDER_SIDE .
            if (parameters["conversionType"] != string.Empty)
                request.conversionType = parameters["conversionType"];

            AdaptivePaymentsService service = null;
            ConvertCurrencyResponse 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.ConvertCurrency(request);
            }
            catch (System.Exception e)
            {
                contextHttp.Response.Write(e.Message);
                return;
            }

            Dictionary<string, string> responseValues = new Dictionary<string, string>();
            string redirectUrl = null;
            if (!(response.responseEnvelope.ack == AckCode.FAILURE) &&
                !(response.responseEnvelope.ack == AckCode.FAILUREWITHWARNING))
            {
                if (response.estimatedAmountTable != null
                    && response.estimatedAmountTable.currencyConversionList != null)
                {
                    int idx = 1;

                    //The list of converted currencies.
                    foreach (CurrencyConversionList list in response.estimatedAmountTable.currencyConversionList)
                    {
                        responseValues.Add("Base amount " + idx,
                            list.baseAmount.amount + " " + list.baseAmount.code);
                        idx++;
                    }
                }

                
                responseValues.Add("Acknowledgement", response.responseEnvelope.ack.ToString());
            }
            Display(contextHttp, "ConvertCurrency", responseValues, service.getLastRequest(), service.getLastResponse(), response.error, redirectUrl);
        }
Exemplo n.º 19
0
        /// <summary>
        /// Handle ExecutePayment API call
        /// </summary>
        /// <param name="context"></param>
        private void ExecutePayment(HttpContext context)
        {
            NameValueCollection parameters = context.Request.Params;
            ExecutePaymentRequest req = new ExecutePaymentRequest(new RequestEnvelope("en_US"), parameters["payKey"]);

            //Fix for release
            req.fundingPlanId = parameters["fundingPlanId"];

            // All set. Fire the request
            AdaptivePaymentsService service = new AdaptivePaymentsService();
            ExecutePaymentResponse resp = null;
            try
            {
                resp = service.ExecutePayment(req);
            }
            catch (System.Exception e)
            {
                context.Response.Write(e.Message);
                return;
            }

            // Display response values.
            Dictionary<string, string> keyResponseParams = new Dictionary<string, string>();
            string redirectUrl = null;
            if (!(resp.responseEnvelope.ack == AckCode.FAILURE) &&
                !(resp.responseEnvelope.ack == AckCode.FAILUREWITHWARNING))
            {
                keyResponseParams.Add("Payment exeucution status", resp.paymentExecStatus);

                //Selenium Test Case
                keyResponseParams.Add("Acknowledgement", resp.responseEnvelope.ack.ToString());
            }
            displayResponse(context, "ExecutePayment", keyResponseParams, service.getLastRequest(), service.getLastResponse(),
                resp.error, redirectUrl);
        }
        /// <summary>
        /// Handle GetAllowedFundingSources API call
        /// </summary>
        /// <param name="contextHttp"></param>
        private void GetAllowedFundingSources(HttpContext contextHttp)
        {
            NameValueCollection parameters = contextHttp.Request.Params;
            // error language : (Required) RFC 3066 language in which error messages are returned; 
            // by default it is en_US, which is the only language currently supported. 
            //key : (Required) The preapproval key that identifies the preapproval
            GetAllowedFundingSourcesRequest request = 
                new GetAllowedFundingSourcesRequest(new RequestEnvelope("en_US"), parameters["key"]);

            AdaptivePaymentsService service = null;
            GetAllowedFundingSourcesResponse 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.GetAllowedFundingSources(request);
            }
            catch (System.Exception e)
            {
                contextHttp.Response.Write(e.Message);
                return;
            }

            Dictionary<string, string> responseValues = new Dictionary<string, string>();
            string redirectUrl = null;
            if (!(response.responseEnvelope.ack == AckCode.FAILURE) &&
                !(response.responseEnvelope.ack == AckCode.FAILUREWITHWARNING))
            {
                int idx = 1;
                foreach (FundingSource source in response.fundingSource)
                {
                    
                    responseValues.Add("Funding source id " + idx, source.fundingSourceId);

                    responseValues.Add("Funding source name " + idx, source.displayName);
                    idx++;
                }                
            }
            Display(contextHttp, "GetAllowedFundingSources", responseValues, service.getLastRequest(), service.getLastResponse(), response.error, redirectUrl);
        }
Exemplo n.º 21
0
        /// <summary>
        /// Handle GetPaymentOptions API call
        /// </summary>
        /// <param name="context"></param>
        private void GetPaymentOptions(HttpContext context)
        {
            NameValueCollection parameters = context.Request.Params;
            GetPaymentOptionsRequest req = new GetPaymentOptionsRequest(
                    new RequestEnvelope("en_US"), parameters["payKey"]);

            // All set. Fire the request
            AdaptivePaymentsService service = new AdaptivePaymentsService();
            GetPaymentOptionsResponse resp = null;
            try
            {
                resp = service.GetPaymentOptions(req);
            }
            catch (System.Exception e)
            {
                context.Response.Write(e.Message);
                return;
            }

            // Display response values.
            Dictionary<string, string> keyResponseParams = new Dictionary<string, string>();
            string redirectUrl = null;
            if (!(resp.responseEnvelope.ack == AckCode.FAILURE) &&
                !(resp.responseEnvelope.ack == AckCode.FAILUREWITHWARNING))
            {
                int idx = 1;
                foreach(ReceiverOptions option in resp.receiverOptions)
                {
                    keyResponseParams.Add("Receiver option " + idx, option.description);
                    if(option.receiver.email != null)
                        keyResponseParams.Add("Receiver email " + idx, option.receiver.email);
                    idx++;
                }
                if(resp.displayOptions != null)
                {
                    keyResponseParams.Add("Business name", resp.displayOptions.businessName);
                    keyResponseParams.Add("Header image", resp.displayOptions.headerImageUrl);
                    keyResponseParams.Add("Email header image", resp.displayOptions.emailHeaderImageUrl);
                }
                keyResponseParams.Add("Shipping address Id", resp.shippingAddressId);

                //Selenium Test Case
                keyResponseParams.Add("Acknowledgement", resp.responseEnvelope.ack.ToString());
            }
            displayResponse(context, "GetPaymentOptions", keyResponseParams, service.getLastRequest(), service.getLastResponse(),
                resp.error, redirectUrl);
        }
Exemplo n.º 22
0
        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);
        }
Exemplo n.º 23
0
        /// <summary>
        /// Handle GetUserLimits API call
        /// </summary>
        /// <param name="context"></param>
        private void GetUserLimits(HttpContext context)
        {
            NameValueCollection parameters = context.Request.Params;

            List<string> limitType = new List<string>();
            if(parameters["limitType"] != "")
                limitType.Add(parameters["limitType"]);
            AccountIdentifier accountId = new AccountIdentifier();
            if (parameters["email"] != "")
            {
                accountId.email = parameters["email"];
            }
            if (parameters["phoneCountry"] != "" && parameters["phoneNumber"] != "")
            {
                accountId.phone = new PhoneNumberType(parameters["phoneCountry"], parameters["phoneNumber"]);
                if (parameters["phoneExtension"] != "")
                    accountId.phone.extension = parameters["phoneExtension"];
            }

            GetUserLimitsRequest req = new GetUserLimitsRequest(
                    new RequestEnvelope("en_US"), accountId, parameters["country"],
                    parameters["currencyCode"], limitType);

            // All set. Fire the request
            AdaptivePaymentsService service = new AdaptivePaymentsService();
            GetUserLimitsResponse resp = null;
            try
            {
                resp = service.GetUserLimits(req);
            }
            catch (System.Exception e)
            {
                context.Response.Write(e.Message);
                return;
            }

            // Display response values.
            Dictionary<string, string> keyResponseParams = new Dictionary<string, string>();
            string redirectUrl = null;
            if (!(resp.responseEnvelope.ack == AckCode.FAILURE) &&
                !(resp.responseEnvelope.ack == AckCode.FAILUREWITHWARNING))
            {
                int idx = 1;
                foreach (UserLimit userLimit in resp.userLimit)
                {
                    keyResponseParams.Add("Limit amount " + idx,
                        userLimit.limitAmount.amount + userLimit.limitAmount.code);
                    keyResponseParams.Add("Limit type " + idx, userLimit.limitType);
                    idx++;
                }
            }
            displayResponse(context, "GetAvailableShippingAddresses", keyResponseParams, service.getLastRequest(), service.getLastResponse(),
                resp.error, redirectUrl);
        }
    // # 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;
    }
Exemplo n.º 25
0
        /// <summary>
        /// Handle PaymentDetails API call
        /// </summary>
        /// <param name="context"></param>
        private void PaymentDetails(HttpContext context)
        {
            NameValueCollection parameters = context.Request.Params;
            PaymentDetailsRequest req = new PaymentDetailsRequest(new RequestEnvelope("en_US"));
            // set optional parameters
            if (parameters["payKey"] != "")
                req.payKey = parameters["payKey"];
            if (parameters["transactionId"] != "")
                req.transactionId = parameters["transactionId"];
            if (parameters["trackingId"] != "")
                req.trackingId = parameters["trackingId"];

            // All set. Fire the request
            AdaptivePaymentsService service = new AdaptivePaymentsService();
            PaymentDetailsResponse resp = null;
            try
            {
                resp = service.PaymentDetails(req);
            }
            catch (System.Exception e)
            {
                context.Response.Write(e.Message);
                return;
            }

            // Display response values.
            Dictionary<string, string> keyResponseParams = new Dictionary<string, string>();
            string redirectUrl = null;
            if (!(resp.responseEnvelope.ack == AckCode.FAILURE) &&
                !(resp.responseEnvelope.ack == AckCode.FAILUREWITHWARNING))
            {
                keyResponseParams.Add("Pay key", resp.payKey);
                keyResponseParams.Add("Payment execution status", resp.status);
                keyResponseParams.Add("Sender email", resp.senderEmail);

                //Selenium Test Case
                keyResponseParams.Add("Acknowledgement", resp.responseEnvelope.ack.ToString());
                keyResponseParams.Add("Action Type", resp.actionType);
            }
            displayResponse(context, "PaymentDetails", keyResponseParams, service.getLastRequest(), service.getLastResponse(),
                resp.error, redirectUrl);
        }
		public override ProcessPaymentResult ProcessPayment(ProcessPaymentEvaluationContext context)
		{
			var retVal = new ProcessPaymentResult();

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

			var url = string.Empty;
			if (!string.IsNullOrEmpty(context.Store.SecureUrl))
			{
				url = context.Store.SecureUrl;
			}
			else
			{
				url = context.Store.Url;
			}

			var config = GetConfigMap();

			var service = new AdaptivePaymentsService(config);

			var request = CreatePaypalRequest(context.Order, context.Payment, url);

			var response = service.Pay(request);

			if (response.error != null && response.error.Count > 0)
			{
				var sb = new StringBuilder();
				foreach (var error in response.error)
				{
					sb.AppendLine(error.message);
				}
				retVal.Error = sb.ToString();
				retVal.NewPaymentStatus = PaymentStatus.Voided;
			}
			else
			{
				retVal.OuterId = response.payKey;
				retVal.IsSuccess = true;
				var redirectBaseUrl = GetBaseUrl(Mode);
				retVal.RedirectUrl = string.Format(redirectBaseUrl, retVal.OuterId);
				retVal.NewPaymentStatus = PaymentStatus.Pending;
			}

			return retVal;
		}
Exemplo n.º 27
0
        /// <summary>
        /// Handle PreapprovalDetails API call
        /// </summary>
        /// <param name="context"></param>
        private void PreapprovalDetails(HttpContext context)
        {
            NameValueCollection parameters = context.Request.Params;
            PreapprovalDetailsRequest req = new PreapprovalDetailsRequest(new RequestEnvelope("en_US"),
                parameters["preapprovalKey"]);
            // set optional parameters
            if (parameters["getBillingAddress"] != "")
                req.getBillingAddress = Boolean.Parse(parameters["getBillingAddress"]);

            // All set. Fire the request
            AdaptivePaymentsService service = new AdaptivePaymentsService();
            PreapprovalDetailsResponse resp = null;
            try
            {
                resp = service.PreapprovalDetails(req);
            }
            catch (System.Exception e)
            {
                context.Response.Write(e.Message);
                return;
            }

            // Display response values.
            Dictionary<string, string> keyResponseParams = new Dictionary<string, string>();
            string redirectUrl = null;
            if (!(resp.responseEnvelope.ack == AckCode.FAILURE) &&
                !(resp.responseEnvelope.ack == AckCode.FAILUREWITHWARNING))
            {
                keyResponseParams.Add("Status", resp.status);
                keyResponseParams.Add("Starting date", resp.startingDate);
                keyResponseParams.Add("Ending date", resp.endingDate);
                keyResponseParams.Add("Sender email", resp.senderEmail);
                keyResponseParams.Add("Currency code", resp.currencyCode);
                keyResponseParams.Add("Maximum amount (across all payments)", resp.maxTotalAmountOfAllPayments.ToString());

                //Selenium Test Case
                keyResponseParams.Add("Acknowledgement", resp.responseEnvelope.ack.ToString());
            }
            displayResponse(context, "PreapprovalDetails", keyResponseParams, service.getLastRequest(), service.getLastResponse(),
                resp.error, redirectUrl);
        }
		public override PostProcessPaymentResult PostProcessPayment(PostProcessPaymentEvaluationContext context)
		{
			var retVal = new PostProcessPaymentResult();

			var config = GetConfigMap();

			var service = new AdaptivePaymentsService(config);

			var response = service.PaymentDetails(new PaymentDetailsRequest
			{
				payKey = context.OuterId,
				requestEnvelope = new RequestEnvelope { errorLanguage = "en_US" }
			});

			if (response.status == "COMPLETED")
			{
				retVal.IsSuccess = true;
				retVal.NewPaymentStatus = PaymentStatus.Paid;
			}
			else if (response.status == "INCOMPLETE" && response.status == "ERROR" && response.status == "REVERSALERROR")
			{
				if (response.error != null && response.error.Count > 0)
				{
					var sb = new StringBuilder();
					foreach (var error in response.error)
					{
						sb.AppendLine(error.message);
					}
					retVal.Error = sb.ToString();
				}
				else
				{
					retVal.Error = "payment canceled";
				}

				retVal.NewPaymentStatus = PaymentStatus.Voided;
			}
			else
			{
				retVal.NewPaymentStatus = PaymentStatus.Pending;
			}

			return retVal;
		}
    // # 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;
    }
Exemplo n.º 30
0
        /// <summary>
        /// Handle SetPaymentOptions API call
        /// </summary>
        /// <param name="context"></param>
        private void SetPaymentOptions(HttpContext context)
        {
            NameValueCollection parameters = context.Request.Params;
            SetPaymentOptionsRequest req = new SetPaymentOptionsRequest(
                    new RequestEnvelope("en_US"), parameters["payKey"]);
            if (parameters["institutionId"] != "")
            {
                req.initiatingEntity = new InitiatingEntity();
                req.initiatingEntity.institutionCustomer = new InstitutionCustomer(
                    parameters["institutionId"], parameters["firstName"],
                    parameters["lastName"], parameters["displayName"],
                    parameters["institutionCustomerId"], parameters["countryCode"]);
                if (parameters["email"] != "")
                {
                    req.initiatingEntity.institutionCustomer.email = parameters["email"];
                }
            }
            if (parameters["emailHeaderImageUrl"] != "" || parameters["emailMarketingImageUrl"] != ""
                || parameters["headerImageUrl"] != "" || parameters["businessName"] != "")
            {
                req.displayOptions = new DisplayOptions();
                if (parameters["emailHeaderImageUrl"] != "" )
                    req.displayOptions.emailHeaderImageUrl = parameters["emailHeaderImageUrl"];
                if (parameters["emailMarketingImageUrl"] != "")
                    req.displayOptions.emailMarketingImageUrl = parameters["emailMarketingImageUrl"];
                if(parameters["headerImageUrl"] != "" )
                    req.displayOptions.headerImageUrl = parameters["headerImageUrl"];
                if(parameters["businessName"] != "")
                    req.displayOptions.businessName = parameters["businessName"];
            }
            if (parameters["shippingAddressId"] != "")
            {
                req.shippingAddressId = parameters["shippingAddressId"];
            }
            if (parameters["requireShippingAddressSelection"] != "" || parameters["referrerCode"] != "")
            {
                req.senderOptions = new SenderOptions();
                if (parameters["requireShippingAddressSelection"] != "")
                    req.senderOptions.requireShippingAddressSelection =
                        Boolean.Parse(parameters["requireShippingAddressSelection"]);
                if (parameters["referrerCode"] != "")
                    req.senderOptions.referrerCode = parameters["referrerCode"];
            }
            req.receiverOptions = new List<ReceiverOptions>();
            ReceiverOptions receiverOption = new ReceiverOptions();
            req.receiverOptions.Add(receiverOption);
            if (parameters["description"] != "")
                receiverOption.description = parameters["description"];
            if (parameters["customId"] != "")
                receiverOption.customId = parameters["customId"];

            string[] name = context.Request.Form.GetValues("name");
            string[] identifier = context.Request.Form.GetValues("identifier");
            string[] price = context.Request.Form.GetValues("price");
            string[] itemPrice = context.Request.Form.GetValues("itemPrice");
            string[] itemCount = context.Request.Form.GetValues("itemCount");
            if (name.Length > 0 && name[0] != "")
            {
                receiverOption.invoiceData = new InvoiceData();
                for (int j = 0; j < name.Length; j++)
                {
                    InvoiceItem item = new InvoiceItem();
                    if (name[j] != "")
                        item.name = name[j];
                    if (identifier[j] != "")
                        item.identifier = identifier[j];
                    if (price[j] != "")
                        item.price = Decimal.Parse(price[j]);
                    if (itemPrice[j] != "")
                        item.itemPrice = Decimal.Parse(itemPrice[j]);
                    if (itemCount[j] != "")
                        item.itemCount = Int32.Parse(itemCount[j]);
                    receiverOption.invoiceData.item.Add(item);
                }

                if (parameters["totalTax"] != "")
                    receiverOption.invoiceData.totalTax = Decimal.Parse(parameters["totalTax"]);
                if (parameters["totalShipping"] != "")
                    receiverOption.invoiceData.totalShipping = Decimal.Parse(parameters["totalShipping"]);
            }
            if (parameters["emailIdentifier"] != "" ||
                (parameters["phoneCountry"] != "" && parameters["phoneNumber"] != ""))
            {
                receiverOption.receiver = new ReceiverIdentifier();
                if(parameters["emailIdentifier"] != "")
                    receiverOption.receiver.email = parameters["emailIdentifier"];
                if (parameters["phoneCountry"] != "" && parameters["phoneNumber"] != "")
                {
                    receiverOption.receiver.phone =
                        new PhoneNumberType(parameters["phoneCountry"], parameters["phoneNumber"]);
                    if (parameters["phoneExtn"] != "")
                        receiverOption.receiver.phone.extension = parameters["phoneExtn"];
                }
            }
            if (parameters["receiverReferrerCode"] != "")
                receiverOption.referrerCode = parameters["receiverReferrerCode"];

            // All set. Fire the request
            AdaptivePaymentsService service = new AdaptivePaymentsService();
            SetPaymentOptionsResponse resp = null;
            try
            {
                resp = service.SetPaymentOptions(req);
            }
            catch (System.Exception e)
            {
                context.Response.Write(e.Message);
                return;
            }

            // Display response values.
            Dictionary<string, string> keyResponseParams = new Dictionary<string, string>();

            //Selenium Test Case
            if (!(resp.responseEnvelope.ack == AckCode.FAILURE) &&
                !(resp.responseEnvelope.ack == AckCode.FAILUREWITHWARNING))
            {
                keyResponseParams.Add("Acknowledgement", resp.responseEnvelope.ack.ToString());
            }

            displayResponse(context, "SetPaymentOptions", keyResponseParams, service.getLastRequest(), service.getLastResponse(),
                resp.error, null);
        }