Skip to content

Instantly share code, notes, and snippets.

@d-sea
Last active October 19, 2023 23:48
Show Gist options
  • Save d-sea/3c06862355657a358916b898e5110bec to your computer and use it in GitHub Desktop.
Save d-sea/3c06862355657a358916b898e5110bec to your computer and use it in GitHub Desktop.
firebase functions Android サブスク更新をチェックして最新レシートをFirestoreに保存する
exports.verifySubscriptionAndroid = functions.pubsub.schedule('0 2 * * 0').timeZone('Asia/Tokyo').onRun(async (context) => {
// 該当レシートを検索
const now = Date.now();
const termTime = 24 * 60 * 60 * 1000; // 24時間間隔でチェックするため
const minTime = now - termTime;
const receiptsSnapshot = await admin.firestore().collectionGroup("receipts")
.where("expires_date_ms", "<=", now)
.where("expires_date_ms", ">", minTime)
.orderBy("expires_date_ms")
.orderBy("orderId")
.get();
if (receiptsSnapshot.empty) {
console.log('result: DOCUMENT_NOT_FOUND');
return { result: DOCUMENT_NOT_FOUND };
}
console.log('Find target receipts.');
receiptsSnapshot.forEach(async doc => {
// receipt_data を使って検証する
const verificationData = doc.data().receipt_data;
const latestReceipt = await verifyReceiptAndroid(verificationData, null);
if (latestReceipt === null || latestReceipt === undefined) {
console.log('result: INVALID_RECEIPT');
return { result: INVALID_RECEIPT };
}
// 期限内であることを確認する
const expireDate = Number(latestReceipt["expiryTimeMillis"]);
if (now < expireDate) {
// Firestoreに保存する
const decodedReceipt = JSON.parse(verificationData);
const purchaseDate = new Date(parseInt(latestReceipt["startTimeMillis"]));
const expiresDate = new Date(parseInt(latestReceipt["expiryTimeMillis"]));
const userRef = doc.ref.parent.parent;
const receiptRef = userRef.collection('receipts').doc();
const result = await receiptRef.set({
receipt_data : verificationData,
product_id : decodedReceipt["productId"],
orderId : latestReceipt["orderId"],
purchase_date_ms : parseInt(latestReceipt["startTimeMillis"]),
purchase_date : purchaseDate.toString(),
expires_date_ms : parseInt(latestReceipt["expiryTimeMillis"]),
expires_date : expiresDate.toString(),
created_at: Firestore.FieldValue.serverTimestamp(),
});
console.log('firestore set document, SUCCESS.');
return { result: SUCCESS };
} else {
console.log('Last receipt is expired, maybe stopped subscription.');
return { result: EXPIRED };
}
});
// DONE
console.log("DONE verifySubscriptionAndroid.");
return null;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment