public string Pay(string senderEmail, string receiverEmail, decimal amount, string returnUrl, string cancelUrl)
        {
            var service = new AdaptivePaymentsService();
            var request = new PayRequest(new RequestEnvelope("en_US"),
                                         "PAY",
                                         cancelUrl,
                                         "USD",
                                         new ReceiverList(new List <Receiver>()
            {
                new Receiver()
                {
                    email = receiverEmail, amount = amount
                }
            }), returnUrl)
            {
                senderEmail = senderEmail
            };

            var    response       = service.Pay(request);
            var    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;
            }

            return(redirectUrl);
        }
Example #2
0
        /// <summary>
        /// Handle ConfirmPreapproval API call
        /// </summary>
        /// <param name="context"></param>
        private void ConfirmPreapproval(HttpContext context)
        {
            NameValueCollection parameters = context.Request.Params;
            ConfirmPreapprovalRequest req = new ConfirmPreapprovalRequest(new RequestEnvelope("en_US"),
                parameters["preapprovalKey"]);
            // Set optional parameters
            if (parameters["pin"] != "")
                req.pin = parameters["pin"];
            if (parameters["fundingSourceId"] != "")
                req.fundingSourceId = parameters["fundingSourceId"];

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

            // Display response values. 
            Dictionary<string, string> keyResponseParams = new Dictionary<string, string>();
            string redirectUrl = null;
            if (!(resp.responseEnvelope.ack == AckCode.FAILURE) &&
                !(resp.responseEnvelope.ack == AckCode.FAILUREWITHWARNING))
            {
                //nothing to add
            }
            displayResponse(context, "ConfirmPreapproval", keyResponseParams, service.getLastRequest(), service.getLastResponse(),
                resp.error, redirectUrl);
        }
        public void Valid_payment_successfull_validation()
        {
            //arrange
            var service = new AdaptivePaymentsService(GetConfigiration());
            var request = CreatePayRequest();

            //act
            var payResponse = service.Pay(request);
            var setPaymentOptionsResponse = service.SetPaymentOptions(new SetPaymentOptionsRequest {
                payKey = payResponse.payKey, senderOptions = new SenderOptions {
                    referrerCode = "Virto_SP"
                }, requestEnvelope = new RequestEnvelope {
                    errorLanguage = "en_US"
                }
            });

            // var executePaymentResponse = service.ExecutePayment(new ExecutePaymentRequest { payKey = payResponse.payKey, actionType = "PAY", requestEnvelope = new RequestEnvelope { errorLanguage = "en_US" } });

            //assert
            Assert.Equal("", GetErrors(payResponse.error));
            Assert.Equal("", GetErrors(setPaymentOptionsResponse.error));
            // Assert.Equal("", GetErrors(executePaymentResponse.error));

            output.WriteLine(payResponse.paymentExecStatus + ". PayKey: " + payResponse.payKey);
            output.WriteLine("Activate " + string.Format(SandboxPaypalBaseUrlFormat, payResponse.payKey));
        }
Example #4
0
        /// <summary>
        /// Handle ExecutePayment API call
        /// </summary>
        /// <param name="context"></param>
        private void ExecutePayment(HttpContext context)
        {
            NameValueCollection parameters = context.Request.Params;
            ExecutePaymentRequest req = new ExecutePaymentRequest(
                    new RequestEnvelope("en_US"), parameters["payKey"]);

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

            // Display response values. 
            Dictionary<string, string> keyResponseParams = new Dictionary<string, string>();
            string redirectUrl = null;
            if (!(resp.responseEnvelope.ack == AckCode.FAILURE) &&
                !(resp.responseEnvelope.ack == AckCode.FAILUREWITHWARNING))
            {
                keyResponseParams.Add("Payment exeucution status", resp.paymentExecStatus);
            }
            displayResponse(context, "ExecutePayment", keyResponseParams, service.getLastRequest(), service.getLastResponse(),
                resp.error, redirectUrl);
        }
        /// <summary>
        /// Gets execution status of a payment by PayKey
        /// </summary>
        /// <param name="payKey"></param>
        /// <returns></returns>
        public PaymentExecStatusSEnum GetPaymentExecutionStatus(string payKey)
        {
            Check.Require(string.IsNullOrEmpty(payKey) == false, "PayPalService.GetPaymentStatus: PayKey is required.");

            PaymentDetailsRequest request = new PaymentDetailsRequest(new RequestEnvelope("en_US"));

            request.payKey = payKey;

            Dictionary <string, string> configurationMap = FWUtils.ConfigUtils.GetAppSettings().Paypal.GetAcctAndConfig();
            AdaptivePaymentsService     service          = new AdaptivePaymentsService(configurationMap);
            PaymentDetailsResponse      response         = service.PaymentDetails(request);

            string ack = response.responseEnvelope.ack.ToString().Trim().ToUpper();

            // if no error happened
            if (!ack.Equals(AckCode.FAILURE.ToString()) &&
                !ack.Equals(AckCode.FAILUREWITHWARNING.ToString()))
            {
                PaymentExecStatusSEnum execStatus = new PaymentExecStatusSEnum(response.status);
                return(execStatus);
            }
            else
            {
                throw new UserException(GetPayPalErrorString(response.error));
            }
        }
