示例#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 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);
        }
        /// <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);
        }
        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);
        }
        /// <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>
        /// Handles Deferred Pay API calls
        /// </summary>
        /// <param name="contextHttp"></param>
        private void DeferredPayment(HttpContext contextHttp)
        {
            NameValueCollection parameters = contextHttp.Request.Params;
            ReceiverList receiverList = new ReceiverList();
            receiverList.receiver = new List<Receiver>();
            PayRequest request = new PayRequest();
            Receiver rec = new Receiver();

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

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

            receiverList.receiver.Add(rec);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            receiverList.Add(sampleReceiver);

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

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

            // URL to redirect the sender's browser to after canceling the approval
            // for a payment; it is always required but only used for payments that
            // require approval (explicit payments)            
            if (parameters["cancelURL"] != null && parameters["cancelURL"].Trim() != string.Empty)
            {
                request.cancelUrl = parameters["cancelURL"];
            }
            
            // The code for the currency in which the payment is made; you can
            // specify only one currency, regardless of the number of receivers
            if (parameters["currencyCode"] != null && parameters["currencyCode"].Trim() != string.Empty)
            {
                request.currencyCode = parameters["currencyCode"];
            }
               
            // URL to redirect the sender's browser to after the sender has logged
            // into PayPal and approved a payment; it is always required but only
            // used if a payment requires explicit approval
            if (parameters["returnURL"] != null && parameters["returnURL"].Trim() != string.Empty)
            {
                request.returnUrl = parameters["returnURL"];
            }
            
            // (Optional) The URL to which you want all IPN messages for this
            // payment to be sent. Maximum length: 1024 characters
            if (parameters["ipnNotificationURL"] != null && parameters["ipnNotificationURL"].Trim() != string.Empty)
            {
                request.ipnNotificationUrl = parameters["ipnNotificationURL"];
            }
           
            AdaptivePaymentsService service = null;
            PayResponse response = null;
            try
            {
                // Configuration map containing signature credentials and other required configuration.
                // For a full list of configuration parameters refer in wiki page 
                // (https://github.com/paypal/sdk-core-dotnet/wiki/SDK-Configuration-Parameters)
                Dictionary<string, string> configurationMap = Configuration.GetAcctAndConfig();

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

            Dictionary<string, string> responseValues = new Dictionary<string, string>();
            string redirectUrl = null;
            responseValues.Add("Acknowledgement", response.responseEnvelope.ack.ToString().Trim().ToUpper());
   
            Display(contextHttp, "PreapprovalPayment", "AdaptivePayments", responseValues, service.getLastRequest(), service.getLastResponse(), response.error, redirectUrl);
        }
        private void PerformPaypalDuesPaymentCheckout(CreateInvoiceReturn output)
        {
            try
            {
                var duesItem = invoice.ItemsDues.FirstOrDefault();

                if (duesItem != null)
                {
                    var memberPaying = MemberCache.GetMemberDisplay(duesItem.MemberPaidId);
                    var leagueSettings = Dues.DuesFactory.GetDuesSettings(duesItem.DuesId);
                    if (leagueSettings != null)
                    {
                        ReceiverList receiverList = new ReceiverList();
                        //RDNation as a reciever
                        Receiver recRDNation = new Receiver(duesItem.PriceAfterFees);
                        if (invoice.Mode == PaymentMode.Live)
                            recRDNation.email = ServerConfig.DEFAULT_ADMIN_EMAIL_ADMIN;
                        else if (invoice.Mode == PaymentMode.Test)
                            recRDNation.email = ServerConfig.PAYPAL_SELLER_DEBUG_ADDRESS;
                        recRDNation.primary = true;

                        //if we modify this invoiceID, 
                        //you need to modify this code here: 
                        recRDNation.invoiceId = invoice.InvoiceId.ToString().Replace("-", "") + ": " + leagueSettings.LeagueOwnerName + " Dues Payment";
                        recRDNation.paymentType = PaymentTypeEnum.SERVICE.ToString();
                        receiverList.receiver.Add(recRDNation);

                        Receiver recLeague = new Receiver(duesItem.BasePrice);
                        recLeague.amount = duesItem.BasePrice;
                        if (invoice.Mode == PaymentMode.Live)
                            recLeague.email = leagueSettings.PayPalEmailAddress;
                        else if (invoice.Mode == PaymentMode.Test)
                            recLeague.email = "*****@*****.**";

                        recLeague.primary = false;
                        //if we modify this invoiceID, 
                        //you need to modify this code here: 
                        recLeague.invoiceId = invoice.InvoiceId.ToString().Replace("-", "") + ": " + leagueSettings.LeagueOwnerName + " Dues Payment";
                        recLeague.paymentType = PaymentTypeEnum.SERVICE.ToString();
                        receiverList.receiver.Add(recLeague);

                        PayRequest req = new PayRequest(new RequestEnvelope("en_US"), ActionTypeEnum.PAY.ToString(), ServerConfig.LEAGUE_DUES_MANAGEMENT_URL + leagueSettings.LeagueOwnerId.ToString().Replace("-", ""), invoice.Currency, receiverList, ServerConfig.LEAGUE_DUES_RECEIPT_URL + invoice.InvoiceId.ToString().Replace("-", ""));
                        req.feesPayer = FeesPayerEnum.PRIMARYRECEIVER.ToString();
                        req.memo = "Dues payment for " + leagueSettings.LeagueOwnerName + " from " + memberPaying.DerbyName + " for " + duesItem.PaidForDate.ToShortDateString();
                        req.reverseAllParallelPaymentsOnError = false;
                        req.trackingId = invoice.InvoiceId.ToString().Replace("-", "");
                        if (invoice.Mode == PaymentMode.Live)
                            req.ipnNotificationUrl = ServerConfig.PAYPAL_IPN_HANDLER;
                        else if (invoice.Mode == PaymentMode.Test)
                            req.ipnNotificationUrl = ServerConfig.PAYPAL_IPN_HANDLER_DEBUG;

                        // All set. Fire the request            
                        AdaptivePaymentsService service = new AdaptivePaymentsService();
                        PayResponse resp = service.Pay(req);



                        // 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))
                        {
                            //EmailServer.EmailServer.SendEmail(ServerConfig.DEFAULT_EMAIL, ServerConfig.DEFAULT_EMAIL_FROM_NAME, ServerConfig.DEFAULT_ADMIN_EMAIL_ADMIN, "Paypal Dues Payment Waiting To be Finished", invoice.InvoiceId + " Amount:" + duesItem.PriceAfterFees + ":" + leagueSettings.PayPalEmailAddress);

                            if (invoice.Mode == PaymentMode.Live)
                                redirectUrl = PaypalPaymentFactory.GetBaseUrl(PaypalPaymentFactory.PaypalMode.live);
                            else if (invoice.Mode == PaymentMode.Test)
                                redirectUrl = PaypalPaymentFactory.GetBaseUrl(PaypalPaymentFactory.PaypalMode.test);

                            redirectUrl += "?cmd=_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());
                            output.RedirectLink = redirectUrl;
                            output.Status = InvoiceStatus.Pending_Payment_From_Paypal;
                        }
                        else
                        {
                            if (resp.error.FirstOrDefault().message.Contains(ServerConfig.DEFAULT_ADMIN_EMAIL_ADMIN + " is restricted"))
                            {
                                output.Status = InvoiceStatus.Paypal_Email_Not_Confirmed;

                                var emailData = new Dictionary<string, string>
                                        {
                                            { "confirmPaypalAccountLink",ServerConfig.WIKI_URL_FOR_CONFIRMED_PAYPAL_ACCOUNT},
                                            { "paypalEmailAccount", leagueSettings.PayPalEmailAddress},
                                            { "duesSettingsLink", ServerConfig.LEAGUE_DUES_SETTINGS_URL +leagueSettings.LeagueOwnerId.ToString().Replace("-", "") + "/" + leagueSettings.DuesId.ToString().Replace("-", "")}
                                                                                    };

                                EmailServer.EmailServer.SendEmail(ServerConfig.DEFAULT_EMAIL, ServerConfig.DEFAULT_EMAIL_FROM_NAME, ServerConfig.DEFAULT_EMAIL, EmailServer.EmailServer.DEFAULT_SUBJECT + " Paypal Email Is Restricted: " + resp.error.FirstOrDefault().message, emailData, EmailServer.EmailServerLayoutsEnum.PaypalEmailIsRestricted);

                            }
                            //paypal account hasn't been confirmed by the league.
                            else if (resp.error.FirstOrDefault().message.Contains("isn't confirmed by PayPal") || resp.error.FirstOrDefault().message.Contains("is restricted") || resp.error.FirstOrDefault().message.Contains("fields are specified to identify a receiver"))
                            {
                                //if the paypal account hasn't been confirmed, we send the league an email
                                //and disable their paypal account for dues.
                                output.Status = InvoiceStatus.Paypal_Email_Not_Confirmed;

                                var emailData = new Dictionary<string, string>
                                        {
                                            { "confirmPaypalAccountLink",ServerConfig.WIKI_URL_FOR_CONFIRMED_PAYPAL_ACCOUNT},
                                            { "paypalEmailAccount", leagueSettings.PayPalEmailAddress},
                                            { "duesSettingsLink", ServerConfig.LEAGUE_DUES_SETTINGS_URL +leagueSettings.LeagueOwnerId.ToString().Replace("-", "") + "/" + leagueSettings.DuesId.ToString().Replace("-", "")}
                                                                                    };
                                if (resp.error.FirstOrDefault().message.Contains("isn't confirmed by PayPal"))
                                {
                                    if (!String.IsNullOrEmpty(leagueSettings.PayPalEmailAddress))
                                        EmailServer.EmailServer.SendEmail(ServerConfig.DEFAULT_EMAIL, ServerConfig.DEFAULT_EMAIL_FROM_NAME, leagueSettings.PayPalEmailAddress, EmailServer.EmailServer.DEFAULT_SUBJECT + " Paypal Email Isn't Confirmed", emailData, EmailServer.EmailServerLayoutsEnum.PayPalEmailIsNotConfirmed);
                                    if (!String.IsNullOrEmpty(leagueSettings.LeagueEmailAddress))
                                        EmailServer.EmailServer.SendEmail(ServerConfig.DEFAULT_EMAIL, ServerConfig.DEFAULT_EMAIL_FROM_NAME, leagueSettings.LeagueEmailAddress, EmailServer.EmailServer.DEFAULT_SUBJECT + " Paypal Email Isn't Confirmed", emailData, EmailServer.EmailServerLayoutsEnum.PayPalEmailIsNotConfirmed);
                                    EmailServer.EmailServer.SendEmail(ServerConfig.DEFAULT_EMAIL, ServerConfig.DEFAULT_EMAIL_FROM_NAME, ServerConfig.DEFAULT_EMAIL, EmailServer.EmailServer.DEFAULT_SUBJECT + " Paypal Email Isn't Confirmed: " + resp.error.FirstOrDefault().message, emailData, EmailServer.EmailServerLayoutsEnum.PayPalEmailIsNotConfirmed);
                                }
                                if (resp.error.FirstOrDefault().message.Contains("is restricted"))
                                {
                                    if (!String.IsNullOrEmpty(leagueSettings.PayPalEmailAddress))
                                        EmailServer.EmailServer.SendEmail(ServerConfig.DEFAULT_EMAIL, ServerConfig.DEFAULT_EMAIL_FROM_NAME, leagueSettings.PayPalEmailAddress, EmailServer.EmailServer.DEFAULT_SUBJECT + " Paypal Email Is Restricted", emailData, EmailServer.EmailServerLayoutsEnum.PaypalEmailIsRestricted);
                                    if (!String.IsNullOrEmpty(leagueSettings.LeagueEmailAddress))
                                        EmailServer.EmailServer.SendEmail(ServerConfig.DEFAULT_EMAIL, ServerConfig.DEFAULT_EMAIL_FROM_NAME, leagueSettings.LeagueEmailAddress, EmailServer.EmailServer.DEFAULT_SUBJECT + " Paypal Email Is Restricted", emailData, EmailServer.EmailServerLayoutsEnum.PaypalEmailIsRestricted);
                                    EmailServer.EmailServer.SendEmail(ServerConfig.DEFAULT_EMAIL, ServerConfig.DEFAULT_EMAIL_FROM_NAME, ServerConfig.DEFAULT_EMAIL, EmailServer.EmailServer.DEFAULT_SUBJECT + " Paypal Email Is Restricted: " + resp.error.FirstOrDefault().message, emailData, EmailServer.EmailServerLayoutsEnum.PaypalEmailIsRestricted);
                                }
                                if (resp.error.FirstOrDefault().message.Contains("specified to identify a receiver"))
                                {
                                    if (!String.IsNullOrEmpty(leagueSettings.PayPalEmailAddress))
                                        EmailServer.EmailServer.SendEmail(ServerConfig.DEFAULT_EMAIL, ServerConfig.DEFAULT_EMAIL_FROM_NAME, leagueSettings.PayPalEmailAddress, EmailServer.EmailServer.DEFAULT_SUBJECT + " Paypal Email Not Specified", emailData, EmailServer.EmailServerLayoutsEnum.PaypalEmailIsRestricted);
                                    if (!String.IsNullOrEmpty(leagueSettings.LeagueEmailAddress))
                                        EmailServer.EmailServer.SendEmail(ServerConfig.DEFAULT_EMAIL, ServerConfig.DEFAULT_EMAIL_FROM_NAME, leagueSettings.LeagueEmailAddress, EmailServer.EmailServer.DEFAULT_SUBJECT + " Paypal Email Not Specified", emailData, EmailServer.EmailServerLayoutsEnum.PaypalEmailIsRestricted);
                                    EmailServer.EmailServer.SendEmail(ServerConfig.DEFAULT_EMAIL, ServerConfig.DEFAULT_EMAIL_FROM_NAME, ServerConfig.DEFAULT_EMAIL, EmailServer.EmailServer.DEFAULT_SUBJECT + " Paypal Email Not Specified: " + resp.error.FirstOrDefault().message, emailData, EmailServer.EmailServerLayoutsEnum.PaypalEmailIsRestricted);
                                }
                                Dues.DuesFactory.DisablePaypalDuesAccountForLeague(leagueSettings.DuesId);

                            }
                            else
                            {
                                output.Status = InvoiceStatus.Failed;
                                throw new Exception("Failure Payment " + leagueSettings.PayPalEmailAddress + ":" + resp.error.FirstOrDefault().message + ":" + Newtonsoft.Json.JsonConvert.SerializeObject(req));
                            }
                        }

                    }
                }
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
        }
        private string PerformPaypalInStorePaymentCheckout()
        {
            try
            {
                var items = invoice.ItemsInvoice;

                if (items.Count > 0)
                {
                    Payment.PaymentGateway pg = new Payment.PaymentGateway();
                    var merchant = pg.GetMerchant(invoice.MerchantId);

                    if (merchant != null)
                    {
                        ReceiverList receiverList = new ReceiverList();
                        //RDNation as a reciever
                        Receiver recRDNation = new Receiver(invoice.FinancialData.BasePriceForItems + invoice.FinancialData.ShippingCost);
                        if (invoice.Mode == PaymentMode.Live)
                            recRDNation.email = ServerConfig.DEFAULT_ADMIN_EMAIL_ADMIN;
                        else if (invoice.Mode == PaymentMode.Test)
                            recRDNation.email = ServerConfig.PAYPAL_SELLER_DEBUG_ADDRESS;
                        if (ServerConfig.DEFAULT_ADMIN_EMAIL_ADMIN != merchant.PaypalEmail)
                            recRDNation.primary = true;
                        //if we modify this invoiceID, 
                        //you need to modify this code here: 
                        recRDNation.invoiceId = invoice.InvoiceId.ToString().Replace("-", "") + ": Payment to " + merchant.ShopName;
                        recRDNation.paymentType = PaymentTypeEnum.GOODS.ToString();
                        receiverList.receiver.Add(recRDNation);
                        if (ServerConfig.DEFAULT_ADMIN_EMAIL_ADMIN != merchant.PaypalEmail)
                        {
                            Receiver recLeague = new Receiver(invoice.FinancialData.PriceSubtractingRDNationFees);
                            recLeague.amount = invoice.FinancialData.PriceSubtractingRDNationFees;
                            if (invoice.Mode == PaymentMode.Live)
                                recLeague.email = merchant.PaypalEmail;
                            else if (invoice.Mode == PaymentMode.Test)
                                recLeague.email = "*****@*****.**";
                            recLeague.primary = false;
                            //if we modify this invoiceID, 
                            //you need to modify this code here: 
                            recLeague.invoiceId = invoice.InvoiceId.ToString().Replace("-", "") + ": Payment to " + merchant.ShopName;
                            recLeague.paymentType = PaymentTypeEnum.GOODS.ToString();
                            receiverList.receiver.Add(recLeague);
                        }

                        PayRequest req = new PayRequest(new RequestEnvelope("en_US"), ActionTypeEnum.PAY.ToString(), ServerConfig.STORE_MERCHANT_CART_URL + merchant.MerchantId.ToString().Replace("-", ""), invoice.Currency, receiverList, ServerConfig.STORE_MERCHANT_RECEIPT_URL + invoice.InvoiceId.ToString().Replace("-", ""));
                        if (ServerConfig.DEFAULT_ADMIN_EMAIL_ADMIN != merchant.PaypalEmail)
                            req.feesPayer = FeesPayerEnum.PRIMARYRECEIVER.ToString();
                        req.memo = "Payment to " + merchant.ShopName + ": " + invoice.InvoiceId.ToString().Replace("-", "");
                        req.reverseAllParallelPaymentsOnError = false;
                        if (invoice.Mode == PaymentMode.Live)
                            req.ipnNotificationUrl = ServerConfig.PAYPAL_IPN_HANDLER;
                        else if (invoice.Mode == PaymentMode.Test)
                            req.ipnNotificationUrl = ServerConfig.PAYPAL_IPN_HANDLER_DEBUG;

                        // All set. Fire the request            
                        AdaptivePaymentsService service = new AdaptivePaymentsService();
                        PayResponse resp = service.Pay(req);

                        // 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))
                        {
                            EmailServer.EmailServer.SendEmail(ServerConfig.DEFAULT_EMAIL, ServerConfig.DEFAULT_EMAIL_FROM_NAME, ServerConfig.DEFAULT_ADMIN_EMAIL_ADMIN, "Paypal Store Item Waiting To be Purchased", invoice.InvoiceId + " Amount:" + invoice.FinancialData.BasePriceForItems + ":" + merchant.PaypalEmail);

                            if (invoice.Mode == PaymentMode.Live)
                                redirectUrl = PaypalPaymentFactory.GetBaseUrl(PaypalPaymentFactory.PaypalMode.live);
                            else if (invoice.Mode == PaymentMode.Test)
                                redirectUrl = PaypalPaymentFactory.GetBaseUrl(PaypalPaymentFactory.PaypalMode.test);

                            redirectUrl += "?cmd=_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());
                            return redirectUrl;
                        }
                        else
                        {

                            throw new Exception("Failure Payment " + merchant.PaypalEmail + ":" + invoice.InvoiceId + ":" + resp.error.FirstOrDefault().message);
                        }

                    }
                }
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
            return String.Empty;
        }
示例#11
0
        private PayRequest CreatePayment(Payment payment)
        {
            // # PayRequest
            // The code for the language in which errors are returned
            var envelopeRequest = new RequestEnvelope {errorLanguage = "en_US"};

            var listReceiver = new List<Receiver>();

            // Amount to be credited to the receiver's account
            var amountPrimary = payment.Amount * 0.98M;
            var amountSecundary = payment.Amount * 0.02M;

            var receivePrimary = new Receiver(amountPrimary) {email = payment.SecundaryReceiver};
            var receiveSecundary = new Receiver(amountSecundary) { email = "*****@*****.**" };

            // A receiver's email address
            listReceiver.Add(receivePrimary);
            listReceiver.Add(receiveSecundary);
            var listOfReceivers = new ReceiverList(listReceiver);

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