Ejemplo 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();
        }
Ejemplo n.º 2
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);
        }
		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;
		}
Ejemplo n.º 4
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);
        }
        /// <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);            
        }
		public override ProcessPaymentResult ProcessPayment(ProcessPaymentEvaluationContext context)
		{
			var retVal = new ProcessPaymentResult();

			if (context.Store == null)
				throw new NullReferenceException("no store with this id");

            if (!(!string.IsNullOrEmpty(context.Store.SecureUrl) || !string.IsNullOrEmpty(context.Store.Url)))
                throw new NullReferenceException("store must specify Url or SecureUrl property");

			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 payResponse = service.Pay(request);
            var setPaymentOptionsResponse = service.SetPaymentOptions(new SetPaymentOptionsRequest { payKey = payResponse.payKey, senderOptions = new SenderOptions { referrerCode = "Virto_SP" } });
            var executePaymentResponse = service.ExecutePayment(new ExecutePaymentRequest { payKey = payResponse.payKey, actionType = "PAY", requestEnvelope = new RequestEnvelope { errorLanguage = "en_US" } });

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

			return retVal;
		}
Ejemplo n.º 7
0
    // # Pay API Operations
    // Use the Pay API operations to transfer funds from a sender’s PayPal account to one or more receivers’ PayPal accounts. You can use the Pay API operation to make simple payments, chained payments, or parallel payments; these payments can be explicitly approved, preapproved, or implicitly approved. 
    public PayResponse PayAPIOperations(PayRequest reqPay)
    {
        // Create the PayResponse object
        PayResponse responsePay = new PayResponse();

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

            // # API call
            // Invoke the Pay method in service wrapper object
            responsePay = service.Pay(reqPay);

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

                // # Success values
                if (responsePay.responseEnvelope.ack.ToString().Trim().ToUpper().Equals("SUCCESS"))
                {
                    // 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.
                    logger.Info("Pay Key : " + responsePay.payKey + "\n");
                    Console.WriteLine("Pay Key : " + responsePay.payKey + "\n");

                    // Once you get success response, user has to redirect to PayPal
                    // for the payment. Construct redirectURL as follows,
                    // `redirectURL=https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_ap-payment&paykey="
                    // + responsePay.payKey;`
                }
                // # Error Values 
                else
                {
                    List<ErrorData> errorMessages = responsePay.error;
                    foreach (ErrorData error in errorMessages)
                    {
                        logger.Debug(error.message);
                        Console.WriteLine(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 responsePay;
    }
        /// <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);
        }
Ejemplo n.º 10
0
        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());
            }
        }
Ejemplo n.º 11
0
        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;
        }
Ejemplo n.º 12
0
        // # Pay API Operations
        // Use the Pay API operations to transfer funds from a sender’s PayPal account to one or more receivers’ PayPal accounts. You can use the Pay API operation to make simple payments, chained payments, or parallel payments; these payments can be explicitly approved, preapproved, or implicitly approved.
        private PayResponse PayApiOperations(PayRequest reqPay)
        {
            // Create the PayResponse object
            var responsePay = new PayResponse();

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

                // # API call
                // Invoke the Pay method in service wrapper object
                responsePay = service.Pay(reqPay);

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

                    // # Success values
                    if (responsePay.responseEnvelope!= null && responsePay.responseEnvelope.ack.ToString().Trim().ToUpper().Equals("SUCCESS"))
                    {
                        // 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.
                        Console.WriteLine("Pay Key : " + responsePay.payKey + "\n");
                    }
                    // # Error Values
                    else
                    {
                        List<ErrorData> errorMessages = responsePay.error;
                        foreach (ErrorData error in errorMessages)
                        {
                            Console.WriteLine(error.message + "\n");
                        }
                    }
                }
            }
            // # Exception log
            catch (Exception ex)
            {
                // Log the exception message
                Console.WriteLine("Error Message : " + ex.Message);
            }
            return responsePay;
        }
        //TODO : tested already but we dont see the place to use this code in python code now
        // Document: https://developer.paypal.com/docs/classic/api/adaptive-payments/Pay_API_Operation/
        // Example: https://devtools-paypal.com/guide/ap_parallel_payment/dotnet?interactive=ON&env=sandbox
        public PayResponse PaypalPayment(decimal amount, string receiverEmail,
            bool autoMode, string orderID)
        {
            var api = GoPlayApi.Instance;
            var headers = PaypalHelper.GetHeader();
            ReceiverList receiverList = new ReceiverList
            {
                receiver = new List<Receiver> {
                    new Receiver(amount)
                    {
                        email = receiverEmail
                    }
                }
            };

            RequestEnvelope requestEnvelope = new RequestEnvelope("en_US")
            {
                detailLevel = DetailLevelCode.RETURNALL
            };

            PayRequest payRequest = new PayRequest
            {
                requestEnvelope = requestEnvelope,
                reverseAllParallelPaymentsOnError = true,
                returnUrl = ConfigurationManager.AppSettings["PAYPAL_PAYMENT_RETURN_URL"] + orderID,
                cancelUrl = ConfigurationManager.AppSettings["PAYPAL_PAYMENT_CANCEL_URL"] + orderID,
                currencyCode = ConfigurationManager.AppSettings["DEFAULT_PAYPAL_CURRENCY"],
                feesPayer = "EACHRECEIVER",
                receiverList = receiverList
            };

            //TODO: When the payment is complete, PayPal sends an IPN message to the URL specified in the ipnNotificationUrl field of the Pay request. 
            //May be we dont need do it, but should consider
            //payRequest.ipnNotificationUrl = "http://replaceIpnUrl.com";

            if (autoMode)
            {
                var pp = api.GetPaypalPreApproval(true).Data;
                if (pp != null)
                    payRequest.preapprovalKey = pp.preapproval_key;
                payRequest.actionType = "PAY";
            }
            else
            {
                payRequest.senderEmail = ConfigurationManager.AppSettings["PAYPAL_SENDER_EMAIL"];
                payRequest.actionType = "CREATE";
                payRequest.payKeyDuration = ConfigurationManager.AppSettings["PAYPAL_PAY_KEY_DURATION"];
            }

            AdaptivePaymentsService adaptivePaymentsService = new AdaptivePaymentsService(headers);
            PayResponse payResponse = adaptivePaymentsService.Pay(payRequest);
            return payResponse;
        }