/
codeExamples.js
102 lines (91 loc) · 2.64 KB
/
codeExamples.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
const process = {
env: {
URL: 'https://useshoppingcart.com'
}
}
export const exampleProducts = `
[
{
"name": "Bananas",
"description": "Yummy yellow fruit",
"id": "id_banana001",
"price": 400,
"currency": "USD",
"image": "https://cdn.mos.cms.futurecdn.net/42E9as7NaTaAi4A6JcuFwG-1200-80.jpg"
}
]
`
export const exampleCartProvider = `
import ReactDOM from 'react-dom'
import { CartProvider } from 'use-shopping-cart'
import App from './App'
ReactDOM.render(
<CartProvider
mode="payment"
cartMode="client-only"
stripe={YOUR_STRIPE_PUBLISHABLE_KEY_HERE}
successUrl="stripe.com"
cancelUrl="twitter.com/dayhaysoos"
currency="USD"
allowedCountries={['US', 'GB', 'CA']}
billingAddressCollection={true}
>
<App />
</CartProvider>,
document.getElementById('root')
)
`
export const exampleFrontend = `
import { useShoppingCart, formatCurrencyString } from 'use-shopping-cart'
function Product({ product }) {
const { redirectToCheckout } = useShoppingCart()
const { name, image, description, currency } = product
const price = formatCurrencyString({ value: product.price, currency, language: 'en-US' })
async function buyNow() {
const response = await fetch("/.netlify/functions/create-session", {
method: "post",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ [product.id]: { ...product, quantity: 1 } }),
}).then(res => res.json())
.catch(error => {/* Error handling */})
redirectToCheckout({ sessionId: response.sessionId })
}
return (
<article>
<figure>
<img src={image} alt={description} width="100" />
<figcaption>
{price} {name}
</figcaption>
</figure>
<button onClick={buyNow}>Buy now</button>
</article>
)
}
`
export const exampleServerless = `
const stripe = require('stripe')(process.env.STRIPE_API_SECRET)
const validateCartItems = require('use-shopping-cart/utilities')
.validateCartItems
const inventory = require('./data/products.json')
exports.handler = async (event) => {
try {
const productJSON = JSON.parse(event.body)
const line_items = validateCartItems(inventory, productJSON)
const session = await stripe.checkout.sessions.create({
payment_method_types: ['card'],
billing_address_collection: 'auto',
shipping_address_collection: {
allowed_countries: ['US', 'CA']
},
success_url: \`${process.env.URL}/success.html\`,
cancel_url: process.env.URL,
line_items
})
return {
statusCode: 200,
body: JSON.stringify({ sessionId: session.id })
}
} catch (error) {/* Error handling */}
}
`