diff --git a/system/netlify.toml b/system/netlify.toml index f7663eaf47..3c9844b247 100644 --- a/system/netlify.toml +++ b/system/netlify.toml @@ -16,7 +16,7 @@ ] external_node_modules = ["got", "mongodb"] [functions.print] - external_node_modules = ["got"] + external_node_modules = ["got", "stripe"] [functions.pixel] external_node_modules = ["got", "sharp"] [functions.user] diff --git a/system/netlify/functions/pixel.js b/system/netlify/functions/pixel.js index 6032deda12..5b051ccd41 100644 --- a/system/netlify/functions/pixel.js +++ b/system/netlify/functions/pixel.js @@ -2,12 +2,13 @@ // An endpoint to transform / affect input pixels from // a painting before returning them. -// Usage: /pixel/widthxheight/bucket/painting +// Usage: /pixel/widthxheight/bucket/painting or add an extension. -// Test URL: https://aesthetic.local:8888/api/print?painting=https://art.aesthetic.computer/Lw2OYs0H.png +// Test URL: https://aesthetic.local:8888/api/print?pixels=https://art.aesthetic.computer/Lw2OYs0H.png /* #region 🏁 TODO - - [] Nearest neighbor scale a painting after opening it. + + Done + - [x] Nearest neighbor scale a painting after opening it. #endregion */ const { builder } = require("@netlify/functions"); @@ -24,7 +25,7 @@ async function handler(event, context) { const params = event.path.replace("/api/pixel/", "").split("/"); const resolution = params[0].split("x").map((n) => parseInt(n)); const bucket = params[1]; - const painting = params[2]; + const painting = params[2].replace(".png", ""); // Replace ".png" suffix if it exists. const imageUrl = `https://${bucket}.aesthetic.computer/${painting}.png`; @@ -37,10 +38,12 @@ async function handler(event, context) { const response = await got(imageUrl, { responseType: "buffer" }); // Resize the image using nearest neighbor filtering with "sharp" + // Docs: https://sharp.pixelplumbing.com/api-resize const resizedBuffer = await sharp(response.body) .resize({ width: resolution[0], height: resolution[1], + fit: "fill", kernel: sharp.kernel.nearest, }) .png() @@ -67,4 +70,4 @@ async function handler(event, context) { } } -exports.handler = builder(handler); \ No newline at end of file +exports.handler = builder(handler); diff --git a/system/netlify/functions/print.js b/system/netlify/functions/print.js index 74c5652820..c8bfc16647 100644 --- a/system/netlify/functions/print.js +++ b/system/netlify/functions/print.js @@ -1,18 +1,35 @@ // Print, 23.08.25.14.37 // Order stickers or get mockup imagery from a POD API (Printful) +// Dashboard: https://www.printful.com/dashboard // Usage: /print?image=imageurl; // ^ TODO: This should be a painting code / url? -// Test URL: https://aesthetic.computer/api/print?pixels=https://aesthetic.computer/api/pixel/1650x1650/art/Lw2OYs0H +// GET: Returns an image mockup url for the print. +// POST: Takes user info like an address and creates an order in the system. +// Prod example URL: https://aesthetic.computer/api/print?pixels=https://aesthetic.computer/api/pixel/1650x1650/art/Lw2OYs0H +// Local example URL: https://aesthetic.local:8888/api/print?pixels=https://aesthetic.computer/api/pixel/1650x1650/art/Lw2OYs0H + +// Installing the Stripe CLI: https://stripe.com/docs/stripe-cli#install +// For testing webhooks: `stripe listen --forward-to stripe listen --forward-to "https://localhost:8888/api/print" /* #region 🏁 TODO + - [] Add branding: https://stripe.com/docs/payments/checkout/customization - [] Get mockup images working and looking good for different resolutions. - - [] Test a painting that is at a different resolution / try - a cropped image. - - [] Create an actual order. (Is it possible to make a fake order / cancel one after making it?) + - [] Test a painting that is at a different resolution / try + a cropped image. + - [] Run some test orders. + - [] Create a REAL order! + + + Later + - [] Generate multiple items / stickers per order. (Multi-pack) + Done + - [x] Add stripe checkout. + - [x] There needs to be a way to get and/or store user address information or + have the user fill out a payment form and validate their address that + way... + - [x] Add some funds ($150) to my Printful wallet. - [x] Find a library that can decode and rescale the PNG. - [x] Should this eventually go in a separate API call? - [x] Nearest-neighbor stretch the painting to fit 1650x1650 @@ -22,22 +39,69 @@ import { respond } from "../../backend/http.mjs"; +import Stripe from "stripe"; + const dev = process.env.CONTEXT === "dev"; const printfulKey = process.env.PRINTFUL_API_TOKEN; +const stripeKey = process.env.STRIPE_API_TEST_KEY; // process.env.STRIPE_API_PRIV_KEY; // Uncomment for real orders. +const productName = "aesthetic.computer Painting Sticker"; export async function handler(event, context) { const { got } = await import("got"); - const API = "https://api.printful.com"; const headers = { Authorization: "Bearer " + printfulKey, "Content-Type": "application/json", }; - if ( - event.httpMethod === "GET" && - (event.headers["host"] === "aesthetic.computer" || dev) - ) { + if (event.headers["host"] !== "aesthetic.computer" && !dev) { + return respond(400, { message: "Bad request." }); + } + + const id = 358; + const variant = 10165; + const imageUrl = event.queryStringParameters.pixels; + const width = 1650; + const height = 1650; + + // 🅰️ GET: Generate a mockup image. + if (event.httpMethod === "GET") { + // TODO: Eventually move this down into a "POST" request. + const stripe = new Stripe(stripeKey); + const domain = dev + ? "https://localhost:8888" + : "https://aesthetic.computer"; + + const stripeCheckout = { + line_items: [ + { + price_data: { + currency: "usd", + product_data: { + name: productName, + images: [imageUrl], + }, + unit_amount: 1000, // Amount in cents + }, + quantity: 1, + }, + ], + metadata: { + imageUrl, // TODO: Eventually this might need to include images<->product associations for multiple items. + }, + mode: "payment", + shipping_address_collection: { allowed_countries: ["US"] }, + success_url: `${domain}/success.html`, + cancel_url: `${domain}/cancel.html`, + automatic_tax: { enabled: true }, + }; + + // TODO: 🔥 Add `customer_email` to the above if the user is currently logged in? + + const session = await stripe.checkout.sessions.create(stripeCheckout); + + return respond(303, undefined, { Location: session.url }); + try { // 🔸 List all products. // (Only really needed while developing for now. 23.08.25.18.42) @@ -49,7 +113,7 @@ export async function handler(event, context) { // 🔍 // 202 - Stickers `category_id`. // 358 - Kiss-cut sticker product `id`. - const id = 358; + // const id = 358; // 🔸 Get information for a single product. // (Which includes its availailbility status by region, per variant.) @@ -59,7 +123,7 @@ export async function handler(event, context) { // 🔍 // ??? - Kiss-cut sticker 5.5" square `variant_id`. - const variant = 10165; + // const variant = 10165; // 🔸 Get print constraints for a given product. // const printfiles = await got.get( @@ -69,8 +133,6 @@ export async function handler(event, context) { // return respond(200, { product: JSON.parse(printfiles.body) }); // 🔸 Generate a mockup image. - const imageUrl = event.queryStringParameters.pixels; - const task = await got.post(`${API}/mockup-generator/create-task/${id}`, { headers: headers, json: { @@ -80,10 +142,10 @@ export async function handler(event, context) { placement: "default", // 185 image_url: imageUrl, position: { - area_width: 1650, + area_width: 1650, // Constant for this variant. area_height: 1650, - width: 1650, - height: 1650, + width, + height, top: 0, left: 0, }, @@ -94,11 +156,7 @@ export async function handler(event, context) { }); const taskResult = JSON.parse(task.body)?.result; - // return respond(200, { task: taskResult }) }); - console.log("Task result:", taskResult); - - // Polling logic let mockupUrl = null; const maxAttempts = 12; let attempt = 0; @@ -127,9 +185,132 @@ export async function handler(event, context) { }); } } catch (error) { - console.error("Failed to generate mockup:", error.message); return respond(500, { message: error.message }); } + } else if (event.httpMethod === "POST") { + // 🅱️ POST: Place an order. + + // ↪️ Receive webhook events... + // ✅ checkout.session.completed + // charge.succeeded + // payment_intent.succeeded + // payment_intent.created + + const stripe = new Stripe(stripeKey); + const sig = event.headers["stripe-signature"]; + const secret = dev + ? "whsec_181bbe48c808731616de39c5c75fc670c83c6ef554409b8c770170b718fbd3b0" + : process.env.STRIPE_ENDPOINT_SECRET; + let hookEvent; + + try { + hookEvent = stripe.webhooks.constructEvent(event.body, sig, secret); + } catch (err) { + const msg = { message: `Webhook Error: ${err.message}` }; + console.log(msg); + return respond(400, msg); + } + + // Handle the `checkout.session.completed` event + if (hookEvent.type === "checkout.session.completed") { + // Retrieve the session. If you require line items in the response, you may include them by expanding line_items. + const session = await stripe.checkout.sessions.retrieve( + hookEvent.data.object.id, + { expand: ["line_items", "shipping_details", "customer_details"] } + ); + console.log("🤑 Stripe order:", session); + + console.log("Line items:", session.line_items); + + const itemImage = hookEvent.data.object.metadata.imageUrl; + console.log("Image:", itemImage); + // console.log("Shipping details:", session.shipping_details); + // console.log("Customer:", session.customer_details); + + // TODO: If this fails after a successful payment, then it needs to be + // manually triggerable for already paid orders or a refund needs + // to be triggered automagically. 23.08.29.17.50 + + if (session.payment_status === "paid") { + console.log("✅ Paid!"); + + // 🖨️ Run the printful order. + const shipping = session.shipping_details; + const recipient = { + name: shipping.name, + address1: shipping.address.line1, + city: shipping.address.city, + state_code: shipping.address.state, + country_code: shipping.address.country, + zip: shipping.address.postal_code, + }; + if (shipping.address.line2) recipient.address2 = shipping.address.line2; + + const order = { + recipient, + items: [ + { + name: productName, + variant_id: variant, + quantity: 1, + files: [ + { + url: itemImage, + position: { + area_width: 1650, // Constant for this variant. + area_height: 1650, + width, + height, + top: 0, + left: 0, + }, + }, + ], + }, + ], + packing_slip: { + email: "mail@aesthetic.computer", + message: "Stickers belong in special spots. - @jeffrey", + logo_url: "https://assets.aesthetic.computer/images/favicon.png", + store_name: "aesthetic.computer", + }, + }; + + console.log("Making printful order:", order); + + try { + // 🔸 Place an order. + // See also: https://developers.printful.com/docs/#operation/createOrder + // TODO: Auto-confirm orders. + const orderResponse = await got.post(`${API}/orders?confirm=false`, { + headers, + json: order, + }); + + const orderResult = JSON.parse(orderResponse.body); + + if (orderResult && orderResult.result) { + console.log("😃 Order sent!", orderResult); + // TODO: How to include image metadata? + + return respond(200, { order: orderResult.result }); + } else { + const msg = { message: "Error processing order." }; + console.log(msg); + return respond(500, msg); + } + } catch (error) { + const msg = { message: error.message }; + console.log(msg); + return respond(500, msg); + } + } else { + // Stripe order was unpaid. + return respond(500, { message: "Order payment failed." }); + } + } else { + return respond(400, { message: "Incorrect webhook event." }); + } } else { return respond(405, { message: "Method Not Allowed" }); } diff --git a/system/package-lock.json b/system/package-lock.json index 08fc444df7..e07b6db286 100644 --- a/system/package-lock.json +++ b/system/package-lock.json @@ -34,6 +34,7 @@ "puppeteer": "^20.9.0", "redis": "^4.5.1", "sharp": "^0.32.5", + "stripe": "^13.3.0", "three": "^0.146.0", "web3": "^1.8.1" }, @@ -31990,6 +31991,18 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/stripe": { + "version": "13.3.0", + "resolved": "https://registry.npmjs.org/stripe/-/stripe-13.3.0.tgz", + "integrity": "sha512-saDZBvk8fCBz9GigKpVXAaAo0K+TQe+DwVmucAzpJq503Y44P2ehMqulfaRoK8a+etuwIUlgsXD+am6YSMxepg==", + "dependencies": { + "@types/node": ">=8.1.0", + "qs": "^6.11.0" + }, + "engines": { + "node": ">=12.*" + } + }, "node_modules/strnum": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/strnum/-/strnum-1.0.5.tgz", diff --git a/system/package.json b/system/package.json index b26e5b98cf..48baae3348 100644 --- a/system/package.json +++ b/system/package.json @@ -60,6 +60,7 @@ "puppeteer": "^20.9.0", "redis": "^4.5.1", "sharp": "^0.32.5", + "stripe": "^13.3.0", "three": "^0.146.0", "web3": "^1.8.1" }, diff --git a/system/public/aesthetic.computer/disks/painting.mjs b/system/public/aesthetic.computer/disks/painting.mjs index f8d85c878c..d4b6b4ea38 100644 --- a/system/public/aesthetic.computer/disks/painting.mjs +++ b/system/public/aesthetic.computer/disks/painting.mjs @@ -5,13 +5,14 @@ #endregion */ /* #region 🏁 TODO - - [] Add `print` button. - - [] Automatically go to the `painting` page after a successful upload / + - [-] Automatically go to the `painting` page after a successful upload / return the proper code. + - [] Generally smooth out the `painting:done` and `yes` feedback. + Later - [] Sound - [] Forwards and backwards directionality. + Done + - [x] Add `print` button. - [x] Load provisional / non-user paintings. - [x] If there is no recording then still load and show the `.png`. - [x] Playback all an existing painting's steps in a loop, with @@ -130,7 +131,26 @@ function paint({ wipe, ink, system, screen, num, paste }) { // 🎪 Act function act({ event: e, screen }) { - print.act(e); + print.act(e, { + push: async () => { + try { + const pixels = + "https://aesthetic.computer/api/pixel/1650x1650/art/Lw2OYs0H"; + const res = await fetch(`/api/print?pixels=${pixels}`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ order: "yeah" }), + // TODO: Add order info here. ^ + }); + + if (!res.ok) throw new Error(`HTTP error! Status: ${res}`); + const data = await res.json(); + console.log("Order:", data); + } catch (error) { + console.error("Order creation error:", error.message); + } + }, + }); if (e.is("reframed")) { print.reposition({ right: 6, bottom: 6, screen }); diff --git a/system/public/cancel.html b/system/public/cancel.html new file mode 100644 index 0000000000..da6088157b --- /dev/null +++ b/system/public/cancel.html @@ -0,0 +1,15 @@ + + + + + Checkout canceled + + + + +
+

Forgot to add something to your cart? Shop around then come back to pay!

+
+ + + \ No newline at end of file diff --git a/system/public/checkout.html b/system/public/checkout.html new file mode 100644 index 0000000000..a238179b21 --- /dev/null +++ b/system/public/checkout.html @@ -0,0 +1,25 @@ + + + + + Buy cool new product + + + + + +
+
+ The cover of Stubborn Attachments +
+

Stubborn Attachments

+
$20.00
+
+
+
+ +
+
+ + + \ No newline at end of file diff --git a/system/public/success.html b/system/public/success.html new file mode 100644 index 0000000000..4e815290c5 --- /dev/null +++ b/system/public/success.html @@ -0,0 +1,18 @@ + + + + + Thanks for your order! + + + + +
+

+ We appreciate your business! If you have any questions, please email + orders@example.com. +

+
+ + + \ No newline at end of file