Example #6
0
        public ActionResult Index(int?id)
        {
            //decimal price = 50;
            //Bids bid = db.Bids.Find(id);
            ReceiverList receiverList = new ReceiverList();

            receiverList.receiver = new List <Receiver>();
            Receiver receiver = new Receiver(50);

            //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   = "*****@*****.**";
            receiver.primary = true;
            receiverList.receiver.Add(receiver);
            Receiver receiver2 = new Receiver(10);

            //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());
            receiver2.email   = "*****@*****.**";
            receiver2.primary = false;
            receiverList.receiver.Add(receiver2);

            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://de3b6191.ngrok.io";

            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);
            SimpleListenerExample("localhost: 80");
            return(View());
        }
Example #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);
    }
Example #8
0
        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 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);
        }
Example #9
0
        /// <summary>
        /// Handle GetUserLimits API call
        /// </summary>
        /// <param name="context"></param>
        private void GetUserLimits(HttpContext context)
        {
            NameValueCollection parameters = context.Request.Params;

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

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

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

            // Display response values. 
            Dictionary<string, string> keyResponseParams = new Dictionary<string, string>();
            string redirectUrl = null;
            if (!(resp.responseEnvelope.ack == AckCode.FAILURE) &&
                !(resp.responseEnvelope.ack == AckCode.FAILUREWITHWARNING))
            {
                int idx = 1;
                foreach (UserLimit userLimit in resp.userLimit)
                {
                    keyResponseParams.Add("Limit amount " + idx,
                        userLimit.limitAmount.amount + userLimit.limitAmount.code);
                    keyResponseParams.Add("Limit type " + idx, userLimit.limitType);
                    idx++;
                }
            }
            displayResponse(context, "GetAvailableShippingAddresses", keyResponseParams, service.getLastRequest(), service.getLastResponse(),
                resp.error, redirectUrl);
        }
Example #10
0
        private bool ChargePayPalSuccess(Subscription sub, ManBoxEntities ent, string thankYouUrl, string cancelUrl)
        {
            var payPalAccount = ConfigurationManager.AppSettings[AppConstants.AppSettingsKeys.PayPalAccount] as string;
            var paymentInfo   = GetPaymentInfo(sub, ent);

            var receiverList = new ReceiverList();

            receiverList.receiver = new List <Receiver>();
            receiverList.receiver.Add(new Receiver(paymentInfo.Total)
            {
                email = payPalAccount
            });

            var         service  = new AdaptivePaymentsService();
            PayResponse response = service.Pay(new PayRequest(
                                                   new RequestEnvelope("en_US"),
                                                   "PAY",
                                                   cancelUrl,
                                                   "EUR",
                                                   receiverList,
                                                   thankYouUrl)
            {
                senderEmail    = sub.PayPalSenderEmail,
                preapprovalKey = sub.PayPalPreapprovalKey
            });

            if (response == null)
            {
                logger.Log(LogType.Fatal, "No Response was received from PayPal Payrequest service");
            }

            logger.Log(LogType.Info, string.Format("paykey is {0} . exec status is {1}", response.payKey ?? "", response.paymentExecStatus ?? ""));

            // error handling
            if (response.error != null && response.error.FirstOrDefault() != null)
            {
                logger.Log(LogType.Error, string.Format("error {0}", response.error.FirstOrDefault().message));
            }

            // error handling
            if (response.payErrorList != null && response.payErrorList.payError.FirstOrDefault() != null)
            {
                logger.Log(LogType.Error, string.Format("payerror {0}", response.payErrorList.payError.FirstOrDefault().error.message));
            }

            //payment exec status must be : COMPLETED
            if (!string.IsNullOrEmpty(response.paymentExecStatus) &&
                response.paymentExecStatus.ToLower() == PayPalConstants.PaymentExecStatus.Completed.ToLower())
            {
                return(true);
            }

            return(false);
        }
        public override ProcessPaymentResult ProcessPayment(ProcessPaymentEvaluationContext context)
        {
            var retVal = new ProcessPaymentResult();

            if (context.Store == null)
            {
                throw new NullReferenceException("Store is required!");
            }

            if (string.IsNullOrEmpty(context.Store.SecureUrl) && string.IsNullOrEmpty(context.Store.Url))
            {
                throw new NullReferenceException("Store must have Url or SecureUrl property assigned!");
            }

            PayResponse payResponse = null;
            string      errorText;

            try
            {
                var service = new AdaptivePaymentsService(GetConfiguration());
                var request = CreatePayRequest(context);

                // submit payment data for redirection to paypal website
                payResponse = service.Pay(request);

                errorText = GetErrors(payResponse.error);

                //var setPaymentOptionsResponse = service.SetPaymentOptions(new SetPaymentOptionsRequest { payKey = payResponse.payKey, senderOptions = new SenderOptions { referrerCode = "Virto_SP" }, requestEnvelope = new RequestEnvelope { errorLanguage = "en_US" } });
                //errorText += GetErrors(setPaymentOptionsResponse.error);

                //var executePaymentResponse = service.ExecutePayment(new ExecutePaymentRequest { payKey = payResponse.payKey, actionType = "PAY", requestEnvelope = new RequestEnvelope { errorLanguage = "en_US" } });
                //errorText += GetErrors(executePaymentResponse.error);
            }
            catch (Exception ex)
            {
                errorText = ex.Message;
            }

            if (string.IsNullOrEmpty(errorText))
            {
                retVal.OuterId          = payResponse.payKey;
                retVal.IsSuccess        = true;
                retVal.RedirectUrl      = string.Format(PaypalBaseUrlFormat, retVal.OuterId);
                retVal.NewPaymentStatus = context.Payment.PaymentStatus = PaymentStatus.Pending;
            }
            else
            {
                retVal.Error            = errorText;
                retVal.NewPaymentStatus = context.Payment.PaymentStatus = PaymentStatus.Voided;
                // context.Payment.VoidedDate = DateTime.UtcNow;
            }

            return(retVal);
        }
        public override PostProcessPaymentResult PostProcessPayment(PostProcessPaymentEvaluationContext context)
        {
            var retVal = new PostProcessPaymentResult();

            var service = new AdaptivePaymentsService(GetConfiguration());

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

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

                context.Payment.VoidedDate = DateTime.UtcNow;
                retVal.NewPaymentStatus    = context.Payment.PaymentStatus = PaymentStatus.Voided;
            }
            else
            {
                retVal.NewPaymentStatus = context.Payment.PaymentStatus = PaymentStatus.Pending;
            }

            return(retVal);
        }
