Advertisement
Guest User

Untitled

a guest
Sep 15th, 2019
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.29 KB | None | 0 0
  1. import iap from 'in-app-purchase';
  2. import { Account } from 'model';
  3. import { constants } from '../util';
  4.  
  5. class AccountController {
  6.  
  7. async validateReceipt(user, receipt) {
  8. let account_id = user._id;
  9. iap.config({
  10. /* Configurations for Apple */
  11. appleExcludeOldTransactions: true, // if you want to exclude old transaction, set this to true. Default is false
  12. applePassword: constants.APPLE_SECRET, // this comes from iTunes Connect (You need this to valiate subscriptions)
  13.  
  14. test: false, // For Apple and Googl Play to force Sandbox validation only
  15. verbose: true // Output debug logs to stdout stream
  16. });
  17.  
  18. let validatedData;
  19. try {
  20. await iap.setup();
  21. validatedData = await iap.validate(receipt);
  22. } catch (error) {
  23. throw new Error('Validate receipt failed');
  24. }
  25.  
  26. if (!validatedData) {
  27. throw new Error('Validate receipt failed');
  28. }
  29. if (!iap.isValidated(validatedData)) {
  30. throw new Error('Receipt is not valid');
  31. }
  32. var options = {
  33. ignoreCanceled: true, // Apple ONLY (for now...): purchaseData will NOT contain cancceled items
  34. ignoreExpired: true // purchaseData will NOT contain exipired subscription items
  35. };
  36. // validatedData contains sandbox: true/false for Apple and Amazon
  37. var purchaseData = iap.getPurchaseData(validatedData, options);
  38. console.log(purchaseData);
  39. let { productId, expirationDate, transactionId } = purchaseData[0];
  40. if (!productId || !expirationDate || !transactionId) {
  41. throw new Error('Validate receipt failed. Response data is not valid');
  42. }
  43. if (productId != constants.APPLE_PRODUCT_ID) {
  44. throw new Error('Product id is not match');
  45. }
  46. if (expirationDate < Date.now()) {
  47. throw new Error('Expired transaction');
  48.  
  49. }
  50. //update account to premium
  51. let account = await Account.findOne({ _id: account_id, deleted: false });
  52. account.expiration_date = expirationDate;
  53. account.transaction_id = transactionId;
  54. account.premium = true;
  55. await account.save();
  56. return true;
  57. }
  58. }
  59. export default new AccountController();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement