1 let square = require("square")
2 let uuid = require("uuid")
5 let config = await env.site.get_json('/_config/config.json')
7 // Initialize the authorization for Square
8 let client = new square.Client(
10 accessToken: config.square_access_token,
12 config.environment === 'production' ?
13 square.Environment.Production :
14 square.Environment.Sandbox
18 // Monetary amounts are specified in the smallest unit of the applicable currency.
19 // This amount is in cents. It's also hard-coded for $1.00, which isn't very useful.
21 // Set currency to the currency for the location
23 await client.locationsApi.retrieveLocation(config.square_location_id)
24 ).result.location.currency
26 let money_A = {currency: currency, amount: 500}
27 let item_A = {quantity: '1', name: 'Test Item A', basePriceMoney: money_A}
29 let money_B = {currency: currency, amount: 1000}
30 let item_B = {quantity: '3', name: 'Test Item B', basePriceMoney: money_B}
32 // Create a new order and add the line items as necessary.
34 locationId: config.square_location_id,
35 lineItems: [item_A, item_B]
38 let order_request = {order: order}
40 // Similar to payments you must have a unique idempotency key.
41 // Set a custom redirect URL, otherwise a default Square confirmation page will be used
42 let checkout_request = {
43 idempotencyKey: uuid.v4(),
45 redirectUrl: 'http://localhost:8080/confirmation.html'
48 let response = await client.checkoutApi.createCheckout(
49 config.square_location_id,
52 console.log('response', response)
54 // If there was an error with the request we will
55 // print them to the browser screen here
56 if (response.isError) {
58 _out.push('<!DOCTYPE html>')
61 'Api response has Errors'
63 for (let i = 0; i < response.errors.length; ++i)
64 li {`❌ ${error.detail}`}
68 env.site.serve(env, 200, Buffer.from(_out.join('')), 'checkout.html.jst')
72 // This redirects to the Square hosted checkout page
73 env.response.setHeader('Location', response.result.checkout.checkoutPageUrl)
74 env.site.serve(env, 301, Buffer.alloc(0), 'checkout.html.jst')