Example #13
0
        /// <summary>
        /// Handle GetPaymentOptions API call
        /// </summary>
        /// <param name="context"></param>
        private void GetPaymentOptions(HttpContext context)
        {
            NameValueCollection parameters = context.Request.Params;
            GetPaymentOptionsRequest req = new GetPaymentOptionsRequest(
                    new RequestEnvelope("en_US"), parameters["payKey"]);

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

            // Display response values. 
            Dictionary<string, string> keyResponseParams = new Dictionary<string, string>();
            string redirectUrl = null;
            if (!(resp.responseEnvelope.ack == AckCode.FAILURE) &&
                !(resp.responseEnvelope.ack == AckCode.FAILUREWITHWARNING))
            {
                int idx = 1;
                foreach(ReceiverOptions option in resp.receiverOptions)
                {
                    keyResponseParams.Add("Receiver option " + idx, option.description);
                    keyResponseParams.Add("Receiver email " + idx, option.receiver.email);
                    idx++;
                }
                if(resp.displayOptions != null) 
                {
                    keyResponseParams.Add("Business name", resp.displayOptions.businessName);
                    keyResponseParams.Add("Header image", resp.displayOptions.headerImageUrl);
                    keyResponseParams.Add("Email header image", resp.displayOptions.emailHeaderImageUrl);
                }
                keyResponseParams.Add("Shipping address Id", resp.shippingAddressId);
            }
            displayResponse(context, "GetPaymentOptions", keyResponseParams, service.getLastRequest(), service.getLastResponse(),
                resp.error, redirectUrl);
        }
Example #14
0
        /// <summary>
        /// Handle GetAvailableShippingAddresses API call
        /// </summary>
        /// <param name="context"></param>
        private void GetAvailableShippingAddresses(HttpContext context)
        {
            NameValueCollection parameters = context.Request.Params;
            GetAvailableShippingAddressesRequest req = new GetAvailableShippingAddressesRequest(
                    new RequestEnvelope("en_US"), parameters["key"]);

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

            // Display response values. 
            Dictionary<string, string> keyResponseParams = new Dictionary<string, string>();
            string redirectUrl = null;
            if (!(resp.responseEnvelope.ack == AckCode.FAILURE) &&
                !(resp.responseEnvelope.ack == AckCode.FAILUREWITHWARNING))
            {
                int idx = 1;
                foreach(Address addr in resp.availableAddress) 
                {
                    keyResponseParams.Add("Address name " + idx, addr.addresseeName);
                    keyResponseParams.Add("Address Id " + idx, addr.addressId);
                    if (addr.baseAddress != null)
                    {
                        keyResponseParams.Add("Address line " + idx, addr.baseAddress.line1);
                        keyResponseParams.Add("City " + idx, addr.baseAddress.city);
                        keyResponseParams.Add("State " + idx, addr.baseAddress.state);
                    }
                }
            }
            displayResponse(context, "GetAvailableShippingAddresses", keyResponseParams, service.getLastRequest(), service.getLastResponse(),
                resp.error, redirectUrl);
        }
Example #15
0
        /// <summary>
        /// Handle PaymentDetails API call
        /// </summary>
        /// <param name="context"></param>
        private void PaymentDetails(HttpContext context)
        {
            NameValueCollection parameters = context.Request.Params;
            PaymentDetailsRequest req = new PaymentDetailsRequest(new RequestEnvelope("en_US")); 
            // set optional parameters
            if (parameters["payKey"] != "")
                req.payKey = parameters["payKey"];
            if (parameters["transactionId"] != "")
                req.transactionId = parameters["transactionId"];
            if (parameters["trackingId"] != "")
                req.trackingId = parameters["trackingId"];

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

            // Display response values. 
            Dictionary<string, string> keyResponseParams = new Dictionary<string, string>();
            string redirectUrl = null;
            if (!(resp.responseEnvelope.ack == AckCode.FAILURE) &&
                !(resp.responseEnvelope.ack == AckCode.FAILUREWITHWARNING))
            {                
                keyResponseParams.Add("Pay key", resp.payKey);
                keyResponseParams.Add("Payment execution status", resp.status);
                keyResponseParams.Add("Sender email", resp.senderEmail);
            }
            displayResponse(context, "PaymentDetails", keyResponseParams, service.getLastRequest(), service.getLastResponse(),
                resp.error, redirectUrl);
        }
