コード例 #1
0
        private PaypalResponse GetBillingAgreementID(CreateBillingAgreementResponseType setECResponse)
        {
            PaypalResponse responseObject = new PaypalResponse();

            responseObject.ApiStatus = setECResponse.Ack.ToString();
            if (setECResponse.Ack.Equals(AckCodeType.FAILURE) || (setECResponse.Errors != null && setECResponse.Errors.Count > 0))
            {
                responseObject.ResponseError       = setECResponse.Errors;
                responseObject.ResponseRedirectURL = null;
                responseObject.CorrelationID       = setECResponse.CorrelationID;
                responseObject.Timestamp           = setECResponse.Timestamp;
                responseObject.ACK = "FAILURE";
                //Todo Log Error to database


                return(responseObject);
            }
            else
            {
                responseObject.CorrelationID      = setECResponse.CorrelationID;
                responseObject.Timestamp          = setECResponse.Timestamp;
                responseObject.ACK                = "SUCCESS";
                responseObject.ResponseError      = null;
                responseObject.BillingAgreementID = setECResponse.BillingAgreementID;
                //TodoLog to Databse
                return(responseObject);
            }
        }
コード例 #2
0
        public PaypalResponse CreateBillingAgreement(PaypalResponse response)
        {
            CreateBillingAgreementRequestType request = new CreateBillingAgreementRequestType();

            // (Required) The time-stamped token returned in the SetCustomerBillingAgreement response.
            // Note: The token expires after 3 hours.
            request.Token = response.ECToken;

            // Invoke the API
            CreateBillingAgreementReq wrapper = new CreateBillingAgreementReq();

            wrapper.CreateBillingAgreementRequest = request;

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

            // Create the PayPalAPIInterfaceServiceService service object to make the API call
            PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(configurationMap);

            // # API call
            // Invoke the CreateBillingAgreement method in service wrapper object
            CreateBillingAgreementResponseType billingAgreementResponse = service.CreateBillingAgreement(wrapper);
            PaypalResponse responsePaypal = new PaypalResponse();

            responsePaypal = GetBillingAgreementID(billingAgreementResponse);
            return(responsePaypal);
        }
コード例 #3
0
        private PaypalResponse ProcessResponse(SetExpressCheckoutResponseType setECResponse)
        {
            PaypalResponse responseObject = new PaypalResponse();

            responseObject.ApiStatus = setECResponse.Ack.ToString();
            if (setECResponse.Ack.Equals(AckCodeType.FAILURE) || (setECResponse.Errors != null && setECResponse.Errors.Count > 0))
            {
                responseObject.ResponseError       = setECResponse.Errors;
                responseObject.ResponseRedirectURL = null;
                responseObject.CorrelationID       = setECResponse.CorrelationID;
                responseObject.Timestamp           = setECResponse.Timestamp;
                responseObject.ACK = setECResponse.Ack.ToString();
                //Todo Log Error to database
                return(responseObject);
            }
            else
            {
                responseObject.CorrelationID       = setECResponse.CorrelationID;
                responseObject.Timestamp           = setECResponse.Timestamp;
                responseObject.ACK                 = responseObject.ACK = setECResponse.Ack.ToString();
                responseObject.ResponseError       = null;
                responseObject.ECToken             = setECResponse.Token;
                responseObject.ResponseRedirectURL = System.Configuration.ConfigurationManager.AppSettings["RedirectURL"] + "_express-checkout&token=" + setECResponse.Token;
                //Log to Database
                return(responseObject);
            }
        }
コード例 #4
0
        public PaypalResponse SetExpressCheckout(string userpackageID, string email, string orderDescription, string billingAgreementText,
                                                 string LogoURL, string brandName, double itemTotalAmount, string PlanName, double planAmount, string planDescription)
        {
            // Create request object
            SetExpressCheckoutRequestType request = new SetExpressCheckoutRequestType();

            PopulateRequestObject(request, email, orderDescription, billingAgreementText, LogoURL, brandName, itemTotalAmount, PlanName, planAmount, planDescription);

            // Invoke the API
            SetExpressCheckoutReq wrapper = new SetExpressCheckoutReq();

            wrapper.SetExpressCheckoutRequest = request;

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

            // Create the PayPalAPIInterfaceServiceService service object to make the API call
            PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(configurationMap);


            string fileName      = DateTime.Now.ToString("Request_" + userpackageID + "_" + "yyyy-MM-dd-HH-mm", CultureInfo.InvariantCulture) + ".txt";
            string baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
            string path          = "~/App_Data/";

            path = path.Replace("~/", "").TrimStart('/').Replace('/', '\\');
            path = path + fileName;

            string reqString = string.Empty;

            reqString = JsonConvert.SerializeObject(wrapper);
            string text = "Paypal request: " + DateTime.Now.ToString();

            text += Environment.NewLine + Environment.NewLine + "request string: " + reqString;
            System.IO.File.WriteAllText(Path.Combine(baseDirectory, path), text);

            // # API call
            // Invoke the SetExpressCheckout method in service wrapper object
            SetExpressCheckoutResponseType setECResponse = service.SetExpressCheckout(wrapper);

            string responseString = string.Empty;

            responseString = JsonConvert.SerializeObject(setECResponse);

            PaypalResponse responsePaypal = new PaypalResponse();

            responsePaypal = ProcessResponse(setECResponse);
            return(responsePaypal);
        }
