It's amazing that a company as big as Google that charges 30% on top of subscriptions makes it so hard to implement. Their docs are honestly some of the worst I've ever seen.
Entire companies like Revenue cat revolve around making something that should be easy for the developer, in-fact, easy..
Currently we have to record the users purchases on a database, then we have a checked that CRONs every 2 weeks with a 'last checked value' so it doesn't bulk up.
We also track what is active and not, not pinging active subs.
The following code requires 'googleapis' and that setup for nodejs.
/**
* Use expiryTimeMillis to check if the subscription is still valid
*/
export const androidCheckSubscriptionStatus = async (props: {
token: string;
skuName: string;
}): Promise<androidpublisher_v3.Schema$SubscriptionPurchase> => {
try {
const { token, skuName } = props;
await initAndroidApisClient();
/**
* If this throws, it might be bad request, and not that the token is invalid.
* For example connection issues.
*/
const result = await androidClient.purchases.subscriptions.get({
packageName: 'com.vegiano.app',
subscriptionId: skuName,
// The token is from the original payment.
token: token,
});
/**
* It will expire so unassign it.
* The unassign will unassign when the month ends for the subscription.
*/
if (result.data.expiryTimeMillis) {
const tokensToUnassign = await SubscriptionToken.findAll({
where: {
subscriptionMeta: token,
},
});
for (const token of tokensToUnassign) {
if (token.activeUserIdSubscribedTo) {
const user = await User.findOne({ where: { id: token.userId } });
const updatedToken = await unassignToken({ tokenId: token.id, owner: user!, paymentFailed: true });
}
}
}
return result.data;
//
} catch (error) {
console.error('checkAndroidSubscriptionValid failed');
console.error(error);
throw error;
}
};