Example #16
0
        /// <summary>
        /// Handle PreapprovalDetails API call
        /// </summary>
        /// <param name="context"></param>
        private void PreapprovalDetails(HttpContext context)
        {
            NameValueCollection parameters = context.Request.Params;
            PreapprovalDetailsRequest req = new PreapprovalDetailsRequest(new RequestEnvelope("en_US"), 
                parameters["preapprovalKey"]);
            // set optional parameters
            if (parameters["getBillingAddress"] != "")
                req.getBillingAddress = Boolean.Parse(parameters["getBillingAddress"]);

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

            // Display response values. 
            Dictionary<string, string> keyResponseParams = new Dictionary<string, string>();
            string redirectUrl = null;
            if (!(resp.responseEnvelope.ack == AckCode.FAILURE) &&
                !(resp.responseEnvelope.ack == AckCode.FAILUREWITHWARNING))
            {
                keyResponseParams.Add("Status", resp.status);
                keyResponseParams.Add("Starting date", resp.startingDate);
                keyResponseParams.Add("Ending date", resp.endingDate);
                keyResponseParams.Add("Sender email", resp.senderEmail);
                keyResponseParams.Add("Currency code", resp.currencyCode);
                keyResponseParams.Add("Maximum amount (across all payments)", resp.maxTotalAmountOfAllPayments.ToString());                
            }
            displayResponse(context, "PreapprovalDetails", keyResponseParams, service.getLastRequest(), service.getLastResponse(),
                resp.error, redirectUrl);
        }
Example #17
0
        /// <summary>
        /// Creates paypal payment and its key
        /// It uses Pay action as of now to make do the payment
        /// </summary>
        /// <returns></returns>
        private PayResponse CallPaypalPay(PayRequest request)
        {
            Dictionary <string, string> configurationMap = FWUtils.ConfigUtils.GetAppSettings().Paypal.GetAcctAndConfig();
            AdaptivePaymentsService     service          = new AdaptivePaymentsService(configurationMap);

            // executing adaptive payment pay service
            PayResponse response = service.Pay(request);

            string ack = response.responseEnvelope.ack.ToString().Trim().ToUpper();

            // if no error happened
            if (!ack.Equals(AckCode.FAILURE.ToString()) &&
                !ack.Equals(AckCode.FAILUREWITHWARNING.ToString()))
            {
                //PaymentExecStatusSEnum execStatus = new PaymentExecStatusSEnum(response.paymentExecStatus);

                return(response);
            }
            else
            {
                throw new UserException(GetPayPalErrorString(response.error));
            }
        }
Example #18
0
        /// <summary>
        /// Handle GetFundingPlans API call
        /// </summary>
        /// <param name="context"></param>
        private void GetFundingPlans(HttpContext context)
        {
            NameValueCollection parameters = context.Request.Params;
            GetFundingPlansRequest req = new GetFundingPlansRequest(new RequestEnvelope("en_US"),
                parameters["payKey"]);

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

            // Display response values. 
            Dictionary<string, string> keyResponseParams = new Dictionary<string, string>();
            string redirectUrl = null;
            if (!(resp.responseEnvelope.ack == AckCode.FAILURE) &&
                !(resp.responseEnvelope.ack == AckCode.FAILUREWITHWARNING))
            {
                int idx = 1;
                foreach (FundingPlan plan in resp.fundingPlan) {
                    keyResponseParams.Add("Funding plan Id " + idx, plan.fundingPlanId);
                    keyResponseParams.Add("Funding plan amount " + idx, 
                        plan.fundingAmount.amount + plan.fundingAmount.code );
                    idx++;
                }
            }
            displayResponse(context, "GetFundingPlans", keyResponseParams, service.getLastRequest(), service.getLastResponse(),
                resp.error, redirectUrl);
        }
Example #19
0
        public string GetPaymentUrl()
        {
            var paymentReceiver = new Receiver
            {
                email  = PaymentReceiverEmail,
                amount = transaction.GetTotal()
            };

            var receivers = new ReceiverList(new List <Receiver>()
            {
                paymentReceiver
            });

            var payRequest = new PayRequest
            {
                actionType      = "PAY",
                receiverList    = receivers,
                currencyCode    = currency.code,
                requestEnvelope = new RequestEnvelope
                {
                    errorLanguage
                        =
                            "en_US"
                },
                returnUrl  = returnUrl,
                trackingId = uniqueid
            };

            payRequest.cancelUrl = payRequest.returnUrl;

            var configurationMap = Configuration.GetAcctAndConfig();

            var service = new AdaptivePaymentsService(configurationMap);

            var resp = service.Pay(payRequest);

            if (resp.responseEnvelope.ack == AckCode.FAILURE ||
                resp.responseEnvelope.ack == AckCode.FAILUREWITHWARNING)
            {
                // TODO: serialize this properly
                throw new Exception(resp.error.First().message);
            }

            if (resp.paymentExecStatus != "CREATED" && resp.paymentExecStatus != "COMPLETED")
            {
                // create the payment
                string errorString = "";
                foreach (var error in resp.payErrorList.payError)
                {
                    errorString += error.error.message;
                }
                throw new Exception(errorString);
            }

            string paymentStatus = PaymentStatus.Charging.ToString();

            if (resp.paymentExecStatus == "COMPLETED")
            {
                paymentStatus = PaymentStatus.Accepted.ToString();
            }

            var pay = new DBML.payment
            {
                created     = DateTime.UtcNow,
                paidAmount  = transaction.GetTotal(),
                method      = PaymentMethodType.Paypal.ToString(),
                orderid     = transaction.GetID(),
                status      = paymentStatus,
                reference   = uniqueid,
                redirectUrl = PaymentConstants.PaypalRedirectUrl + resp.payKey
            };

            transaction.AddPayment(pay, true);

            // update invoice status
            repository.Save();

            return(pay.redirectUrl);
        }
