Skip to content

Instantly share code, notes, and snippets.

@d-sea
Last active October 11, 2023 08:24
Show Gist options
  • Save d-sea/08e0f8973b94008c0e93c828b1634dbc to your computer and use it in GitHub Desktop.
Save d-sea/08e0f8973b94008c0e93c828b1634dbc to your computer and use it in GitHub Desktop.
firebase functions verifyAndroid Android 購入を検証してFirestoreに保存する
exports.verifyAndroid = functions.https.onCall(async (data, context) => {
if (context.auth === null) {
return { result: NO_AUTH };
}
const uid = context.auth.uid;
const verificationData = data["data"];
const latestReceipt = await verifyReceiptAndroid(
verificationData,
context.auth
);
if (latestReceipt === null || latestReceipt === undefined) {
return { result: INVALID_RECEIPT };
}
// 同じorderIdが存在しないか確認し、購入情報が既に登録済みでないか確認する
const queryId = await admin.firestore().collectionGroup("receipts")
.where("orderId", "==", latestReceipt["orderId"])
.get();
if (!queryId.empty) {
return { result: ALREADY_EXIST };
}
// Firestoreに保存する
const decodedReceipt = JSON.parse(verificationData);
const purchaseDate = new Date(parseInt(latestReceipt["startTimeMillis"]));
const expiresDate = new Date(parseInt(latestReceipt["expiryTimeMillis"]));
const receiptRef = admin.firestore().collection('users').doc(uid).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(),
});
// 期限内であることを確認する
const now = Date.now();
const expireDate = Number(latestReceipt["expiryTimeMillis"]);
if (now < expireDate) {
return { result: SUCCESS };
} else {
return { result: EXPIRED };
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment