invoices work

This commit is contained in:
Paul Miller
2022-03-18 19:40:50 -05:00
parent 147547241a
commit 4b566e1c59
15 changed files with 1812 additions and 239 deletions

6
config/index.ts Normal file
View File

@@ -0,0 +1,6 @@
export const CURRENCY = "usd";
// Set your amount limits: Use float for decimal currencies and
// Integer for zero-decimal currencies: https://stripe.com/docs/currencies#zero-decimal.
export const MIN_AMOUNT = 10.0;
export const MAX_AMOUNT = 5000.0;
export const AMOUNT_STEP = 5.0;

1514
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -9,15 +9,24 @@
"lint": "next lint"
},
"dependencies": {
"@stripe/react-stripe-js": "^1.7.0",
"@stripe/stripe-js": "^1.25.0",
"micro": "^9.3.4",
"micro-cors": "^0.1.1",
"next": "12.1.0",
"react": "17.0.2",
"react-dom": "17.0.2"
"react-dom": "17.0.2",
"stripe": "^8.210.0",
"swr": "^1.2.2"
},
"devDependencies": {
"@types/node": "17.0.21",
"@types/react": "17.0.40",
"autoprefixer": "^10.4.4",
"eslint": "8.11.0",
"eslint-config-next": "12.1.0",
"postcss": "^8.4.12",
"tailwindcss": "^3.0.23",
"typescript": "4.6.2"
}
}

35
pages/api/btcpay.ts Normal file
View File

@@ -0,0 +1,35 @@
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type { NextApiRequest, NextApiResponse } from "next";
import { CURRENCY, MIN_AMOUNT, MAX_AMOUNT } from "../../config";
import { fetchPostJSONAuthed } from "../../utils/api-helpers";
import { formatAmountForStripe } from "../../utils/stripe-helpers";
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
if (req.method === "POST") {
const { amount }: { amount: number } = req.body;
try {
// Validate the amount that was passed from the client.
if (!(amount >= MIN_AMOUNT && amount <= MAX_AMOUNT)) {
throw new Error("Invalid amount.");
}
let data = await fetchPostJSONAuthed(
`${process.env
.BTCPAY_URL!}stores/9PMMpizLnpWtBeHV5Y9iKLj14Ei5iuVSWxYeSSntnsDU/invoices`,
`token ${process.env.BTCPAY_API_KEY}`,
// TODO validate that we aren't fucking with the amount with floating point stuff
{ amount, currency: CURRENCY }
);
res.status(200).json(data);
} catch (err) {
res.status(500).json({ statusCode: 500, message: err.message });
}
} else {
res.setHeader("Allow", "POST");
res.status(405).end("Method Not Allowed");
}
}

View File

@@ -1,13 +0,0 @@
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type { NextApiRequest, NextApiResponse } from 'next'
type Data = {
name: string
}
export default function handler(
req: NextApiRequest,
res: NextApiResponse<Data>
) {
res.status(200).json({ name: 'John Doe' })
}

41
pages/api/stripe.ts Normal file
View File

@@ -0,0 +1,41 @@
import { NextApiRequest, NextApiResponse } from "next";
import { CURRENCY, MIN_AMOUNT, MAX_AMOUNT } from "../../config";
import { formatAmountForStripe } from "../../utils/stripe-helpers";
import Stripe from "stripe";
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
// https://github.com/stripe/stripe-node#configuration
apiVersion: "2020-08-27",
});
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
if (req.method === "POST") {
const { amount }: { amount: number } = req.body;
try {
// Validate the amount that was passed from the client.
if (!(amount >= MIN_AMOUNT && amount <= MAX_AMOUNT)) {
throw new Error("Invalid amount.");
}
// Create PaymentIntent from body params.
const params: Stripe.PaymentIntentCreateParams = {
payment_method_types: ["card"],
amount: formatAmountForStripe(amount, CURRENCY),
currency: CURRENCY,
description: process.env.STRIPE_PAYMENT_DESCRIPTION ?? "",
};
const payment_intent: Stripe.PaymentIntent =
await stripe.paymentIntents.create(params);
res.status(200).json(payment_intent);
} catch (err) {
res.status(500).json({ statusCode: 500, message: err.message });
}
} else {
res.setHeader("Allow", "POST");
res.status(405).end("Method Not Allowed");
}
}

View File

