コード例 #1
0
        public async Task <IActionResult> Details(string id)
        {
            var client = _clientFactory.GetClient();

            var request = new AgreementGetRequest(id);
            var result  = await client.Execute(request);

            var agreement = result.Result <Agreement>();

            return(View(agreement));
        }
コード例 #2
0
        private async Task TellPayPalToCancelSubscription(string payPalAgreement)
        {
            try
            {
                var client = _clientFactory.GetClient();

                var requestForPayPalAgreement = new AgreementGetRequest(payPalAgreement);
                var result = await client.Execute(requestForPayPalAgreement);

                var agreement = result.Result <Agreement>();

                var request = new AgreementCancelRequest(payPalAgreement).RequestBody(new AgreementStateDescriptor()
                {
                    Note = "Cancelled"
                });

                await client.Execute(request);
            }
            catch (Exception ex)
            {
                // save error in the database.
                PaypalErrors payPalReturnedError = new PaypalErrors()
                {
                    Exception = ex.Message,
                    DateTime  = DateTime.Now
                };

                this._dbContext.PaypalErrors.Add(payPalReturnedError);
                await this._dbContext.SaveChangesAsync();
            }
        }
コード例 #3
0
        private async Task TellPayPalToCancelSubscription(string payPalAgreement)
        {
            try
            {
                var client = _clientFactory.GetClient();

                var requestForPayPalAgreement = new AgreementGetRequest(payPalAgreement);
                var result = await client.Execute(requestForPayPalAgreement);

                var agreement = result.Result <Agreement>();

                var request = new AgreementCancelRequest(payPalAgreement).RequestBody(new AgreementStateDescriptor()
                {
                    Note = "Cancelled"
                });

                await client.Execute(request);

                var message = $"PayPal has been notified to cancel Subscription :{agreement.Id} for the package : {agreement.Description} under {agreement.Name}.";
                var subject = $"PayPal has been notified to Cancel Subscription :{agreement.Id}";
                await EmailAdmin(message, subject);

                //await EmailSuperAdmin("Notify PayPal to Cancel Subscription SUCCESS", "Notify PayPal to Cancel Subscription SUCCESS");
            }
            catch (Exception ex)
            {
                // save error in the database.
                PaypalErrors payPalReturnedError = new PaypalErrors()
                {
                    Exception = ex.Message,
                    DateTime  = DateTime.Now
                };

                _dbcontext.PaypalErrors.Add(payPalReturnedError);
                await _dbcontext.SaveChangesAsync();

                await EmailSuperAdmin($"Notify PayPal ({payPalAgreement}) to Cancel Subscription Failed", "Notify PayPal to Cancel Subscription Failed");
            }
        }
コード例 #4
0
        public async Task <IActionResult> Index()
        {
            //get user subscription
            var client = _clientFactory.GetClient();
            AgreementGetRequest request = new AgreementGetRequest("I-GY2WH34CHXR5");

            BraintreeHttp.HttpResponse result = await client.Execute(request);

            Agreement agreement = result.Result <Agreement>();

            var payPalCancelSubscription = System.Net.WebRequest.Create("https://api.paypal.com/v1/payments/billing-agreements/I-GY2WH34CHXR5/cancel");

            //Set values for the verification request
            payPalCancelSubscription.Method = "POST";

            var response = payPalCancelSubscription.GetResponse();

            //await AddEmailtoList("*****@*****.**");

            return(View());
        }
コード例 #5
0
        public async Task <IActionResult> SubmitPayouts()
        {
            PayoutBatch payoutBatch = await _context.AddPayoutBatch(GetCurrentPayouts());

            if (payoutBatch.PayoutPaypalBatchId == null)
            {
                PayPalHttpClient client = _clientFactory.GetClient();
                try
                {
                    await client.AuthorizeAsync();

                    await client.CreatePayouts(payoutBatch);

                    await _context.SaveChangesAsync();
                }
                catch (Exception e)
                {
                    return(Json(e.Message));
                }
            }

            return(View(viewName: "Index", model: new List <UserPayoutVM>()));
        }
