Change paypal example to square
[square_example_site.git] / checkout.html.jst
1 let square = require("square")
2 let uuid = require("uuid")
3
4 return async env => {
5   let config = await env.site.get_json('/_config/config.json')
6
7   // Initialize the authorization for Square
8   let client = new square.Client(
9     {
10       accessToken: config.square_access_token,
11       environment:
12         config.environment === 'production' ?
13           square.Environment.Production :
14           square.Environment.Sandbox
15     }
16   )
17
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.
20   
21   // Set currency to the currency for the location
22   let currency = (
23     await client.locationsApi.retrieveLocation(config.square_location_id)
24   ).result.location.currency
25
26   let money_A = {currency: currency, amount: 500}
27   let item_A = {quantity: '1', name: 'Test Item A', basePriceMoney: money_A}
28
29   let money_B = {currency: currency, amount: 1000}
30   let item_B = {quantity: '3', name: 'Test Item B', basePriceMoney: money_B}
31
32   // Create a new order and add the line items as necessary.
33   let order = {
34     locationId: config.square_location_id,
35     lineItems: [item_A, item_B]
36   }
37
38   let order_request = {order: order}
39
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(),
44     order: order_request,
45     redirectUrl: 'http://localhost:8080/confirmation.html'
46   }
47
48   let response = await client.checkoutApi.createCheckout(
49     config.square_location_id,
50     checkout_request
51   )
52   console.log('response', response)
53
54   // If there was an error with the request we will
55   // print them to the browser screen here
56   if (response.isError) {
57     let _out = []
58     _out.push('<!DOCTYPE html>')
59     html {
60       body {
61         'Api response has Errors'
62         ul {
63           for (let i = 0; i < response.errors.length; ++i)
64             li {`❌ ${error.detail}`}
65         }
66       }
67     }
68     env.site.serve(env, 200, Buffer.from(_out.join('')), 'checkout.html.jst')
69     return
70   }
71
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')
75 }