@@ -0,0 +1,49 @@
import { NextApiRequest, NextApiResponse } from "next";
import { CURRENCY, MIN_AMOUNT, MAX_AMOUNT } from "../../config";
import { formatAmountForStripe } from "../../utils/stripe-helpers";
import Stripe from "stripe";
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
// https://github.com/stripe/stripe-node#configuration
apiVersion: "2020-08-27",
});
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
if (req.method === "POST") {
const amount: number = req.body.amount;
try {
// Validate the amount that was passed from the client.
if (!(amount >= MIN_AMOUNT && amount <= MAX_AMOUNT)) {
throw new Error("Invalid amount.");
}
// Create Checkout Sessions from body params.
const params: Stripe.Checkout.SessionCreateParams = {
submit_type: "donate",
payment_method_types: ["card"],
line_items: [
{
name: "Custom amount donation",
amount: formatAmountForStripe(amount, CURRENCY),
currency: CURRENCY,
quantity: 1,
},
],
success_url: `${req.headers.origin}/?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${req.headers.origin}/`,
};
const checkoutSession: Stripe.Checkout.Session =
await stripe.checkout.sessions.create(params);
res.status(200).json(checkoutSession);
} catch (err) {
res.status(500).json({ statusCode: 500, message: err.message });
}
} else {
res.setHeader("Allow", "POST");
res.status(405).end("Method Not Allowed");
}
}

29
pages/checkout.tsx Normal file
View File

@@ -0,0 +1,29 @@
import type { NextPage } from "next";
import Head from "next/head";
import Image from "next/image";
const Checkout: NextPage = () => {
async function handleClick() {
console.log("yo");
}
return (
<div>
<Head>
<title>Create Next App</title>
<meta name="description" content="Generated by create next app" />
<link rel="icon" href="/favicon.ico" />
</Head>
<main>
<h1>yooo</h1>
<button onClick={handleClick}>Heyo</button>
<p>testing 123</p>
</main>
<footer>footer</footer>
</div>
);
};
export default Checkout;

View File

@@ -1,72 +1,57 @@
import type { NextPage } from 'next'
import Head from 'next/head'
import Image from 'next/image'
import styles from '../styles/Home.module.css'
import type { NextPage } from "next";
import Head from "next/head";
import Image from "next/image";
import { useState } from "react";
import useSWR from "swr";
import { fetchPostJSON } from "../utils/api-helpers";
const Home: NextPage = () => {
const [shouldFetch, setShouldFetch] = useState(false);
const [data, setData] = useState(false);
const [stripeUrl, setStripeUrl] = useState("");
const [btcpayUrl, setBtcPayUrl] = useState("");
async function handleClick() {
// setShouldFetch(true);
// const { data, error } = useSWR(shouldFetch ? "/api/invoice" : null, fetchGetJSON);
// const res = await fetchGetJSON("/api/invoice");
const amount = 100.0;
try {
const stripe = await fetchPostJSON("/api/stripe_checkout", {
amount,
});
const btcpay = await fetchPostJSON("/api/btcpay", {
amount,
});
console.debug(stripe);
setStripeUrl(stripe.url);
setBtcPayUrl(btcpay.checkoutLink);
console.debug(btcpay);
} catch (e) {
console.error(e);
}
}
return (
<div className={styles.container}>
<div>
<Head>
<title>Create Next App</title>
<meta name="description" content="Generated by create next app" />
<link rel="icon" href="/favicon.ico" />
</Head>
<main className={styles.main}>
<h1 className={styles.title}>
Welcome to <a href="https://nextjs.org">Next.js!</a>
</h1>
<p className={styles.description}>
Get started by editing{' '}
<code className={styles.code}>pages/index.tsx</code>
</p>
<div className={styles.grid}>
<a href="https://nextjs.org/docs" className={styles.card}>
<h2>Documentation &rarr;</h2>
<p>Find in-depth information about Next.js features and API.</p>
</a>
<a href="https://nextjs.org/learn" className={styles.card}>
<h2>Learn &rarr;</h2>
<p>Learn about Next.js in an interactive course with quizzes!</p>
</a>
<a
href="https://github.com/vercel/next.js/tree/canary/examples"
className={styles.card}
>
<h2>Examples &rarr;</h2>
<p>Discover and deploy boilerplate example Next.js projects.</p>
</a>
<a
href="https://vercel.com/new?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
className={styles.card}
>
<h2>Deploy &rarr;</h2>
<p>
Instantly deploy your Next.js site to a public URL with Vercel.
</p>
</a>
</div>
<main>
<h1>yooo</h1>
<button onClick={handleClick}>Heyo</button>
{data && <pre>{JSON.stringify(data, null, 2)}</pre>}
{stripeUrl && <a href={stripeUrl}>Stripe Checkout</a>}
{btcpayUrl && <a href={btcpayUrl}>BTCPay Checkout</a>}
<p>testing 123</p>
</main>
<footer className={styles.footer}>
<a
href="https://vercel.com?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
Powered by{' '}
<span className={styles.logo}>
<Image src="/vercel.svg" alt="Vercel Logo" width={72} height={16} />
</span>
</a>
</footer>
<footer>footer</footer>
</div>
)
}
);
};
export default Home
export default Home;

6
postcss.config.js Normal file
View File

@@ -0,0 +1,6 @@
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}

View File