コード例 #6
0
        private async Task CheckUpdateUserSubscriptionDetails(ApplicationUser user)
        {
            List <UserSubscriptions> userSubs = _dbContext.UserSubscriptions
                                                .Where(x => x.UserId == user.Id && x.PayPalAgreementId != null)
                                                .ToList();

            if (userSubs.Count() > 0)
            {
                List <string> userSubscriptionIds = _dbContext.UserSubscriptions
                                                    .Where(x => x.UserId == user.Id && x.PayPalAgreementId != null)
                                                    .Select(x => x.PayPalAgreementId)
                                                    .ToList();

                foreach (var Id in userSubscriptionIds)
                {
                    //get user subscription
                    var client = _clientFactory.GetClient();
                    AgreementGetRequest        request = new AgreementGetRequest(Id);
                    BraintreeHttp.HttpResponse result  = await client.Execute(request);

                    Agreement agreement = result.Result <Agreement>();

                    //get user subscription
                    UserSubscriptions userExistingSubscription = user.Subscriptions.Where(x => x.PayPalAgreementId == Id).FirstOrDefault();

                    //first time user is cancelling.
                    if (agreement.State == "Cancelled" && userExistingSubscription.State != "Cancelled")
                    {
                        //if this is the first cancellation.
                        if (userExistingSubscription.ExpiryDate.Year < 1995)
                        {
                            //set expiry date in the User Subscription to the next billing date.
                            //"last_payment_date": "2020-06-15T17:57:02Z",
                            // "next_billing_date": "2020-07-15T10:00:00Z",

                            string expiryDateAsString = agreement.AgreementDetails.NextBillingDate.Substring(0, 10);

                            DateTime expiryDate = DateTime.ParseExact(expiryDateAsString, "yyyy-MM-dd", null);

                            userExistingSubscription.ExpiryDate = expiryDate;

                            //update user subscription status.
                            userExistingSubscription.State = agreement.State;

                            //only send cancellation email when Paypal first sends cancellation confirmation.

                            var cancellationEmailAlreadyBeenSent = _dbContext.UserSubscriptions.Where(x => x.UserId == user.Id && x.PayPalAgreementId == agreement.Id && x.State != "Cancelled").Any();
                            if (!cancellationEmailAlreadyBeenSent)
                            {
                                //Send user an email and let them know expiry date.
                                var confirmationHtml = $"<h2>As per your request, your Subscription <strong>{userExistingSubscription.Description}</strong> has been cancelled.</h2> <p>However, you can continue enjoy your access till your paid period expired on {userExistingSubscription.ExpiryDate}.</p>";
                                var sendGridKey      = _configuration.GetValue <string>("SendGridApi");
                                await Emailer.SendEmail(user.Email, "AndyTipster Subscription, has been cancelled", confirmationHtml, sendGridKey);


                                //Send admin an email and let them know expiry date.
                                var confirmationAdminHtml = $"<h2>User {user.Email} has cancelled their subscription for <strong>{userExistingSubscription.Description}</strong>.</h2> <p>However, user has access till their paid period expired on {userExistingSubscription.ExpiryDate}.</p><p>An email confirmation has been sent to user on {user.Email}</p>";
                                await Emailer.SendEmail("*****@*****.**", "A user has cancelled a Subscription", confirmationAdminHtml, sendGridKey);
                            }
                        }
                    }
                    if (agreement.State == "Cancelled" && userExistingSubscription.State == "Cancelled")
                    {
                        //check if subscription date has expired.
                        if (userExistingSubscription.ExpiryDate < DateTime.Now) // user subs expired, delete their subscription.
                        {
                            //delete Subscription.
                            var subsTobeDeleted = _dbContext.Subscriptions.Where(x => x.PayPalAgreementId == agreement.Id).FirstOrDefault();
                            if (subsTobeDeleted != null)
                            {
                                _dbContext.Subscriptions.Remove(subsTobeDeleted);
                            }

                            //delete user Subscription
                            var userSubsToBeDeleted = _dbContext.UserSubscriptions.Where(x => x.UserId == user.Id && x.State == "Cancelled" && x.PayPalAgreementId == agreement.Id).FirstOrDefault();
                            if (userSubsToBeDeleted != null)
                            {
                                _dbContext.UserSubscriptions.Remove(userSubsToBeDeleted);
                            }

                            _dbContext.SaveChanges();

                            //Send user an email and let them know subscription now has expired.
                            var expiredHtml = $"<h2>Your Subscription <strong>{userExistingSubscription.Description}</strong> has now expired.</h2>";
                            var sendGridKey = _configuration.GetValue <string>("SendGridApi");
                            await Emailer.SendEmail(user.Email, "Andy Tipster Subscription has expired.", expiredHtml, sendGridKey);

                            //Send admin an email and let them know expiry.
                            var expiredAdminHtml = $"<h2>User {user.Email} subscription for <strong>{userExistingSubscription.Description}</strong>. has now expired.</h2><p>An email confirmation has been sent to user on {user.Email}</p>";
                            await Emailer.SendEmail("*****@*****.**", $"{userExistingSubscription.PayerEmail} : Subscription has expired.", expiredAdminHtml, sendGridKey);
                        }
                    }

                    await userManager.UpdateAsync(user);
                }
            }
        }
