Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Try out upgrading Stripe #2693

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 10 additions & 10 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@
"simple-vdf": "^1.1.1",
"steam": "github:odota/node-steam-npm",
"steam-resources": "github:odota/node-steam-resources",
"stripe": "^9.12.0",
"stripe": "^14.9.0",
"uuid": "^3.3.3",
"ws": "^8.14.2"
},
Expand Down
26 changes: 12 additions & 14 deletions routes/keyManagement.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,12 @@ import uuid from 'uuid';
import bodyParser from 'body-parser';
import moment from 'moment';
import async from 'async';
import stripeLib from 'stripe';
import { Stripe } from 'stripe';
import db from '../store/db';
import redis from '../store/redis';
import config from '../config';
import { redisCount } from '../util/utility';
//@ts-ignore
const stripe = stripeLib(config.STRIPE_SECRET);

const stripe = new Stripe(config.STRIPE_SECRET);
const stripeAPIPlan = config.STRIPE_API_PLAN;
const keys = express.Router();
keys.use(bodyParser.json());
Expand All @@ -26,7 +25,7 @@ keys.use((req, res, next) => {
}
return next();
});
// @param rows - query result from api_keys table
// @param rows - query resut from api_keys table
function getActiveKey(rows: any[]) {
const notCanceled = rows.filter((row) => row.is_canceled != true);
return notCanceled.length > 0 ? notCanceled[0] : null;
Expand Down Expand Up @@ -75,14 +74,14 @@ keys
api_key,
};
stripe.customers
.retrieve(customer_id)
.then((customer: any) => {
const source = customer.sources.data[0];
.retrieve(customer_id, {expand: ['default_source']})
.then((customer) => {
const source = (customer as Stripe.Customer).default_source as Stripe.Card;
toReturn.credit_brand = source?.brand;
toReturn.credit_last4 = source?.last4;
return stripe.subscriptions.retrieve(subscription_id);
})
.then((sub: any) => {
.then((sub) => {
toReturn.current_period_end = sub.current_period_end;
})
.then(() => cb(null, toReturn))
Expand All @@ -94,7 +93,7 @@ keys
}
const customer_id = allKeyRecords[0].customer_id;
getOpenInvoices(customer_id).then((invoices) => {
const processed = invoices.map((i: any) => ({
const processed = invoices.map((i) => ({
id: i.id,
amountDue: i.amount_due,
paymentLink: i.hosted_invoice_url,
Expand Down Expand Up @@ -155,7 +154,7 @@ keys
}
const { api_key, subscription_id } = keyRecord;
// Immediately bill the customer for any unpaid usage
await stripe.subscriptions.del(subscription_id, { invoice_now: true });
await stripe.subscriptions.cancel(subscription_id, { invoice_now: true });
await db
.from('api_keys')
.where({
Expand Down Expand Up @@ -231,7 +230,7 @@ keys
source: token.id,
email: token.email,
metadata: {
account_id: req.user?.account_id,
account_id: req.user?.account_id ?? '',
},
});
customer_id = customer.id;
Expand All @@ -240,6 +239,7 @@ keys
return res.status(402).json(err);
}
}

const apiKey = uuid.v4();
const sub = await stripe.subscriptions.create({
customer: customer_id,
Expand Down Expand Up @@ -291,8 +291,6 @@ keys
} = req.body;
await stripe.customers.update(customer_id, {
email,
});
await stripe.subscriptions.update(subscription_id, {
source: id,
});
res.sendStatus(200);
Expand Down
19 changes: 15 additions & 4 deletions svc/apiadmin.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
// Runs background processes related to API keys and billing/usage
import async from 'async';
import moment from 'moment';
import stripeLib from 'stripe';
import { Stripe } from 'stripe';
import redis from '../store/redis';
import db from '../store/db';
import config from '../config';
import type { knex } from 'knex';
import { invokeInterval } from '../util/utility';

//@ts-ignore
const stripe = stripeLib(config.STRIPE_SECRET);
const stripe = new Stripe(config.STRIPE_SECRET);
function storeUsageCounts(cursor: string | number, cb: ErrorCb) {
redis.hscan('usage_count', cursor, (err, results) => {
if (err) {
Expand Down Expand Up @@ -89,7 +88,7 @@ async function updateStripeUsage(cb: ErrorCb) {
// From the docs:
// By default, returns a list of subscriptions that have not been canceled.
// In order to list canceled subscriptions, specify status=canceled. Use all for completeness.
status: 'all',
status: 'all' as Stripe.Subscription.Status,
};
let num = 0;
try {
Expand All @@ -108,6 +107,18 @@ async function updateStripeUsage(cb: ErrorCb) {
);
continue;
}
// Deactivate any keys belonging to an invalid card
const BANNED_CARDS: string[] = [];
const sourceId = sub.default_source;
if (sourceId) {
const source = await stripe.sources.retrieve(sourceId as string);
if (source.card?.fingerprint && BANNED_CARDS.includes(source.card?.fingerprint)) {
await db.raw(
`UPDATE api_keys SET is_canceled = true WHERE subscription_id = ?`,
[sub.id]
);
}
}
const startTime = moment
.unix(sub.current_period_end - 1)
.startOf('month');
Expand Down
5 changes: 2 additions & 3 deletions svc/syncSubs.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
// Syncs the list of subscribers from Stripe to the database
import db from '../store/db';
import config from '../config';
import stripeLib from 'stripe';
import { Stripe } from 'stripe';
import { invokeIntervalAsync } from '../util/utility';

//@ts-ignore
const stripe = stripeLib(config.STRIPE_SECRET);
const stripe = new Stripe(config.STRIPE_SECRET);
async function doSyncSubs() {
// Get list of current subscribers
const result = [];
Expand Down
9 changes: 4 additions & 5 deletions svc/web.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import passport from 'passport';
import passportSteam from 'passport-steam';
import cors from 'cors';
import bodyParser from 'body-parser';
import stripeLib from 'stripe';
import { Stripe } from 'stripe';
import { Redis } from 'ioredis';
import { WebSocketServer, WebSocket } from 'ws';
import keys from '../routes/keyManagement';
Expand All @@ -28,8 +28,7 @@ import {

const admins = config.ADMIN_ACCOUNT_IDS.split(',').map((e) => Number(e));
const SteamStrategy = passportSteam.Strategy;
//@ts-ignore
const stripe = stripeLib(config.STRIPE_SECRET);
const stripe = new Stripe(config.STRIPE_SECRET);
export const app = express();
const apiKey = config.STEAM_API_KEY.split(',')[0];
const host = config.ROOT_URL;
Expand Down Expand Up @@ -317,8 +316,8 @@ app.route('/subscribeSuccess').get(async (req, res) => {
return res.status(400).json({ error: 'no account ID' });
}
// look up the checkout session id: https://stripe.com/docs/payments/checkout/custom-success-page
const session = await stripe.checkout.sessions.retrieve(req.query.session_id);
const customer = await stripe.customers.retrieve(session.customer);
const session = await stripe.checkout.sessions.retrieve(req.query.session_id as string);
const customer = await stripe.customers.retrieve(session.customer as string);
const accountId = req.user.account_id;
// associate the customer id with the steam account ID (req.user.account_id)
await db.raw(
Expand Down
13 changes: 6 additions & 7 deletions test/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import type { Express } from 'express';
import nock from 'nock';
import assert from 'assert';
import supertest from 'supertest';
import stripeLib from 'stripe';
import { Stripe } from 'stripe';
import pg from 'pg';
import { readFileSync } from 'fs';
import util from 'util';
Expand Down Expand Up @@ -551,16 +551,15 @@ describe(c.blue('[TEST] api management'), () => {
.delete('/keys?loggedin=1')
.then(async (res) => {
assert.equal(res.statusCode, 200);
//@ts-ignore
const stripe = stripeLib(STRIPE_SECRET);
const stripe = new Stripe(STRIPE_SECRET);

await stripe.invoiceItems.create({
const invoice = await stripe.invoices.create({
customer: this.previousCustomer,
price: 'price_1Lm1siCHN72mG1oKkk3Jh1JT', // test $123 one time
});

const invoice = await stripe.invoices.create({
await stripe.invoiceItems.create({
customer: this.previousCustomer,
price: 'price_1Lm1siCHN72mG1oKkk3Jh1JT', // test $123 one time
invoice: invoice.id,
});

await stripe.invoices.finalizeInvoice(invoice.id);
Expand Down
Loading