@@ -1,116 +0,0 @@
.container {
padding: 0 2rem;
}
.main {
min-height: 100vh;
padding: 4rem 0;
flex: 1;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.footer {
display: flex;
flex: 1;
padding: 2rem 0;
border-top: 1px solid #eaeaea;
justify-content: center;
align-items: center;
}
.footer a {
display: flex;
justify-content: center;
align-items: center;
flex-grow: 1;
}
.title a {
color: #0070f3;
text-decoration: none;
}
.title a:hover,
.title a:focus,
.title a:active {
text-decoration: underline;
}
.title {
margin: 0;
line-height: 1.15;
font-size: 4rem;
}
.title,
.description {
text-align: center;
}
.description {
margin: 4rem 0;
line-height: 1.5;
font-size: 1.5rem;
}
.code {
background: #fafafa;
border-radius: 5px;
padding: 0.75rem;
font-size: 1.1rem;
font-family: Menlo, Monaco, Lucida Console, Liberation Mono, DejaVu Sans Mono,
Bitstream Vera Sans Mono, Courier New, monospace;
}
.grid {
display: flex;
align-items: center;
justify-content: center;
flex-wrap: wrap;
max-width: 800px;
}
.card {
margin: 1rem;
padding: 1.5rem;
text-align: left;
color: inherit;
text-decoration: none;
border: 1px solid #eaeaea;
border-radius: 10px;
transition: color 0.15s ease, border-color 0.15s ease;
max-width: 300px;
}
.card:hover,
.card:focus,
.card:active {
color: #0070f3;
border-color: #0070f3;
}
.card h2 {
margin: 0 0 1rem 0;
font-size: 1.5rem;
}
.card p {
margin: 0;
font-size: 1.25rem;
line-height: 1.5;
}
.logo {
height: 1em;
margin-left: 0.5rem;
}
@media (max-width: 600px) {
.grid {
width: 100%;
flex-direction: column;
}
}

View File

@@ -1,16 +1,11 @@
html,
body {
padding: 0;
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen,
Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;
@tailwind base;
@tailwind components;
@tailwind utilities;
h1 {
@apply text-2xl;
}
a {
color: inherit;
text-decoration: none;
}
* {
box-sizing: border-box;
button {
@apply py-2 px-4 bg-black text-white rounded;
}

10
tailwind.config.js Normal file
View File

@@ -0,0 +1,10 @@
module.exports = {
content: [
"./pages/**/*.{js,ts,jsx,tsx}",
"./components/**/*.{js,ts,jsx,tsx}",
],
theme: {
extend: {},
},
plugins: [],
};

67
utils/api-helpers.ts Normal file
View File

@@ -0,0 +1,67 @@
export async function fetchGetJSON(url: string) {
try {
const data = await fetch(url).then((res) => res.json());
return data;
} catch (err) {
if (err instanceof Error) {
throw new Error(err.message);
}
throw err;
}
}
export async function fetchPostJSON(url: string, data?: {}) {
try {
// Default options are marked with *
const response = await fetch(url, {
method: "POST", // *GET, POST, PUT, DELETE, etc.
mode: "cors", // no-cors, *cors, same-origin
cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
credentials: "same-origin", // include, *same-origin, omit
headers: {
"Content-Type": "application/json",
Authorization: `token ${process.env.BTCPAY_API_KEY}`,
// 'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: "follow", // manual, *follow, error
referrerPolicy: "no-referrer", // no-referrer, *client
body: JSON.stringify(data || {}), // body data type must match "Content-Type" header
});
return await response.json(); // parses JSON response into native JavaScript objects
} catch (err) {
if (err instanceof Error) {
throw new Error(err.message);
}
throw err;
}
}
export async function fetchPostJSONAuthed(
url: string,
auth: string,
data?: {}
) {
try {
// Default options are marked with *
const response = await fetch(url, {
method: "POST", // *GET, POST, PUT, DELETE, etc.
mode: "cors", // no-cors, *cors, same-origin
cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
credentials: "same-origin", // include, *same-origin, omit
headers: {
"Content-Type": "application/json",
Authorization: auth,
// 'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: "follow", // manual, *follow, error
referrerPolicy: "no-referrer", // no-referrer, *client
body: JSON.stringify(data || {}), // body data type must match "Content-Type" header
});
return await response.json(); // parses JSON response into native JavaScript objects
} catch (err) {
if (err instanceof Error) {
throw new Error(err.message);
}
throw err;
}
}

30
utils/stripe-helpers.ts Normal file
View File

@@ -0,0 +1,30 @@
export function formatAmountForDisplay(
amount: number,
currency: string
): string {
let numberFormat = new Intl.NumberFormat(["en-US"], {
style: "currency",
currency: currency,
currencyDisplay: "symbol",
});
return numberFormat.format(amount);
}
export function formatAmountForStripe(
amount: number,
currency: string
): number {
let numberFormat = new Intl.NumberFormat(["en-US"], {
style: "currency",
currency: currency,
currencyDisplay: "symbol",
});
const parts = numberFormat.formatToParts(amount);
let zeroDecimalCurrency: boolean = true;
for (let part of parts) {
if (part.type === "decimal") {
zeroDecimalCurrency = false;
}
}
return zeroDecimalCurrency ? amount : Math.round(amount * 100);
}