コード例 #7
0
        /// <summary>
        /// Create the default billing plans for this website
        /// </summary>
        private async Task CreatePayPalPlans()
        {
            var client = _clientFactory.GetClient();

            foreach (var plan in BillingPlanSeed.PayPalPlans("https://www.andytipster.com/Subscription/Return", "https://www.andytipster.com/Subscription/Cancel"))

            //foreach (var plan in BillingPlanSeed.PayPalPlans("https://localhost:44376/Subscription/Return", "https://localhost:44376/Subscription/Cancel"))

            {
                // Create Plan
                var request = new PlanCreateRequest().RequestBody(plan);
                BraintreeHttp.HttpResponse result = await client.Execute(request);

                var obj = result.Result <Plan>();

                // Activate Plan
                var activateRequest = new PlanUpdateRequest <Plan>(obj.Id)
                                      .RequestBody(GetActivatePlanBody());

                await client.Execute(activateRequest);



                // Add to database record
                //var dbPlan = _dbContext.BillingPlans.FirstOrDefault(x =>
                //    x.Name == obj.Name);

                //if (dbPlan != null && string.IsNullOrEmpty(dbPlan.PayPalPlanId))
                //{
                //    dbPlan.PayPalPlanId = obj.Id;
                //    await _dbContext.SaveChangesAsync();
                //}
            }

            //// Create plans
            //var justBrowsingPlanRequest = new PlanCreateRequest().RequestBody(justBrowsingPlan);
            //var justBrowsingPlanResult = await client.Execute(justBrowsingPlanRequest);
            //var justBrowsingPlanObject = justBrowsingPlanResult.Result<Plan>();

            //var letsDoThisPlanRequest = new PlanCreateRequest().RequestBody(letsDoThisPlan);
            //var letsDoThisPlanResult = await client.Execute(letsDoThisPlanRequest);
            //var letsDoThisPlanObject = letsDoThisPlanResult.Result<Plan>();

            //var beardIncludedPlanRequest = new PlanCreateRequest().RequestBody(beardIncludedPlan);
            //var beardIncludedPlanResult = await client.Execute(beardIncludedPlanRequest);
            //var beardIncludedPlanObject = beardIncludedPlanResult.Result<Plan>();

            //var hookItToMyVeinsPlanRequest = new PlanCreateRequest().RequestBody(hookItToMyVeinsPlan);
            //var hookItToMyVeinsPlanResult = await client.Execute(hookItToMyVeinsPlanRequest);
            //var hookItToMyVeinsPlanObject = hookItToMyVeinsPlanResult.Result<Plan>();

            //// Activate plans
            //var activateJustBrowsingPlanRequest = new PlanUpdateRequest<Plan>(justBrowsingPlanObject.Id)
            //    .RequestBody(GetActivatePlanBody());
            //await client.Execute(activateJustBrowsingPlanRequest);

            //var activateletsDoThisPlanRequest = new PlanUpdateRequest<Plan>(letsDoThisPlanObject.Id)
            //    .RequestBody(GetActivatePlanBody());
            //await client.Execute(activateletsDoThisPlanRequest);

            //var activateBeardIncludedPlanRequest = new PlanUpdateRequest<Plan>(beardIncludedPlanObject.Id)
            //    .RequestBody(GetActivatePlanBody());
            //await client.Execute(activateBeardIncludedPlanRequest);

            //var activateHookItToMyVeinsPlanRequest = new PlanUpdateRequest<Plan>(hookItToMyVeinsPlanObject.Id)
            //    .RequestBody(GetActivatePlanBody());
            //await client.Execute(activateHookItToMyVeinsPlanRequest);
        }