Example #20
0
    // # Refund API Operation
    // Use the Refund API operation to refund all or part of a payment. You can specify the amount of the refund and identify the accounts to receive the refund by the payment key or tracking ID, and optionally, by transaction ID or the receivers of the original payment.
    public RefundResponse RefundAPIOperation()
    {
        // Create the RefundResponse object
        RefundResponse responseRefund = new RefundResponse();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                // # Success values
                if (responsePreapprovalDetails.responseEnvelope.ack.ToString().Trim().ToUpper().Equals("SUCCESS"))
                {
                    // First date for which the preapproval is valid.
                    logger.Info("Starting Date : " + responsePreapprovalDetails.startingDate + "\n");
                    Console.WriteLine("Starting Date : " + responsePreapprovalDetails.startingDate + "\n");
                }
                // # Error Values
                else
                {
                    List <ErrorData> errorMessages = responsePreapprovalDetails.error;
                    foreach (ErrorData error in errorMessages)
                    {
                        logger.Debug("API Error Message : " + error.message);
                        Console.WriteLine("API Error Message : " + error.message + "\n");
                    }
                }
            }
        }
        // # Exception log
        catch (System.Exception ex)
        {
            // Log the exception message
            logger.Debug("Error Message : " + ex.Message);
            Console.WriteLine("Error Message : " + ex.Message);
        }
        return(responsePreapprovalDetails);
    }
Example #22
0
        /// <summary>
        /// Handle ConvertCurrency API call
        /// </summary>
        /// <param name="context"></param>
        private void ConvertCurrency(HttpContext context)
        {
            NameValueCollection parameters = context.Request.Params;           
            string[] fromCurrencyCodes = context.Request.Form.GetValues("currencyCode");
            string[] fromCurrencyAmounts = context.Request.Form.GetValues("currencyAmount");
            string[] toCurrencyCodes = context.Request.Form.GetValues("toCurrencyCode");

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

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

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


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

            // Display response values. 
            Dictionary<string, string> keyResponseParams = new Dictionary<string, string>();
            string redirectUrl = null;
            if (!(resp.responseEnvelope.ack == AckCode.FAILURE) &&
                !(resp.responseEnvelope.ack == AckCode.FAILUREWITHWARNING))
            {
                if (resp.estimatedAmountTable != null
                    && resp.estimatedAmountTable.currencyConversionList != null)
                {
                    int idx = 1;
                    foreach (CurrencyConversionList list in resp.estimatedAmountTable.currencyConversionList)
                    {
                        keyResponseParams.Add("Base amount " + idx,
                            list.baseAmount.amount + " " + list.baseAmount.code);
                        idx++;
                    }
                }
            }
            displayResponse(context, "ConvertCurrency", keyResponseParams, service.getLastRequest(), service.getLastResponse(),
                resp.error, redirectUrl);
        }
        public ActionResult Payment(int?id)
        {
            string identity = System.Web.HttpContext.Current.User.Identity.GetUserId();

            if (identity == null)
            {
                return(RedirectToAction("Unauthorized_Access", "Home"));
            }
            var    completedList  = db.CompletedBids.ToList();
            string HomeOwnerEmail = "";
            string payeeEmail     = "";
            var    person         = db.Homeowners.Where(x => x.UserId == identity).SingleOrDefault();


            foreach (var user in db.Users)
            {
                if (user.Id == identity)
                {
                    payeeEmail = user.Email;
                }
            }

            foreach (var i in completedList)
            {
                if (id == i.ID)
                {
                    HomeOwnerEmail = i.HomeEmail;
                }
            }


            if (this.User.IsInRole("Admin") || HomeOwnerEmail == payeeEmail)
            {
                if (id == null)
                {
                    return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
                }
                CompletedBids completedBids = db.CompletedBids.Find(id);
                if (completedBids == null)
                {
                    return(HttpNotFound());
                }
                ReceiverList receiverList = new ReceiverList();
                receiverList.receiver = new List <Receiver>();
                Receiver receiver = new Receiver(completedBids.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   = "*****@*****.**";
                receiver.primary = true;
                receiverList.receiver.Add(receiver);
                Receiver receiver2 = new Receiver(completedBids.ContractorDue);
                //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());
                receiver2.email   = completedBids.ConEmail;
                receiver2.primary = false;
                receiverList.receiver.Add(receiver2);
                RequestEnvelope requestEnvelope = new RequestEnvelope("en_US");
                string          actionType      = "PAY";
                string          successUrl      = "http://" + System.Web.HttpContext.Current.Request.Url.Authority + "/CompletedBids/SuccessView/{0}";
                string          failureUrl      = "http://" + System.Web.HttpContext.Current.Request.Url.Authority + "/CompletedBids/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://cf719b5f.ngrok.io";
                string memo = completedBids.Description + " Invoice = " + completedBids.Invoice;
                payRequest.memo = memo;
                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(completedBids));
            }
            else
            {
                return(RedirectToAction("Unauthorized_Access", "Home"));
            }
        }
