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

Appex 406 #130

Merged
merged 2 commits into from
Sep 27, 2022
Merged
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
1 change: 0 additions & 1 deletion .env-sample
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@ CHECKOUT_APP_ID={Application ID}
CHECKOUT_CLIENT={Partner Client ID}
CHECKOUT_TOKEN={Partner Access Token}
CHECKOUT_PARTNER={Partner Account UUID}
CHECKOUT_MERCHANT={Merchant Account UUID}
CHECKOUT_URL=https://${API_URL}/accounts/${CHECKOUT_PARTNER}/graphql

# Dev Enironment Vars
Expand Down
3 changes: 1 addition & 2 deletions lib/checkout.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
const checkoutAppId = process.env.CHECKOUT_APP_ID;
const appId = process.env.CURRENT_APP_ID ?? checkoutAppId;
const merchantUuid = process.env.CHECKOUT_MERCHANT;
const environment = process.env.ENVIRONMENT;
const isProd = environment === 'bigcommerce.com';
const hostName = isProd ? environment : `-${environment}`;
Expand Down Expand Up @@ -99,7 +98,7 @@ const checkoutGraphQuery = `
}
`;

export function getCheckoutBody(productId: string, storeHash: string) {
export function getCheckoutBody(productId: string, storeHash: string, merchantUuid: string) {
return {
query: checkoutGraphQuery,
variables: {
Expand Down
61 changes: 59 additions & 2 deletions lib/dbs/mysql.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import * as mysql from 'mysql';
import { promisify } from 'util';
import { SessionProps, StoreData } from '../../types';
import { trialDays } from '../checkout';

const MYSQL_CONFIG = {
host: process.env.MYSQL_HOST,
Expand All @@ -26,12 +27,17 @@ export async function setUser({ user }: SessionProps) {
}

export async function setStore(session: SessionProps) {
const { access_token: accessToken, context, scope } = session;
const {
access_token: accessToken,
context,
scope,
user: { id },
} = session;
// Only set on app install or update
if (!accessToken || !scope) return null;

const storeHash = context?.split('/')[1] || '';
const storeData: StoreData = { accessToken, scope, storeHash };
const storeData: StoreData = { accessToken, adminId: id, scope, storeHash };

await query('REPLACE INTO stores SET ?', storeData);
}
Expand Down Expand Up @@ -91,3 +97,54 @@ export async function getStoreToken(storeHash: string) {
export async function deleteStore({ store_hash: storeHash }: SessionProps) {
await query('DELETE FROM stores WHERE storeHash = ?', storeHash);
}

// CHECKOUT Functions
export async function setStorePlan(session: SessionProps) {
const { access_token: accessToken, context, plan, sub } = session;
// Only set on app install or subscription verification (load)
if ((!accessToken && !plan?.pid) || (plan && !plan.isPaidApp)) return null;

const contextString = context ?? sub;
const storeHash = contextString?.split('/')[1] || '';
const defaultEnd = new Date(Date.now() + (trialDays * 24 * 60 * 60 * 1000));
const data = {
pid: '',
isPaidApp: false,
showPaidWelcome: false,
storeHash,
trialEndDate: defaultEnd,
...plan,
};

await query('REPLACE INTO plan SET ?', data);
}

export async function getStorePlan(storeHash: string) {
if (!storeHash) return null;

const results = await query('SELECT * FROM plan WHERE storeHash = ? LIMIT 1', storeHash);

return results.length ? results[0] : null;
}

export async function setStoreWelcome(storeHash: string, show: boolean) {
if (!storeHash) return null;

const values = [show, storeHash];

await query('UPDATE plan SET showPaidWelcome = ? WHERE storeHash = ?', values);
}

export async function setCheckoutId(pid: string, checkoutId: string) {
if (!pid || !checkoutId) return null;

await query('REPLACE INTO checkout SET ?', { pid, checkoutId });
}

export async function getCheckoutId(pid: string) {
if (!pid) return null;

const results = await query('SELECT checkoutId FROM checkout WHERE pid = ?', pid);

return results.length ? results[0].checkoutId : null;
}
14 changes: 9 additions & 5 deletions pages/api/checkout/[pid].ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
import { NextApiRequest, NextApiResponse } from 'next';
import { getSession, setCheckout } from '../../../lib/auth';
import { bigcommerceClient, getSession, setCheckout } from '../../../lib/auth';
import { getCheckoutBody } from '../../../lib/checkout';

export default async function checkout(req: NextApiRequest, res: NextApiResponse) {
const { query: { pid } } = req;

try {
const { storeHash } = await getSession(req);
const checkoutBody = getCheckoutBody(String(pid), storeHash);
const { accessToken, storeHash } = await getSession(req);
const bigcommerce = bigcommerceClient(accessToken, storeHash, 'v2');
const { account_uuid: merchantUuid } = await bigcommerce.get(`/store`);
bookernath marked this conversation as resolved.
Show resolved Hide resolved

const checkoutBody = getCheckoutBody(String(pid), storeHash, merchantUuid);
const response = await fetch(process.env.CHECKOUT_URL, {
method: 'POST',
headers: {
Expand All @@ -24,10 +27,11 @@ export default async function checkout(req: NextApiRequest, res: NextApiResponse
throw new Error(errors[0]?.message);
}

const checkoutId = data?.checkout?.createCheckout?.checkout?.id.split('/')[3] ?? '';
const checkout = data?.checkout?.createCheckout?.checkout || {};
const checkoutId = checkout.id?.split('/')[3] ?? '';
if (checkoutId) setCheckout(String(pid), checkoutId);

res.status(200).json(data?.checkout?.createCheckout?.checkout);
res.status(200).json(checkout);
} catch (error) {
const { message, response } = error;
res.status(response?.status || 500).json({ message });
Expand Down
24 changes: 23 additions & 1 deletion scripts/db.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ const storesCreate = query('CREATE TABLE `stores` (\n' +
' `id` int(11) unsigned NOT NULL AUTO_INCREMENT,\n' +
' `storeHash` varchar(10) NOT NULL,\n' +
' `accessToken` text,\n' +
' `adminId` int(11) NOT NULL,\n' +
' `scope` text,\n' +
' PRIMARY KEY (`id`),\n' +
' UNIQUE KEY `storeHash` (`storeHash`)\n' +
Expand All @@ -42,6 +43,27 @@ const storeUsersCreate = query('CREATE TABLE `storeUsers` (\n' +
') ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;\n'
);

Promise.all([usersCreate, storesCreate]).then(() => {
const planCreate = query('CREATE TABLE `plan` (\n' +
' `id` int(11) unsigned NOT NULL AUTO_INCREMENT,\n' +
' `storeHash` varchar(10) NOT NULL,\n' +
' `pid` varchar(20) NOT NULL,\n' +
' `isPaidApp` boolean,\n' +
' `showPaidWelcome` boolean,\n' +
' `trialEndDate` datetime,\n' +
' PRIMARY KEY (`id`),\n' +
' UNIQUE KEY `storeHash` (`storeHash`)\n' +
') ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;'
);

const checkoutCreate = query('CREATE TABLE `checkout` (\n' +
' `id` int(11) unsigned NOT NULL AUTO_INCREMENT,\n' +
' `pid` varchar(20) NOT NULL,\n' +
' `checkoutId` varchar(40) NOT NULL,\n' +
' PRIMARY KEY (`id`),\n' +
' UNIQUE KEY `pid` (`pid`)\n' +
') ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;\n'
);

Promise.all([usersCreate, storesCreate, storeUsersCreate, planCreate, checkoutCreate]).then(() => {
connection.end();
});
1 change: 1 addition & 0 deletions types/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { SessionProps } from './index';

export interface StoreData {
accessToken?: string;
adminId: number;
scope?: string;
storeHash: string;
}
Expand Down