コード例 #8
0
        public async Task <IActionResult> Purchase(PurchaseVm model)
        {
            var plan    = _dbContext.BillingPlans.FirstOrDefault(x => x.PayPalPlanId == model.Product.PayPalPlanId);
            var product = _dbContext.Products.FirstOrDefault(x => x.PayPalPlanId == model.Product.PayPalPlanId);

            //check DUPLICATES
            ApplicationUser currentUser = await _userManager.GetUserAsync(User);

            var userhasAnySubscriptions = _dbContext.UserSubscriptions.Any(x => x.UserId == currentUser.Id && x.SubscriptionId != null);

            if (userhasAnySubscriptions)
            {
                List <UserSubscriptions> subscribedPlans = _dbContext.UserSubscriptions.Where(x => x.UserId == currentUser.Id && x.SubscriptionId != null).ToList();

                bool alreadySusbcribedToThisPlan = subscribedPlans.Any(x => x.PayPalPlanId == product.PayPalPlanId);

                if (alreadySusbcribedToThisPlan)
                {
                    return(RedirectToAction("DuplicateSubscriptionFound", product));
                }
            }


            if (ModelState.IsValid && plan != null)
            {
                // Since we take an Initial Payment (instant payment), the start date of the recurring payments will be next month.
                //var startDate = DateTime.UtcNow.AddMonths(1);

                //set subscription start date based on plan.
                var startDate = DateTime.UtcNow;
                if (plan.Name.Contains("Monthly"))
                {
                    startDate = DateTime.UtcNow.AddMonths(1);
                }

                if (plan.Name.Contains("3 Months"))
                {
                    startDate = DateTime.UtcNow.AddMonths(3);
                }


                //start_date string required
                //The date and time when this agreement begins, in Internet date and time format.
                //The start date must be no less than 24 hours after the current date as the agreement can take up to 24 hours to activate.
                //The start date and time in the create agreement request might not match the start date and time that the API returns
                //in the execute agreement response. When you execute an agreement, the API internally converts the start date and time to
                //the start of the day in the time zone of the merchant account.For example, the API converts a 2017 - 01 - 02T14: 36:21Z start date and time
                //for an account in the Berlin time zone(UTC + 1) to 2017 - 01 - 02T00:00:00.When the API returns this date and time in the
                //execute agreement response, it shows the converted date and time in the UTC time zone.So,
                //the internal 2017-01-02T00:00:00 start date and time becomes 2017-01-01T23:00:00 externally.
                string formatedStringDate = startDate.ToString("o", CultureInfo.InvariantCulture);
                var    formatedStartDate  = DateTime.Parse(formatedStringDate, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind);

                //DateTime.UtcNow.ToString("o");


                var subscription = new Subscription()
                {
                    FirstName    = currentUser.FirstName,
                    LastName     = currentUser.LastName,
                    Email        = currentUser.Email,
                    StartDate    = formatedStartDate, //stat date has to be greator than now.
                    PayPalPlanId = plan.PayPalPlanId
                };
                _dbContext.Subscriptions.Add(subscription);


                var userNewSubscriptoin = new UserSubscriptions()
                {
                    PayPalPlanId = plan.PayPalPlanId,
                    Description  = plan.Description,
                    User         = currentUser,
                    UserId       = currentUser.Id
                };

                _dbContext.UserSubscriptions.Add(userNewSubscriptoin);

                _dbContext.SaveChanges();

                var agreement = new Agreement()
                {
                    Name        = plan.Name,
                    Description = plan.Description,
                    StartDate   = startDate.ToString("yyyy-MM-ddTHH:mm:ssZ"),
                    Plan        = new PlanWithId()
                    {
                        Id = Convert.ToString(plan.PayPalPlanId)
                    },
                    Payer = new Payer()
                    {
                        PaymentMethod = "paypal"
                    }
                };


                // Send the agreement to PayPal
                var client  = _clientFactory.GetClient();
                var request = new AgreementCreateRequest()
                              .RequestBody(agreement);
                var result = await client.Execute(request);

                Agreement createdAgreement = result.Result <Agreement>();

                // Find the Approval URL to send our user to (also contains the token)
                var approvalUrl =
                    createdAgreement.Links.FirstOrDefault(
                        x => x.Rel.Equals("approval_url", StringComparison.OrdinalIgnoreCase));

                var token = QueryHelpers.ParseQuery(approvalUrl?.Href)["token"].First();

                // Save the token so we can match the returned request to our subscription.
                subscription.PayPalAgreementToken = token;


                _dbContext.SaveChanges();

                // Send the user to PayPal to approve the payment
                return(Redirect(approvalUrl.Href));
            }

            model.Product = product;
            return(View(model));
        }