voltrue2 / in-app-purchase

A Node.js module for in-App-Purchase for iOS, Android, Amazon and Windows.
http://iap.gracenode.org
Other
1.04k stars 287 forks source link

Is comparing endDate and current the right way to validate if subscription active? #308

Open nickbullll opened 4 years ago

nickbullll commented 4 years ago

Hey, if I understand right, the only way to check if user subscription is active is to compare expiresDateMs with current date (I have only ios subscriptions)

If I'll call deliverSubscriptionReceipt on every app launch, will this code handle all situations? Like free trails, Introductory Offers and etc for ios subscriptions

async function processPurchase({ receipt }: ProcessPurchase) {
  try {
    await iap.setup();
    const validationResponse = await iap.validate(receipt);
    const purchaseData = iap.getPurchaseData(validationResponse);
    const firstPurchaseItem = purchaseData[0];
    const endDate = new Date(firstPurchaseItem.expiresDateMs);
    const nowMs = new Date().getTime();
    const endDateMs = moment(endDate).valueOf();

    if (endDateMs >= nowMs) {
      return { isPaid: true };
    } else {
      return { isPaid: false };
    }
  } catch (error) {
    // if purchased nothing
    if (error.status == 2) {
      return { isPaid: false };
    } else {
      throw new functions.https.HttpsError(
        'unknown',
        error.message || 'Something went wrong'
      );
    }
  }
}

exports.deliverSubscriptionReceipt = functions.https.onCall(
  async ({ receipt }: { receipt: string }) => {
    const subscription = await processPurchase({ receipt });

    return subscription;
  }
);