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));
        }
        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);
        }
示例#3
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());
        }
示例#4
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);
    }
示例#5
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);
        }
示例#7
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);
        }
示例#8
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));
            }
        }
示例#9
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);
        }
示例#10
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);
        }
示例#11
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);            
        }
        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"));
            }
        }
示例#13
0
        public void Pay()
        {
            Random r = new Random();
            int    PayPalPurchaseTransactionId = r.Next();      // -10;
            string PayPalRedirectUrl           = "www.cnn.com"; // ConfigurationManager.AppSettings["PAYPAL_REDIRECT_URL"];
            // Instantiate PayPalResponse class
            GIBSPayPal objPayPalResponse = new GIBSPayPal();

            objPayPalResponse.PayPalPaykey            = " ";
            objPayPalResponse.PayPalPaymentExecStatus = " ";
            objPayPalResponse.PayPalRedirectUrl       = PayPalRedirectUrl;
            objPayPalResponse.PayPalErrorMessage      = " ";
            objPayPalResponse.PayPalError             = false;
            string currentPath =
                System.Web.HttpContext.Current.Request.Url.OriginalString
                .Replace(@"/PayPal_Call_back.ashx", "");

            string strActionType = "PAY";
            string currencyCode  = "USD";
            string cancelUrl     = string.Format(@"{0}&mode=cancel", currentPath);
            string returnUrl     = String.Format(@"{0}&payment=complete", currentPath);
            string IpnURL        = String.Format(@"{0}/PayPal/IPNListener.aspx", currentPath);

            ReceiverList receiverList = new ReceiverList();

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

            Receiver Receiver1 = new Receiver(Decimal.Parse("5.59"));

            Receiver1.email     = "*****@*****.**";
            Receiver1.primary   = false;
            Receiver1.invoiceId = "";

            Receiver1.paymentType = "SERVICE";

            receiverList.receiver.Add(Receiver1);

            PayRequest req = new PayRequest(new RequestEnvelope("en_US"),
                                            strActionType,
                                            cancelUrl,
                                            currencyCode,
                                            receiverList,
                                            returnUrl);

            //// IPN Url (only enable with a published internet accessable application)
            //req.ipnNotificationUrl = IpnURL;
            //req.reverseAllParallelPaymentsOnError = true;
            //req.trackingId = PayPalPurchaseTransactionId.ToString();


            // Call PayPal to get PayKey
            Dictionary <string, string> configMap = new Dictionary <string, string>();

            //configMap = GetConfig();
            configMap.Add("mode", "sandbox");
            // Signature Credential
            configMap.Add("account1.apiUsername", "joe-facilitator_api1.gibs.com");
            configMap.Add("account1.apiPassword", "5UX8EJBTREJQ33MH");
            configMap.Add("account1.apiSignature", "An5ns1Kso7MWUdW4ErQKJJJ4qi4-AM3p4jdO1vcSS2ClRObAqbmoxWeN");
            configMap.Add("account1.applicationId", "APP-80W284485P519543T");

            //configMap.Add("account1.apiUsername", "joe_api1.gibs.com");
            //configMap.Add("account1.apiPassword", "Y5M699WXLTEF976T");
            //configMap.Add("account1.apiSignature", "AUHOQLvCB6h8yLQ2ZC0YcUb3EuZjAY-OG4J5Hkaj35SjMEkMxhoMslvt");
            //configMap.Add("account1.applicationId", "APP-80W284485P519543T");
            // Sandbox Email Address
            //configMap.Add("sandboxEmailAddress", "*****@*****.**");

            AdaptivePaymentsService service = new AdaptivePaymentsService(configMap);
            PayResponse             resp    = null;

            try
            {
                resp = service.Pay(req);
            }

            catch (System.Exception e)
            {
                objPayPalResponse.PayPalError        = true;
                objPayPalResponse.PayPalErrorMessage = e.Message;
                PayPalPaykey = " Catch " + e.Message; // resp.payKey;
            }
            // Check for errors
            if ((resp.responseEnvelope.ack == AckCode.FAILURE) ||
                (resp.responseEnvelope.ack == AckCode.FAILUREWITHWARNING))
            {
                string strError = "";
                objPayPalResponse.PayPalError = true;
                foreach (var error in resp.error)
                {
                    strError = strError + " " + error.message;
                }
                objPayPalResponse.PayPalErrorMessage = strError;
                PayPalPaykey = " " + strError;// resp.payKey;
            }
            else
            {
                objPayPalResponse.PayPalPaykey = resp.payKey;
                PayPalPaykey = resp.payKey;
                objPayPalResponse.PayPalPaymentExecStatus = resp.paymentExecStatus;
            }
        }