Example #24
0
    // # Preapproval API Operation
    // Use the Preapproval API operation to set up an agreement between yourself and a sender for making payments on the sender’s behalf. You set up a preapprovals for a specific maximum amount over a specific period of time and, optionally, by any of the following constraints: the number of payments, a maximum per-payment amount, a specific day of the week or the month, and whether or not a PIN is required for each payment request.
    public PreapprovalResponse PreapprovalAPIOperation()
    {
        // Create the PreapprovalResponse object
        PreapprovalResponse responsePreapproval = new PreapprovalResponse();

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

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

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

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

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

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

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

                    // Once you get success response, user has to redirect to PayPal
                    // to preapprove the payment. Construct redirectURL as follows,
                    // `redirectURL=https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_ap-preapproval&preapprovalkey="
                    // + responsePreapproval.preapprovalKey;`
                }
                // # Error Values
                else
                {
                    List <ErrorData> errorMessages = responsePreapproval.error;
                    foreach (ErrorData error in errorMessages)
                    {
                        logger.Debug("API Error Message : " + error.message);
                        Console.WriteLine("API Error Message : " + error.message + "\n");
                    }
                }
            }
        }
        // # Exception log
        catch (System.Exception ex)
        {
            // Log the exception message
            logger.Debug("Error Message : " + ex.Message);
            Console.WriteLine("Error Message : " + ex.Message);
        }
        return(responsePreapproval);
    }
Example #25
0
        /// <summary>
        /// Handle Preapproval API
        /// </summary>
        /// <param name="context"></param>
        private void Preapproval(HttpContext context)
        {
            NameValueCollection parameters = context.Request.Params;
            PreapprovalRequest req = new PreapprovalRequest(new RequestEnvelope("en_US"), parameters["cancelUrl"], 
                    parameters["currencyCode"], parameters["returnUrl"], parameters["startingDate"]);
            // set optional parameters
            if(parameters["dateOfMonth"] != "") 
            {
	            req.dateOfMonth = Int32.Parse(parameters["dateOfMonth"]);
            }
            if(parameters["dayOfWeek"] != "" && parameters["dayOfWeek"] != "") 
            {
                req.dayOfWeek = (PayPal.AdaptivePayments.Model.DayOfWeek)
                        Enum.Parse(typeof(PayPal.AdaptivePayments.Model.DayOfWeek), parameters["dayOfWeek"]);
            }
            if(parameters["dateOfMonth"] != "") 
            {
	            req.dateOfMonth = Int32.Parse(parameters["dateOfMonth"]);
            }
            if(parameters["endingDate"] != "") 
            {
	            req.endingDate = parameters["endingDate"];
            }
            if(parameters["maxAmountPerPayment"] != "") 
            {
	            req.maxAmountPerPayment = Decimal.Parse(parameters["maxAmountPerPayment"]);
            }
            if(parameters["maxNumberOfPayments"] != "" ) 
            {
	            req.maxNumberOfPayments = Int32.Parse(parameters["maxNumberOfPayments"]);
            }
            if(parameters["maxNumberOfPaymentsPerPeriod"] != "") 
            {
	            req.maxNumberOfPaymentsPerPeriod = Int32.Parse(parameters["maxNumberOfPaymentsPerPeriod"]);
            }
            if(parameters["maxTotalAmountOfAllPayments"] != "") 
            {
	            req.maxTotalAmountOfAllPayments = Decimal.Parse(parameters["maxTotalAmountOfAllPayments"]);
            }
            if(parameters["paymentPeriod"] != "" && parameters["paymentPeriod"] != "") 
            {
	            req.paymentPeriod = parameters["paymentPeriod"];
            }
            if(parameters["memo"] != "") 
            {
	            req.memo = parameters["memo"];
            }
            if(parameters["ipnNotificationUrl"] != "") 
            {
	            req.ipnNotificationUrl = parameters["ipnNotificationUrl"];
            }
            if(parameters["senderEmail"] != "") 
            {
	            req.senderEmail = parameters["senderEmail"];
            }
            if(parameters["pinType"] != "" && parameters["pinType"] != "") 
            {
	            req.pinType = parameters["pinType"];
            }
            if(parameters["feesPayer"] != "") 
            {
	            req.feesPayer = parameters["feesPayer"];
            }
            if (parameters["displayMaxTotalAmount"] != "")
            {
                req.displayMaxTotalAmount = Boolean.Parse(parameters["displayMaxTotalAmount"]);
            }

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

            // Display response values. 
            Dictionary<string, string> keyResponseParams = new Dictionary<string, string>();
            string redirectUrl = null;
            if (!(resp.responseEnvelope.ack == AckCode.FAILURE) &&
                !(resp.responseEnvelope.ack == AckCode.FAILUREWITHWARNING))
            {
                keyResponseParams.Add("Preapproval key", resp.preapprovalKey);
            }
            displayResponse(context, "Preapproval", keyResponseParams, service.getLastRequest(), service.getLastResponse(),
                resp.error, redirectUrl);
        }
Example #26
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, bool isPreapproved)
        {
            // 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();


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

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

                        string url = String.Format("https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_ap-payment&paykey={0}", responsePay.payKey);
                        if (isPreapproved)
                        {
                            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

                            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                            //if (response.StatusCode.ToString() == "OK")
                            //{
                            //    Console.WriteLine("PAY MENT SUCCESS");
                            //}
                        }
                        else
                        if (HttpContext.Current != null)
                        {
                            HttpContext.Current.Response.Redirect(url);
                        }
                    }
                    // # Error Values
                    else
                    {
                        List <ErrorData> errorMessages = responsePay.error;
                        foreach (ErrorData error in errorMessages)
                        {
                        }
                    }
                }
            }
            // # Exception log
            catch (System.Exception ex)
            {
                string temp = ex.StackTrace.ToString();
            }
            return(responsePay);
        }
