habitica/website/server/libs/payments/apple.js

299 lines
9.7 KiB
JavaScript
Raw Permalink Normal View History

2019-10-08 14:57:10 +00:00
import moment from 'moment';
2018-04-08 14:27:03 +00:00
import shared from '../../../common';
import iap from '../inAppPurchases';
import payments from './payments';
import { validateGiftMessage } from './gems';
import {
NotAuthorized,
BadRequest,
2018-04-08 14:27:03 +00:00
} from '../errors';
import { model as IapPurchaseReceipt } from '../../models/iapPurchaseReceipt';
2019-10-08 14:57:10 +00:00
import { model as User } from '../../models/user';
2019-10-08 14:57:10 +00:00
const api = {};
api.constants = {
PAYMENT_METHOD_APPLE: 'Apple',
PAYMENT_METHOD_GIFT: 'Apple (Gift)',
RESPONSE_INVALID_RECEIPT: 'INVALID_RECEIPT',
RESPONSE_ALREADY_USED: 'RECEIPT_ALREADY_USED',
RESPONSE_INVALID_ITEM: 'INVALID_ITEM_PURCHASED',
RESPONSE_STILL_VALID: 'SUBSCRIPTION_STILL_VALID',
RESPONSE_NO_ITEM_PURCHASED: 'NO_ITEM_PURCHASED',
};
api.verifyPurchase = async function verifyPurchase (options) {
2019-10-08 14:57:10 +00:00
const {
gift, user, receipt, headers,
} = options;
if (gift) {
Stripe: upgrade module and API, switch to Checkout (#12785) * upgrade stripe module * switch stripe api to latest version * fix api version in tests * start upgrading client and server * client: switch to redirect * implement checkout session creation for gems, start implementing webhooks * stripe: start refactoring one time payments * working gems and gift payments * start adding support for subscriptions * stripe: migrate subscriptions and fix cancelling sub * allow upgrading group plans * remove console.log statements * group plans: upgrade from static page / create new one * fix #11885, correct group plan modal title * silence more stripe webhooks * fix group plans redirects * implement editing payment method * start cleaning up code * fix(stripe): update in-code docs, fix eslint issues * subscriptions tests * remove and skip old tests * skip integration tests * fix client build * stripe webhooks: throw error if request fails * subscriptions: correctly pass groupId * remove console.log * stripe: add unit tests for one time payments * wip: stripe checkout tests * stripe createCheckoutSession unit tests * stripe createCheckoutSession unit tests * stripe createCheckoutSession unit tests (editing card) * fix existing webhooks tests * add new webhooks tests * add more webhooks tests * fix lint * stripe integration tests * better error handling when retrieving customer from stripe * client: remove unused strings and improve error handling * payments: limit gift message length (server) * payments: limit gift message length (client) * fix redirects when payment is cancelled * add back "subUpdateCard" string * fix redirects when editing a sub card, use proper names for products, check subs when gifting
2020-12-14 14:59:17 +00:00
validateGiftMessage(gift, user);
gift.member = await User.findById(gift.uuid).exec();
}
Fall Festival Gem Promo (#138) * content: add gems blocks * gemsBlocks: include ios and android identifiers * wip: promo code * split common constants into multiple files * add second promo part * geCurrentEvent, refactor promo * fix lint * fix exports, use world state api * start adding world state tests * remove console.log * use gems block for purchases * remove comments * fix most unit tests * restore comment * fix lint * prevent apple/google gift tests from breaking other tests when stub is not reset * fix unit tests, clarify tests names * iap: use gift object when gifting gems * allow gift object with less data * fix iap tests, remove findById stubs * iap: require less data from the mobile apps * apply discounts * add missing worldState file * fix lint * add test event * start removing 20 gems option for web * start adding support for all gems packages on web * fix unit tests for apple, stripe and google * amazon: support all gems blocks * paypal: support all gems blocks * fix payments unit tests, add tests for getGemsBlock * web: add gems plans with discounts, update stripe * fix amazon and paypal clients, payments success modals * amazon pay: disabled state * update icons, start abstracting payments buttons * begin redesign * redesign gems modal * fix buttons * fix hover color for gems modal close icon * add key to world state current event * extend test event length * implement gems modals designs * early test fall2020 * fix header banner position * add missing files * use iso 8601 for dates, minor ui fixes * fix time zones * events: fix ISO8601 format * fix css indentation * start abstracting banners * refactor payments buttons * test spooky, fix group plans box * implement gems promo banners, refactor banners, fixes * fix lint * fix dates * remove unused i18n strings * fix stripe integration test * fix world state integration tests * the current active event * add missing unit tests * add storybook story for payments buttons component * fix typo * fix(stripe): correct label when gifting subscriptions
2020-09-21 14:22:13 +00:00
const receiver = gift ? gift.member : user;
const receiverCanGetGems = await receiver.canGetGems();
if (!receiverCanGetGems) throw new NotAuthorized(shared.i18n.t('groupPolicyCannotGetGems', user.preferences.language));
await iap.setup();
2019-10-08 14:57:10 +00:00
const appleRes = await iap.validate(iap.APPLE, receipt);
const isValidated = iap.isValidated(appleRes);
if (!isValidated) throw new NotAuthorized(api.constants.RESPONSE_INVALID_RECEIPT);
const purchaseDataList = iap.getPurchaseData(appleRes);
if (purchaseDataList.length === 0) {
throw new NotAuthorized(api.constants.RESPONSE_NO_ITEM_PURCHASED);
}
// Purchasing one item at a time (processing of await(s) below is sequential not parallel)
for (const purchaseData of purchaseDataList) {
2019-10-08 14:57:10 +00:00
const token = purchaseData.transactionId;
const existingReceipt = await IapPurchaseReceipt.findOne({ // eslint-disable-line no-await-in-loop, max-len
_id: token,
}).exec();
if (!existingReceipt) {
await IapPurchaseReceipt.create({ // eslint-disable-line no-await-in-loop
_id: token,
consumed: true,
// This should always be the buying user even for a gift.
userId: user._id,
});
await payments.buySkuItem({ // eslint-disable-line no-await-in-loop
user,
gift,
paymentMethod: api.constants.PAYMENT_METHOD_APPLE,
sku: purchaseData.productId,
headers,
});
}
}
return appleRes;
};
2022-11-03 16:48:36 +00:00
api.subscribe = async function subscribe (user, receipt, headers, nextPaymentProcessing) {
await iap.setup();
2019-10-08 14:57:10 +00:00
const appleRes = await iap.validate(iap.APPLE, receipt);
const isValidated = iap.isValidated(appleRes);
if (!isValidated) throw new NotAuthorized(api.constants.RESPONSE_INVALID_RECEIPT);
2019-10-08 14:57:10 +00:00
const purchaseDataList = iap.getPurchaseData(appleRes);
if (purchaseDataList.length === 0) {
throw new NotAuthorized(api.constants.RESPONSE_NO_ITEM_PURCHASED);
}
2022-11-08 11:19:17 +00:00
let purchase;
2022-11-03 16:48:36 +00:00
let newestDate;
for (const purchaseData of purchaseDataList) {
2022-11-03 16:48:36 +00:00
const datePurchased = new Date(Number(purchaseData.purchaseDate));
2019-10-08 14:57:10 +00:00
const dateTerminated = new Date(Number(purchaseData.expirationDate));
2022-11-03 16:48:36 +00:00
if ((!newestDate || datePurchased > newestDate) && dateTerminated > new Date()) {
2022-11-08 11:19:17 +00:00
purchase = purchaseData;
newestDate = datePurchased;
}
}
2022-11-03 16:48:36 +00:00
let subCode;
2022-11-08 11:19:17 +00:00
switch (purchase.productId) { // eslint-disable-line default-case
2022-11-03 16:48:36 +00:00
case 'subscription1month':
subCode = 'basic_earned';
break;
case 'com.habitrpg.ios.habitica.subscription.3month':
subCode = 'basic_3mo';
break;
case 'com.habitrpg.ios.habitica.subscription.6month':
subCode = 'basic_6mo';
break;
case 'com.habitrpg.ios.habitica.subscription.12month':
subCode = 'basic_12mo';
break;
}
const sub = subCode ? shared.content.subscriptionBlocks[subCode] : false;
2022-11-08 11:19:17 +00:00
if (purchase.originalTransactionId) {
let existingSub;
if (user && user.isSubscribed()) {
2022-11-08 11:19:17 +00:00
if (user.purchased.plan.customerId !== purchase.originalTransactionId) {
throw new NotAuthorized(this.constants.RESPONSE_ALREADY_USED);
}
existingSub = shared.content.subscriptionBlocks[user.purchased.plan.planId];
if (existingSub === sub) {
throw new NotAuthorized(this.constants.RESPONSE_ALREADY_USED);
}
2022-10-21 14:57:12 +00:00
}
2022-11-11 12:54:17 +00:00
const existingUsers = await User.find({
$or: [
{ 'purchased.plan.customerId': purchase.originalTransactionId },
{ 'purchased.plan.customerId': purchase.transactionId },
2023-02-27 12:30:44 +00:00
],
}).exec();
2022-11-11 12:54:17 +00:00
if (existingUsers.length > 0) {
if (purchase.originalTransactionId === purchase.transactionId) {
throw new NotAuthorized(this.constants.RESPONSE_ALREADY_USED);
}
2022-11-11 12:58:45 +00:00
for (const existingUser of existingUsers) {
2023-02-28 15:17:52 +00:00
if (existingUser._id !== user._id && !existingUser.purchased.plan.dateTerminated) {
2022-11-11 12:54:17 +00:00
throw new NotAuthorized(this.constants.RESPONSE_ALREADY_USED);
}
}
2022-10-21 14:57:12 +00:00
}
nextPaymentProcessing = nextPaymentProcessing || moment.utc().add({ days: 2 }); // eslint-disable-line max-len, no-param-reassign
2022-11-08 11:19:17 +00:00
const terminationDate = moment(Number(purchase.expirationDate));
if (nextPaymentProcessing > terminationDate) {
// For test subscriptions that have a significantly shorter expiration period, this is better
nextPaymentProcessing = terminationDate; // eslint-disable-line no-param-reassign
}
const data = {
user,
2022-11-08 11:19:17 +00:00
customerId: purchase.originalTransactionId,
paymentMethod: this.constants.PAYMENT_METHOD_APPLE,
sub,
headers,
nextPaymentProcessing,
additionalData: receipt,
};
if (existingSub) {
data.updatedFrom = existingSub;
data.updatedFrom.logic = 'refundAndRepay';
}
await payments.createSubscription(data);
} else {
throw new NotAuthorized(api.constants.RESPONSE_INVALID_RECEIPT);
}
};
api.noRenewSubscribe = async function noRenewSubscribe (options) {
2019-10-08 14:57:10 +00:00
const {
sku, gift, user, receipt, headers,
} = options;
if (!sku) throw new BadRequest(shared.i18n.t('missingSubscriptionCode'));
let subCode;
switch (sku) { // eslint-disable-line default-case
case 'com.habitrpg.ios.habitica.norenew_subscription.1month':
subCode = 'basic_earned';
break;
case 'com.habitrpg.ios.habitica.norenew_subscription.3month':
subCode = 'basic_3mo';
break;
case 'com.habitrpg.ios.habitica.norenew_subscription.6month':
subCode = 'basic_6mo';
break;
case 'com.habitrpg.ios.habitica.norenew_subscription.12month':
subCode = 'basic_12mo';
break;
}
const sub = subCode ? shared.content.subscriptionBlocks[subCode] : false;
if (!sub) throw new NotAuthorized(this.constants.RESPONSE_INVALID_ITEM);
await iap.setup();
2019-10-08 14:57:10 +00:00
const appleRes = await iap.validate(iap.APPLE, receipt);
const isValidated = iap.isValidated(appleRes);
if (!isValidated) throw new NotAuthorized(api.constants.RESPONSE_INVALID_RECEIPT);
2019-10-08 14:57:10 +00:00
const purchaseDataList = iap.getPurchaseData(appleRes);
if (purchaseDataList.length === 0) {
throw new NotAuthorized(api.constants.RESPONSE_NO_ITEM_PURCHASED);
}
let correctReceipt = false;
/* eslint-disable no-await-in-loop */
for (const purchaseData of purchaseDataList) {
if (purchaseData.productId === sku) {
const { transactionId } = purchaseData;
const existingReceipt = await IapPurchaseReceipt.findOne({
_id: transactionId,
}).exec();
if (existingReceipt) throw new NotAuthorized(this.constants.RESPONSE_ALREADY_USED);
await IapPurchaseReceipt.create({
_id: transactionId,
consumed: true,
// This should always be the buying user even for a gift.
userId: user._id,
});
const data = {
user,
paymentMethod: this.constants.PAYMENT_METHOD_APPLE,
headers,
sub,
autoRenews: false,
};
if (gift) {
Stripe: upgrade module and API, switch to Checkout (#12785) * upgrade stripe module * switch stripe api to latest version * fix api version in tests * start upgrading client and server * client: switch to redirect * implement checkout session creation for gems, start implementing webhooks * stripe: start refactoring one time payments * working gems and gift payments * start adding support for subscriptions * stripe: migrate subscriptions and fix cancelling sub * allow upgrading group plans * remove console.log statements * group plans: upgrade from static page / create new one * fix #11885, correct group plan modal title * silence more stripe webhooks * fix group plans redirects * implement editing payment method * start cleaning up code * fix(stripe): update in-code docs, fix eslint issues * subscriptions tests * remove and skip old tests * skip integration tests * fix client build * stripe webhooks: throw error if request fails * subscriptions: correctly pass groupId * remove console.log * stripe: add unit tests for one time payments * wip: stripe checkout tests * stripe createCheckoutSession unit tests * stripe createCheckoutSession unit tests * stripe createCheckoutSession unit tests (editing card) * fix existing webhooks tests * add new webhooks tests * add more webhooks tests * fix lint * stripe integration tests * better error handling when retrieving customer from stripe * client: remove unused strings and improve error handling * payments: limit gift message length (server) * payments: limit gift message length (client) * fix redirects when payment is cancelled * add back "subUpdateCard" string * fix redirects when editing a sub card, use proper names for products, check subs when gifting
2020-12-14 14:59:17 +00:00
validateGiftMessage(gift, user);
gift.member = await User.findById(gift.uuid).exec();
gift.subscription = sub;
data.gift = gift;
data.paymentMethod = this.constants.PAYMENT_METHOD_GIFT;
}
await payments.createSubscription(data);
correctReceipt = true;
break;
}
}
if (!correctReceipt) throw new NotAuthorized(api.constants.RESPONSE_INVALID_ITEM);
return appleRes;
};
/* eslint-enable no-await-in-loop */
api.cancelSubscribe = async function cancelSubscribe (user, headers) {
2019-10-08 14:57:10 +00:00
const { plan } = user.purchased;
if (plan.paymentMethod !== api.constants.PAYMENT_METHOD_APPLE) throw new NotAuthorized(shared.i18n.t('missingSubscription'));
await iap.setup();
try {
2019-10-08 14:57:10 +00:00
const appleRes = await iap.validate(iap.APPLE, plan.additionalData);
2019-10-08 14:57:10 +00:00
const isValidated = iap.isValidated(appleRes);
if (!isValidated) throw new NotAuthorized(this.constants.RESPONSE_INVALID_RECEIPT);
2019-10-08 14:57:10 +00:00
const purchases = iap.getPurchaseData(appleRes);
if (purchases.length === 0) throw new NotAuthorized(this.constants.RESPONSE_INVALID_RECEIPT);
let newestDate;
2022-11-11 12:58:45 +00:00
let newestPurchase;
for (const purchaseData of purchases) {
const datePurchased = new Date(Number(purchaseData.purchaseDate));
if (!newestDate || datePurchased > newestDate) {
newestDate = datePurchased;
2022-11-11 12:54:17 +00:00
newestPurchase = purchaseData;
}
}
2022-11-11 12:58:45 +00:00
if (!iap.isCanceled(newestPurchase) && !iap.isExpired(newestPurchase)) {
throw new NotAuthorized(this.constants.RESPONSE_STILL_VALID);
}
2022-11-11 12:54:17 +00:00
await payments.cancelSubscription({
user,
nextBill: new Date(Number(newestPurchase.expirationDate)),
paymentMethod: this.constants.PAYMENT_METHOD_APPLE,
headers,
});
} catch (err) {
// If we have an invalid receipt, cancel anyway
if (
!err || !err.validatedData || err.validatedData.is_retryable === true
|| err.validatedData.status !== 21010
) {
throw err;
}
}
};
export default api;