Stripe: Prorated amount using billing_cycle_anchor - stripe-payments

I am using billing_cycle_anchor when creating a subscription. I have a requirement where I need to charge from the day of payment to last of the month. And then from 1st of every month.
I am using code shown below:
var date = new Date();
var lastDay = Date.UTC(date.getFullYear(), date.getMonth() + 1, 0);
var monthLastDay = Math.floor(lastDay/1000);
let subscription = {
metadata: metadata,
billing_cycle_anchor: monthLastDay
};
Using above below is what is happening:
Prorated amount is charged from May 16 to May 31st
Subscription is created from May 31 – Jun 30.
But I want subscription to be created from June 1.
EDIT:
Right now time which is being calculated is:
1527724800
which is equivalent to:
05/31/2018 # 12:00am (UTC)
Please let me know possible solution.

Related

stripe upcoming invoice for same billing cycle in stripe

I'd like to show a customer a preview (or a quote) of what their subscription charges will be if they make changes to their subscription. For this, I'm using the "upcoming invoice" API endpoint:
https://stripe.com/docs/api/invoices/upcoming
From that link, they state that "You can preview the effects of updating a subscription, including a preview of what proration will take place.".
here is the exapmle
def retrieveUpcomingInvoice(subscriptionId,customerId,nextPriceId):
try:
# Retrieve the subscription
subscription = stripe.Subscription.retrieve(subscriptionId)
# Retrieve the invoice
invoice = stripe.Invoice.upcoming(
customer=customerId,
subscription=subscriptionId,
subscription_items=[
{
'id': subscription['items']['data'][0].id,
'deleted': True,
},
{
'price': nextPriceId,
'deleted': False,
}
],
)
return invoice
except Exception as e:
return str(e)
i got the amount_due for upgrad subscription amount user has to pay but only for different billing cycle
Monthly to monthly subscription "or" yearly to yearly subscription(same billing cycle):
like if i am on monthly basic subscription for $10 and i upgrade the subscription for advance subscription for $30 than invoice in return i got amount_due for $40 which is merged amount of plus and advanced, which is wrong , because i had already paid for 10$, so amount pay should be 30-10 = 20$ (tested: if i pay then 20$ is cut from account) (and invoice show $40 which is wrong)
Monthly subscription to yearly subscription or Vice-versa (this is ok)
if currently i am on monthly basic subscription for 10$ and i upgrade to yearly plus subscription for 100$ then upcoming invoice in amount_due show me correct information which is 90$ (and also if i pay it cut 90$ from account)
so how to get coorect amount in same billing cycle in stripe
You have a subscription for $10 per month, and after 15 days (half of the month) you want to change it to $30. With the upcoming invoice, you get the invoice the customer should pay in the next billing cycle which includes 3 line items:
Unused time: -$5 (that's the initial price divided by two)
Remaining time: +$15 (that's the new price divided by two)
Next invoice: +$30 (the new price for next month)
Here the total is: -$5 + $15 + $30 = $40 to be paid in 15 days. If that's not what you want you could:
Remove the $30 of the next invoice by passing subscription_proration_behavior: "always_invoice".
Or remove the $15 of the remaining time by passing subscription_billing_cycle_anchor: "now"
Note that changing the billing cycle of a subscription from monthly to yearly works differently, as explained here.
reset your billing cycle for get the exact amount
add subscription_billing_cycle_anchor = "now" at getting upcoming invoice
def retrieveUpcomingInvoice(subscriptionId,customerId,nextPriceId):
try:
# Retrieve the subscription
subscription = stripe.Subscription.retrieve(subscriptionId)
# Retrieve the invoice
invoice = stripe.Invoice.upcoming(
customer=customerId,
subscription=subscriptionId,
subscription_items=[
{
'id': subscription['items']['data'][0].id,
'deleted': True,
},
{
'price': nextPriceId,
'deleted': False,
}
],
subscription_billing_cycle_anchor = "now", # add
)
return invoice
except Exception as e:
return str(e)

Difference between using `Period.Between` and substracting two local dates

Why is the result for the periodBetween.Days and substracted.Days different?
I can see that a periodBetween.Months is 0 and substracted.Months is 2 and I can see how are these two results different, but I don't know why :).
using NodaTime;
void Main()
{
var firstDate = new LocalDate(2020, 8, 1);
var secondDate = new LocalDate(2020, 10, 30);
var periodBetween = Period.Between(firstDate, secondDate, PeriodUnits.Days);
var subtracted = secondDate - firstDate;
Console.WriteLine(periodBetween.Days);
Console.WriteLine(subtracted.Days);
}
Your periodBetween calculation is saying "What's the period between these two dates, using only days?"
Your subtracted calculation is equivalent to calling Period.Between either without specifying any units, or specifying PeriodUnits.Days | PeriodUnits.Months | PeriodUnits.Years - in other words, "What's the period between these two dates, using days, months and years?"
A period has independent values for years, months, days, hours, minutes etc - if you compute a value using years/months/days that's not equivalent to computing a value using just days.
A period of "90 days" is not the same as a period of "2 months and 29 days". In some calculations they'll give the same answer, but not always. For example, if you add "90 days" to January 1st 2020, you'll get March 31st 2020... but if you add "2 months and 29 days" to January 1st 2020, you'll get March 30th 2020.

Node.js | check days left on account

I want to verify Date is valid for subscription.
Date is in UTC format.
when user creates an account i set the expiration date to be the date in 30 days.
Before each action, i want to verify the expiration date of his account.
To get the days left for user i do
let oneDay = 24*60*60*1000;
let daysLeft = (userSubscription.expired - new Date())/(oneDay))
Now i want to check that if daysLeft is 0, then do some action alerting the user.
My problem is, that is if expiration was a year ago, then days left will not be below 0 as i expected, it will be 300+.
how can i enforce it?
With this you just get the difference between those dates:
let oneDay = 24*60*60*1000;
let daysLeft = (userSubscription.expired - new Date())/(oneDay))
So the result after one year would be 365 - 30 = 335
But you need to check if userSubscription.expired is higher than new Date()
Use something from here: Compare two dates