コード例 #5
0
        public ActionResult Success(decimal planId, string payerId, string paymentId)
        {
            try
            {
                decimal userId = Convert.ToDecimal(UserHelper.GetUserId());

                //-----For sending Invoice mail------
                decimal recordId = 0;

                using (LaxNarroEntities ctx = new LaxNarroEntities())
                {
                    using (var transaction = ctx.Database.BeginTransaction())
                    {
                        int?maxInvoice = ctx.User_Transaction_Master.Max(u => u.Invoice_No);

                        Rate_Card rate_card = ctx.Rate_Card.Include(x => x.Plan_Master)
                                              .Where(m => m.Plan_Id == planId && m.Status == "Active").FirstOrDefault();

                        User_Transaction_Master userTransaction = new User_Transaction_Master();

                        IEnumerable <User_Transaction_Master> userAllTransaction = ctx.User_Transaction_Master
                                                                                   .Where(x => x.User_ID == userId);

                        // Set the payer for the payment
                        var paymentExecution = new PaymentExecution()
                        {
                            payer_id = payerId
                        };

                        // Identify the payment to execute
                        var payment = new Payment()
                        {
                            id = paymentId
                        };

                        var apiContext = GetAPIContext();

                        // Execute the Payment
                        var executedPayment = payment.Execute(apiContext, paymentExecution);

                        int?max = userAllTransaction.Max(u => (int?)u.Invoice_No);

                        User_Transaction_Master maxedInvoicedTransaction = userAllTransaction
                                                                           .FirstOrDefault(x => x.User_ID == userId && x.Invoice_No == max);

                        int?maxedInvoiceNo = ctx.User_Transaction_Master.Max(u => (int?)u.Invoice_No);

                        if (executedPayment.state == "approved")
                        {
                            //---------For new payment record (second time payment and so on)-------
                            if (maxedInvoicedTransaction.Payment_Status != "N/A")
                            {
                                userTransaction.Amount = Convert.ToDecimal(rate_card.Amount);

                                DateTime?endDate    = maxedInvoicedTransaction.End_Date;
                                string   strEndDate = string.Empty;
                                if (endDate != null)
                                {
                                    strEndDate = endDate.ToString();
                                }

                                userTransaction.Start_Date = Convert.ToDateTime(strEndDate);

                                if (rate_card.Plan_Master.Plan == "Yearly")
                                {
                                    userTransaction.End_Date = userTransaction.Start_Date.AddYears(1);
                                }
                                else
                                {
                                    userTransaction.End_Date = userTransaction.Start_Date.AddYears(2);
                                }

                                if (maxInvoice == null)
                                {
                                    userTransaction.Invoice_No = 1;
                                }
                                else
                                {
                                    userTransaction.Invoice_No = maxInvoice + 1;
                                }

                                userTransaction.Payment_Date = DateTime.Today;

                                userTransaction.Payment_Method = "Online";
                                userTransaction.Payment_Status = "Paid";
                                userTransaction.Paypal_PayerId = payerId;
                                userTransaction.PlanID         = rate_card.Plan_Id;
                                userTransaction.Rate_ID        = rate_card.Rate_Id;

                                userTransaction.Status             = "Active";
                                userTransaction.Transaction_Status = executedPayment.state;
                                userTransaction.Transection_ID     = executedPayment.id;
                                userTransaction.User_ID            = userId;

                                ctx.User_Transaction_Master.Add(userTransaction);
                                ctx.SaveChanges();

                                recordId = userTransaction.Id;
                            }

                            //---------For updating the demo record (First time payment)-------
                            else
                            {
                                maxedInvoicedTransaction.Amount = Convert.ToDecimal(rate_card.Amount);

                                if (rate_card.Plan_Master.Plan == "Yearly")
                                {
                                    maxedInvoicedTransaction.End_Date = DateTime.Today.AddYears(1);
                                }
                                else
                                {
                                    maxedInvoicedTransaction.End_Date = DateTime.Today.AddYears(2);
                                }

                                if (maxInvoice == null)
                                {
                                    maxedInvoicedTransaction.Invoice_No = 1;
                                }
                                else
                                {
                                    maxedInvoicedTransaction.Invoice_No = maxInvoice + 1;
                                }

                                maxedInvoicedTransaction.Payment_Date = DateTime.Today;

                                maxedInvoicedTransaction.Payment_Method = "Online";
                                maxedInvoicedTransaction.Payment_Status = "Paid";
                                maxedInvoicedTransaction.Paypal_PayerId = payerId;
                                maxedInvoicedTransaction.PlanID         = rate_card.Plan_Id;
                                maxedInvoicedTransaction.Rate_ID        = rate_card.Rate_Id;

                                //DateTime? endDate = maxedInvoicedTransaction.End_Date;
                                //string strEndDate = string.Empty;
                                //if (endDate != null)
                                //    strEndDate = endDate.ToString();
                                maxedInvoicedTransaction.Start_Date = DateTime.Today;

                                maxedInvoicedTransaction.Status             = "Active";
                                maxedInvoicedTransaction.Transaction_Status = executedPayment.state;
                                maxedInvoicedTransaction.Transection_ID     = executedPayment.id;
                                maxedInvoicedTransaction.User_ID            = userId;

                                ctx.Entry(maxedInvoicedTransaction).State = EntityState.Modified;
                                ctx.SaveChanges();

                                recordId = maxedInvoicedTransaction.Id;
                            }

                            PaypalResponse paypalResponse = new PaypalResponse
                            {
                                user_id            = userId,
                                Paypal_ReferenceId = executedPayment.id,
                                intent             = executedPayment.intent,
                                payer          = Convert.ToString(executedPayment.payer),
                                payee          = Convert.ToString(executedPayment.payee),
                                note_to_payer  = executedPayment.note_to_payer,
                                update_time    = executedPayment.update_time,
                                create_time    = executedPayment.create_time,
                                response_state = executedPayment.state,
                                failure_reason = executedPayment.failure_reason
                            };

                            ctx.PaypalResponses.Add(paypalResponse);
                            ctx.SaveChanges();

                            transaction.Commit();

                            MailLog user = ctx.MailLogs.FirstOrDefault(x => x.UserID == userId);
                            user.LastReminderStatus = "Deactive";
                            ctx.SaveChanges();
                        }

                        Thread thread = new Thread(() => SendInvoice(recordId));
                        thread.Start();

                        User_Profile userMail = ctx.User_Profile.Where(p => p.ID == userId).FirstOrDefault();

                        Thread thread2 = new Thread(() => SendMail(userMail.FirstName, userMail.LastName, userMail.EmailAddress, "",
                                                                   "Lexnarro - Subscription Successful", "~/EmailTemplate/SubscriptionMail.html"));
                        thread2.Start();

                        //SendMail(userMail.FirstName, userMail.LastName, userMail.EmailAddress, "",
                        //    "Lexnarro - Subscription Successful", "~/EmailTemplate/SubscriptionMail.html");

                        TempData["message"] = ToasterMessage.Message(ToastType.success, "Subscription successful. Thank you.");
                    }
                }
            }

            catch (DbEntityValidationException e)
            {
                string errorMessage = string.Empty;

                foreach (DbEntityValidationResult eve in e.EntityValidationErrors)
                {
                    Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                                      eve.Entry.Entity.GetType().Name, eve.Entry.State);

                    foreach (DbValidationError ve in eve.ValidationErrors)
                    {
                        Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                                          ve.PropertyName, ve.ErrorMessage);
                        errorMessage = ve.ErrorMessage;

                        TempData["message"] = ViewBag.message + ToasterMessage.Message(ToastType.error, errorMessage);
                    }
                }
            }

            catch (Exception r)
            {
                TempData["message"] = ToasterMessage.Message(ToastType.error, "Something went wrong");
            }
            return(RedirectToAction("Index"));
        }