Example #27
0
        // # Preapproval API Operation
        public PreapprovalResponse PreapprovalAPIOperation(decimal rate, string userId, DateTime subscriptionDate)
        {
            // Create the PreapprovalResponse object
            PreapprovalResponse responsePreapproval = new PreapprovalResponse();

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

                PreapprovalRequest requestPreapproval = new PreapprovalRequest();
                requestPreapproval.requestEnvelope              = envelopeRequest;
                requestPreapproval.returnUrl                    = System.Configuration.ConfigurationManager.AppSettings["RETURN_URL"] + "/DoctorInformation/PayPalSubscription/?pstatus=success&userId=" + userId;
                requestPreapproval.cancelUrl                    = System.Configuration.ConfigurationManager.AppSettings["CANCEL_URL"] + "/DoctorInformation/PayPalSubscription/?pstatus=cancel&userid=" + userId;
                requestPreapproval.currencyCode                 = "USD";
                requestPreapproval.startingDate                 = subscriptionDate.ToString("yyyy-MM-dd");
                requestPreapproval.endingDate                   = subscriptionDate.AddYears(1).ToString("yyyy-MM-dd");
                requestPreapproval.feesPayer                    = "EACHRECEIVER";
                requestPreapproval.maxAmountPerPayment          = rate;
                requestPreapproval.maxNumberOfPaymentsPerPeriod = 1;
                requestPreapproval.maxTotalAmountOfAllPayments  = (12 * rate);
                requestPreapproval.maxNumberOfPayments          = 12;
                //requestPreapproval.dateOfMonth = 27;
                requestPreapproval.pinType = "NOT_REQUIRED";
                //if(!string.IsNullOrEmpty(paypalId))
                //    requestPreapproval.senderEmail = paypalId;
                requestPreapproval.paymentPeriod = "DAILY";
                // IPN URL
                //
                // * PayPal Instant Payment Notification is a call back system that is initiated when a transaction is completed
                // * The transaction related IPN variables will be received on the call back URL specified in the request
                // * The IPN variables have to be sent back to the PayPal system for validation, upon validation PayPal will send a response string "VERIFIED" or "INVALID"
                // * PayPal would continuously resend IPN if a wrong IPN is sent
                requestPreapproval.ipnNotificationUrl = System.Configuration.ConfigurationManager.AppSettings["IPN_URL"] + "/DoctorInformation/PayPalIPN/";

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

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

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

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

                        // Once you get success response, user has to redirect to PayPal
                        // to preapprove the payment. Construct redirectURL as follows,
                        // `redirectURL=https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_ap-preapproval&preapprovalkey="
                        // + responsePreapproval.preapprovalKey;`

                        string url = String.Format("https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_ap-preapproval&preapprovalkey={0}", responsePreapproval.preapprovalKey);
                        if (HttpContext.Current != null)
                        {
                            HttpContext.Current.Response.Redirect(url);
                        }
                    }
                    // # Error Values
                    else
                    {
                        List <ErrorData> errorMessages = responsePreapproval.error;
                        foreach (ErrorData error in errorMessages)
                        {
                            //logger.Debug("API Error Message : " + error.message);
                            //Console.WriteLine("API Error Message : " + error.message + "\n");
                        }
                    }
                }
            }
            // # Exception log
            catch (System.Exception ex)
            {
                // Log the exception message
            }
            return(responsePreapproval);
        }