Cron schedule in quartz to fire every week from a specific date for one year

I have a scenario, where I need to schedule a job using quartz which triggers every week from the date specified by the user and this should continue for exactly one year.
After going through Cron Schedule examples, I think below cron expression might help me:
eg. If date specified is 31-10-2015, then the expression would be:
" 0 30 20 31/7 10-10 ? 2015-2016 " which means starting from 31 Oct 3015, trigger after every 7 days for 1 year, ie. till 31 Oct 2016.
Please let me know if there are any issues with this expression.
Thanks.....
Your cron-expression is not valid as per CronMaker.Com. Looking at your cron expression, I have following things:
Your job fires at 8:30PM
It is weekly job running all 7 days of week
It ends in 2016
Here is the correct cron expression :
0 30 20 ? * 2,3,4,5,6,7,1 2015,2016 //Runs all days of week
To expire it on 31st Oct in 2016, you will have to provide Ending time while creating this job.
Update:
If you want to fire this job on a particular day of week, it will be something as below:
0 30 20 ? * MON 2015,2016 //Runs every week on monday
even i had same requirement, i implemented as below
we can run for every seven days from the start date, seven days when converted to hours, value is 168
JobDataMap jobDataMap = new JobDataMap();
jobDataMap.put("json", json);
String startDateStr = "2017-06-21 00:00:00.0";
Date startDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").parse(startDateStr);
String endDateStr = "2018-06-21 00:00:00.0";
Date endDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").parse(endDateStr);
JobDetail job = newJob(SimpleJob.class).withIdentity(name, "group1").build();
Trigger trigger = TriggerBuilder.newTrigger()
.startAt(startDate)
.withSchedule(
SimpleScheduleBuilder.simpleSchedule().withIntervalInHours(168).repeatForever())
.endAt(endDate)
.usingJobData(jobDataMap)
.build();
sched.scheduleJob(job, trigger);
sched.start();
hope it helps!!

how to calculate the number of the week in a year?

I would like to calculte the number of the week in a year. I see this post
In this post the acepted answer use this code:
public static int GetIso8601WeekOfYear(DateTime time)
{
// Seriously cheat. If its Monday, Tuesday or Wednesday, then it'll
// be the same week# as whatever Thursday, Friday or Saturday are,
// and we always get those right
DayOfWeek day = CultureInfo.InvariantCulture.Calendar.GetDayOfWeek(time);
if (day >= DayOfWeek.Monday && day <= DayOfWeek.Wednesday)
{
time = time.AddDays(3);
}
// Return the week of our adjusted day
return CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(time, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
}
However I see a problem. The number of the week is repeated if the last day of a month is in Sunday.
For example, the last day of March of 2013 year is in sunday. This week is the number 13th, is correct. But in April, how C# use always 6 weeks in a month to calculate the number of week, the first week of april has not any day of april, because all the days belong to march because the last day of the week is 30th March. So C# says that the first week of april is th 15th week, but this is incorrect, it has to be 14th.
So I would like to know if there are any way to calculate the number of a week in a right way.
EDIT:
I mean this:
In march, the last week is this:
25 26 27 28 29 30 31
This is the 13th, is correct.
In april, the first week is:
1 2 3 4 5 6 7
And this week is calculated as 15th.
So if I see the march calendar the last week is calculated as 13th and if I see the april calendar the last week of march is caluclated as 14th. This is incorrect.
SOLUTION:
DateTime dtCalendar = Calendar.DisplayDate;
int gridRow = (int)GetValue(Grid.RowProperty);
// Return the week of our adjusted day
int wueekNumber= System.Globalization.CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(dtCalendar, System.Globalization.CalendarWeekRule.FirstDay, DayOfWeek.Monday);
if (dtCalendar.DayOfWeek == DayOfWeek.Monday)
{
gridRow = gridRow - 1;
}
Text = (weekNumbe r+ gridRow - 1).ToString();
Thanks.
The problem is that you are using the wrong CalendarWeekRule. To get the result you want you should use FirstDay. I have seen various codes in internet saying that you should use FirstFourDayWeek but, after some testing, I realised that the "right one" is FirstDay. I have tested it with your example and it delivers the right result: 14th week.
int targetYear = 2013;
DateTime targetDate = new DateTime(targetYear, 4, 1);
int week = System.Globalization.CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(targetDate, System.Globalization.CalendarWeekRule.FirstDay, DayOfWeek.Monday);

Resources