コード例 #6
0
        public ReturnData PostTransaction(string email, string Plan_ID, string payerId, string Rate_Id,
                                          string paymentId, string Amount, string Transection_ID)
        {
            ReturnData rd = new ReturnData();

            if (email == string.Empty || Plan_ID == string.Empty || payerId == string.Empty || paymentId == string.Empty ||
                Rate_Id == string.Empty || Amount == string.Empty || Transection_ID == string.Empty)
            {
                rd.Status     = "Failure";
                rd.Message    = "Missing Parameters";
                rd.Requestkey = "PostTransactions";
                return(rd);
            }

            try
            {
                decimal userId = db.User_Profile.Where(x => x.EmailAddress == email).Select(x => x.ID).First();

                //-----For sending Invoice mail------
                decimal recordId = 0;

                decimal planId = Convert.ToDecimal(Plan_ID);

                using (LaxNarroEntities ctx = new LaxNarroEntities())
                {
                    using (var transaction = ctx.Database.BeginTransaction())
                    {
                        int?maxInvoice = ctx.User_Transaction_Master.Max(u => u.Invoice_No);

                        Rate_Card rate_card = ctx.Rate_Card.Include(x => x.Plan_Master)
                                              .Where(m => m.Plan_Id == planId && m.Status == "Active" && m.Plan_Master.Plan != "Demo").FirstOrDefault();

                        if (rate_card == null)
                        {
                            rd.Status     = "Failure";
                            rd.Message    = "Invalid Plan (Demo)";
                            rd.Requestkey = "PostTransactions";
                            return(rd);
                        }


                        //if(rate_card.Amount !=Convert.ToDecimal(Amount))
                        //{
                        //    PaypalResponse paypalResponse1 = new PaypalResponse
                        //    {
                        //        user_id = userId,
                        //        Paypal_ReferenceId = paymentId,
                        //        intent = "sale",
                        //        payer = "Android",
                        //        payee = string.Empty,
                        //        note_to_payer = "From Android",
                        //        update_time = Convert.ToString(DateTime.Today),
                        //        create_time = Convert.ToString(DateTime.Today),
                        //        response_state = "created",
                        //        failure_reason = "Invalid Amount"
                        //    };

                        //    ctx.PaypalResponses.Add(paypalResponse1);
                        //    ctx.SaveChanges();

                        //    transaction.Commit();


                        //    rd.Status = "Failure";
                        //    rd.Message = "Invalid Amount";
                        //    rd.Requestkey = "PostTransactions";
                        //    return rd;


                        //}



                        User_Transaction_Master userTransaction = new User_Transaction_Master();

                        List <User_Transaction_Master> userAllTransaction = ctx.User_Transaction_Master
                                                                            .Where(x => x.User_ID == userId).ToList();

                        // Set the payer for the payment
                        var paymentExecution = new PaymentExecution()
                        {
                            payer_id = payerId
                        };

                        // Identify the payment to execute
                        var payment = new Payment()
                        {
                            id = paymentId
                        };

                        //var apiContext = GetAPIContext();

                        // Execute the Payment
                        //var executedPayment = payment.Execute(apiContext, paymentExecution);

                        int?max = userAllTransaction.Max(u => (int?)u.Invoice_No);

                        User_Transaction_Master maxedInvoicedTransaction = userAllTransaction
                                                                           .FirstOrDefault(x => x.User_ID == userId && x.Invoice_No == max);

                        int?maxedInvoiceNo = ctx.User_Transaction_Master.Max(u => (int?)u.Invoice_No);

                        //if (executedPayment.state == "approved")
                        //{
                        //---------For new payment record (second time payment and so on)-------
                        if (maxedInvoicedTransaction.Payment_Status != "N/A")
                        {
                            userTransaction.Amount = Convert.ToDecimal(rate_card.Amount);

                            DateTime?endDate    = maxedInvoicedTransaction.End_Date;
                            string   strEndDate = string.Empty;
                            if (endDate != null)
                            {
                                strEndDate = endDate.ToString();
                            }

                            userTransaction.Start_Date = Convert.ToDateTime(strEndDate);

                            if (rate_card.Plan_Master.Plan == "Yearly")
                            {
                                userTransaction.End_Date = userTransaction.Start_Date.AddYears(1);
                            }
                            else
                            {
                                userTransaction.End_Date = userTransaction.Start_Date.AddYears(2);
                            }

                            if (maxInvoice == null)
                            {
                                userTransaction.Invoice_No = 1;
                            }
                            else
                            {
                                userTransaction.Invoice_No = maxInvoice + 1;
                            }

                            userTransaction.Payment_Date = DateTime.Today;

                            userTransaction.Payment_Method = "Online";
                            userTransaction.Payment_Status = "Paid";
                            userTransaction.Paypal_PayerId = payerId;
                            userTransaction.PlanID         = rate_card.Plan_Id;
                            userTransaction.Rate_ID        = rate_card.Rate_Id;

                            userTransaction.Status             = "Active";
                            userTransaction.Transaction_Status = "approved";
                            userTransaction.Transection_ID     = Transection_ID;
                            userTransaction.User_ID            = userId;

                            ctx.User_Transaction_Master.Add(userTransaction);
                            ctx.SaveChanges();

                            recordId = userTransaction.Id;

                            rd.Status     = "Success";
                            rd.Message    = "Transaction Saved";
                            rd.Requestkey = "PostTransactions";
                            //return rd;
                        }

                        //---------For updating the demo record (First time payment)-------
                        else
                        {
                            maxedInvoicedTransaction.Amount = Convert.ToDecimal(rate_card.Amount);

                            if (rate_card.Plan_Master.Plan == "Yearly")
                            {
                                maxedInvoicedTransaction.End_Date = DateTime.Today.AddYears(1);
                            }
                            else
                            {
                                maxedInvoicedTransaction.End_Date = DateTime.Today.AddYears(2);
                            }

                            if (maxInvoice == null)
                            {
                                maxedInvoicedTransaction.Invoice_No = 1;
                            }
                            else
                            {
                                maxedInvoicedTransaction.Invoice_No = maxInvoice + 1;
                            }

                            maxedInvoicedTransaction.Payment_Date = DateTime.Today;

                            maxedInvoicedTransaction.Payment_Method = "Online";
                            maxedInvoicedTransaction.Payment_Status = "Paid";
                            maxedInvoicedTransaction.Paypal_PayerId = payerId;
                            maxedInvoicedTransaction.PlanID         = rate_card.Plan_Id;
                            maxedInvoicedTransaction.Rate_ID        = rate_card.Rate_Id;

                            //DateTime? endDate = maxedInvoicedTransaction.End_Date;
                            //string strEndDate = string.Empty;
                            //if (endDate != null)
                            //    strEndDate = endDate.ToString();
                            maxedInvoicedTransaction.Start_Date = DateTime.Today;

                            maxedInvoicedTransaction.Status             = "Active";
                            maxedInvoicedTransaction.Transaction_Status = "approved";
                            maxedInvoicedTransaction.Transection_ID     = Transection_ID;
                            maxedInvoicedTransaction.User_ID            = userId;

                            ctx.Entry(maxedInvoicedTransaction).State = EntityState.Modified;
                            ctx.SaveChanges();

                            recordId = maxedInvoicedTransaction.Id;

                            rd.Status     = "Success";
                            rd.Message    = "Transaction Saved";
                            rd.Requestkey = "PostTransactions";
                            //return rd;
                        }

                        PaypalResponse paypalResponse = new PaypalResponse
                        {
                            user_id            = userId,
                            Paypal_ReferenceId = paymentId,
                            intent             = "sale",
                            payer          = "Android",
                            payee          = string.Empty,
                            note_to_payer  = "From Android",
                            update_time    = Convert.ToString(DateTime.Today),
                            create_time    = Convert.ToString(DateTime.Today),
                            response_state = "approved",
                            failure_reason = string.Empty
                        };

                        ctx.PaypalResponses.Add(paypalResponse);
                        ctx.SaveChanges();

                        MailLog user = ctx.MailLogs.FirstOrDefault(x => x.UserID == userId);
                        if (user != null)
                        {
                            user.LastReminderStatus = "Deactive";
                            ctx.SaveChanges();
                        }


                        transaction.Commit();
                    }

                    Thread thread = new Thread(() => SendInvoice(recordId, userId));
                    thread.Start();

                    User_Profile userMail = ctx.User_Profile.Where(p => p.ID == userId).FirstOrDefault();

                    Thread thread2 = new Thread(() => SendMail(userMail.FirstName, userMail.LastName, userMail.EmailAddress, "",
                                                               "Lexnarro - Subscription Successful", "~/EmailTemplate/SubscriptionMail.html"));
                    thread2.Start();

                    return(rd);
                }
            }

            //catch (DbEntityValidationException e)
            //{
            //    string errorMessage = string.Empty;

            //    foreach (DbEntityValidationResult eve in e.EntityValidationErrors)
            //    {
            //        Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
            //            eve.Entry.Entity.GetType().Name, eve.Entry.State);

            //        foreach (DbValidationError ve in eve.ValidationErrors)
            //        {
            //            Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
            //                ve.PropertyName, ve.ErrorMessage);
            //            errorMessage = ve.ErrorMessage;

            //            //TempData["message"] = ViewBag.message + ToasterMessage.Message(ToastType.error, errorMessage);
            //        }
            //    }
            //}

            catch (Exception r)
            {
                rd.Status     = "Failure";
                rd.Message    = "Something went wrong. Please contact administrator";
                rd.Requestkey = "PostTransactions";
                return(rd);
            }
        }