Example #28
0
        /// <summary>
        /// Handle SetPaymentOptions API call
        /// </summary>
        /// <param name="context"></param>
        private void SetPaymentOptions(HttpContext context)
        {
            NameValueCollection parameters = context.Request.Params;
            SetPaymentOptionsRequest req = new SetPaymentOptionsRequest(
                    new RequestEnvelope("en_US"), parameters["payKey"]);
            if (parameters["institutionId"] != "")
            {
                req.initiatingEntity = new InitiatingEntity();
                req.initiatingEntity.institutionCustomer = new InstitutionCustomer(
                    parameters["institutionId"], parameters["firstName"], 
                    parameters["lastName"], parameters["displayName"], 
                    parameters["institutionCustomerId"], parameters["countryCode"]);
                if (parameters["email"] != "")
                {
                    req.initiatingEntity.institutionCustomer.email = parameters["email"];
                }
            }
            if (parameters["emailHeaderImageUrl"] != "" || parameters["emailMarketingImageUrl"] != ""
                || parameters["headerImageUrl"] != "" || parameters["businessName"] != "")
            {
                req.displayOptions = new DisplayOptions();
                if (parameters["emailHeaderImageUrl"] != "" )
                    req.displayOptions.emailHeaderImageUrl = parameters["emailHeaderImageUrl"];
                if (parameters["emailMarketingImageUrl"] != "")
                    req.displayOptions.emailMarketingImageUrl = parameters["emailMarketingImageUrl"];
                if(parameters["headerImageUrl"] != "" )
                    req.displayOptions.headerImageUrl = parameters["headerImageUrl"];
                if(parameters["businessName"] != "")
                    req.displayOptions.businessName = parameters["businessName"];
            }
            if (parameters["shippingAddressId"] != "")
            {
                req.shippingAddressId = parameters["shippingAddressId"];
            }
            if (parameters["requireShippingAddressSelection"] != "" || parameters["referrerCode"] != "")
            {
                req.senderOptions = new SenderOptions();
                if (parameters["requireShippingAddressSelection"] != "")
                    req.senderOptions.requireShippingAddressSelection = 
                        Boolean.Parse(parameters["requireShippingAddressSelection"]);
                if (parameters["referrerCode"] != "")
                    req.senderOptions.referrerCode = parameters["referrerCode"];
            }
            req.receiverOptions = new List<ReceiverOptions>();
            ReceiverOptions receiverOption = new ReceiverOptions();
            req.receiverOptions.Add(receiverOption);
            if (parameters["description"] != "")
                receiverOption.description = parameters["description"];
            if (parameters["customId"] != "")
                receiverOption.customId = parameters["customId"];

            string[] name = context.Request.Form.GetValues("name");
            string[] identifier = context.Request.Form.GetValues("identifier");
            string[] price = context.Request.Form.GetValues("price");
            string[] itemPrice = context.Request.Form.GetValues("itemPrice");
            string[] itemCount = context.Request.Form.GetValues("itemCount");
            if (name.Length > 0 && name[0] != "")
            {
                receiverOption.invoiceData = new InvoiceData();
                for (int j = 0; j < name.Length; j++)
                {
                    InvoiceItem item = new InvoiceItem();
                    if (name[j] != "")
                        item.name = name[j];
                    if (identifier[j] != "")
                        item.identifier = identifier[j];
                    if (price[j] != "")
                        item.price = Decimal.Parse(price[j]);
                    if (itemPrice[j] != "")
                        item.itemPrice = Decimal.Parse(itemPrice[j]);
                    if (itemCount[j] != "")
                        item.itemCount = Int32.Parse(itemCount[j]);
                    receiverOption.invoiceData.item.Add(item);
                }
                if (parameters["totalTax"] != "")
                    receiverOption.invoiceData.totalTax = Decimal.Parse(parameters["totalTax"]);
                if (parameters["totalShipping"] != "")
                    receiverOption.invoiceData.totalShipping = Decimal.Parse(parameters["totalShipping"]);
            }
            if (parameters["emailIdentifier"] != "" ||
                (parameters["phoneCountry"] != "" && parameters["phoneNumber"] != ""))
            {
                receiverOption.receiver = new ReceiverIdentifier();
                if(parameters["emailIdentifier"] != "")
                    receiverOption.receiver.email = parameters["emailIdentifier"];
                if (parameters["phoneCountry"] != "" && parameters["phoneNumber"] != "")
                {
                    receiverOption.receiver.phone = 
                        new PhoneNumberType(parameters["phoneCountry"], parameters["phoneNumber"]);
                    if (parameters["phoneExtn"] != "")
                        receiverOption.receiver.phone.extension = parameters["phoneExtn"];
                }
            }
            if (parameters["receiverReferrerCode"] != "")
                receiverOption.referrerCode = parameters["receiverReferrerCode"];

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

            // Display response values. 
            Dictionary<string, string> keyResponseParams = new Dictionary<string, string>();            
            displayResponse(context, "SetPaymentOptions", keyResponseParams, service.getLastRequest(), service.getLastResponse(),
                resp.error, null);
        }
Example #29
0
        /// <summary>
        /// Handle Refund API call
        /// </summary>
        /// <param name="context"></param>
        private void Refund(HttpContext context)
        {
            NameValueCollection parameters = context.Request.Params;
            RefundRequest req = new RefundRequest(new RequestEnvelope("en_US"));
            // Set optional parameters
            if(parameters["receiverEmail"].Length > 0) 
            {
                string[] amt = context.Request.Form.GetValues("receiverAmount");
                string[] receiverEmail = context.Request.Form.GetValues("receiverEmail");
                string[] phoneCountry = context.Request.Form.GetValues("phoneCountry");
                string[] phoneNumber = context.Request.Form.GetValues("phoneNumber");
                string[] phoneExtn = context.Request.Form.GetValues("phoneExtn");
                string[] primaryReceiver = context.Request.Form.GetValues("primaryReceiver");
                string[] invoiceId = context.Request.Form.GetValues("invoiceId");
                string[] paymentType = context.Request.Form.GetValues("paymentType");
                string[] paymentSubType = context.Request.Form.GetValues("paymentSubType");

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

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

            // Display response values. 
            Dictionary<string, string> keyResponseParams = new Dictionary<string, string>();
            string redirectUrl = null;
            if (!(resp.responseEnvelope.ack == AckCode.FAILURE) &&
                !(resp.responseEnvelope.ack == AckCode.FAILUREWITHWARNING))
            {
                keyResponseParams.Add("Currency code", resp.currencyCode);
                int idx = 1;
                foreach (RefundInfo refund in resp.refundInfoList.refundInfo)
                {
                    keyResponseParams.Add("Refund receiver " + idx, refund.receiver.email);
                    keyResponseParams.Add("Refund amount " + idx, refund.receiver.amount.ToString());
                    keyResponseParams.Add("Refund status " + idx, refund.refundStatus);
                }
            }
            displayResponse(context, "Refund", keyResponseParams, service.getLastRequest(), service.getLastResponse(),
                resp.error, redirectUrl);
        }
Example #30
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"]);
            // 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);
                }
            }
            displayResponse(context, "Pay", keyResponseParams, service.getLastRequest(), service.getLastResponse(), 
                resp.error, redirectUrl);            
        }