Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import iap from 'in-app-purchase';
- import { Account } from 'model';
- import { constants } from '../util';
- class AccountController {
- async validateReceipt(user, receipt) {
- let account_id = user._id;
- iap.config({
- /* Configurations for Apple */
- appleExcludeOldTransactions: true, // if you want to exclude old transaction, set this to true. Default is false
- applePassword: constants.APPLE_SECRET, // this comes from iTunes Connect (You need this to valiate subscriptions)
- test: false, // For Apple and Googl Play to force Sandbox validation only
- verbose: true // Output debug logs to stdout stream
- });
- let validatedData;
- try {
- await iap.setup();
- validatedData = await iap.validate(receipt);
- } catch (error) {
- throw new Error('Validate receipt failed');
- }
- if (!validatedData) {
- throw new Error('Validate receipt failed');
- }
- if (!iap.isValidated(validatedData)) {
- throw new Error('Receipt is not valid');
- }
- var options = {
- ignoreCanceled: true, // Apple ONLY (for now...): purchaseData will NOT contain cancceled items
- ignoreExpired: true // purchaseData will NOT contain exipired subscription items
- };
- // validatedData contains sandbox: true/false for Apple and Amazon
- var purchaseData = iap.getPurchaseData(validatedData, options);
- console.log(purchaseData);
- let { productId, expirationDate, transactionId } = purchaseData[0];
- if (!productId || !expirationDate || !transactionId) {
- throw new Error('Validate receipt failed. Response data is not valid');
- }
- if (productId != constants.APPLE_PRODUCT_ID) {
- throw new Error('Product id is not match');
- }
- if (expirationDate < Date.now()) {
- throw new Error('Expired transaction');
- }
- //update account to premium
- let account = await Account.findOne({ _id: account_id, deleted: false });
- account.expiration_date = expirationDate;
- account.transaction_id = transactionId;
- account.premium = true;
- await account.save();
- return true;
- }
- }
- export default new AccountController();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement