-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauthClient.js
More file actions
172 lines (143 loc) · 4.69 KB
/
authClient.js
File metadata and controls
172 lines (143 loc) · 4.69 KB
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
import * as Crypto from 'expo-crypto';
import { useShopifyCheckoutSheet } from '@shopify/checkout-sheet-kit';
const shopDomain = '{shop}.myshopify.com';
const customerAccountsApiClientId = 'your-client-id';
const customerAccountsApiRedirectUri = 'shop.{your_shop_id}.app://callback';
const storefrontAccessToken = 'your-storefront-access-token';
let codeVerifier = null;
let savedState = null;
// PKCE
// [START auth.generate-pkce]
function encodeBase64Url(bytes) {
return Buffer.from(bytes)
.toString('base64')
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=+$/, '');
}
export async function generateCodeVerifier() {
const bytes = await Crypto.getRandomBytesAsync(32);
return encodeBase64Url(bytes);
}
export async function generateCodeChallenge(codeVerifier) {
const digestString = await Crypto.digestStringAsync(
Crypto.CryptoDigestAlgorithm.SHA256,
codeVerifier,
);
return encodeBase64Url(digestString);
}
// [END auth.generate-pkce]
// Endpoint Discovery
// [START auth.discover-endpoints]
async function discoverAuthEndpoints() {
const discoveryUrl = `https://${shopDomain}/.well-known/openid-configuration`;
const response = await fetch(discoveryUrl);
const config = await response.json();
return {
authEndpoint: config.authorization_endpoint,
tokenEndpoint: config.token_endpoint,
};
}
// [END auth.discover-endpoints]
// Authorization URL
// [START auth.build-auth-url]
function generateRandomString(length) {
const characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
let result = '';
for (let i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * characters.length));
}
return result;
}
export async function buildAuthorizationUrl() {
codeVerifier = await generateCodeVerifier();
const codeChallenge = await generateCodeChallenge(codeVerifier);
const { authEndpoint } = await discoverAuthEndpoints();
savedState = generateRandomString(36);
const url = new URL(authEndpoint);
url.searchParams.append('scope', 'openid email customer-account-api:full');
url.searchParams.append('client_id', customerAccountsApiClientId);
url.searchParams.append('response_type', 'code');
url.searchParams.append('redirect_uri', customerAccountsApiRedirectUri);
url.searchParams.append('state', savedState);
url.searchParams.append('code_challenge', codeChallenge);
url.searchParams.append('code_challenge_method', 'S256');
return url.toString();
}
// [END auth.build-auth-url]
// Callback Handling
// [START auth.handle-callback]
export function handleCallback(url) {
if (!url?.startsWith(customerAccountsApiRedirectUri)) {
return null;
}
const parsed = new URL(url);
const state = parsed.searchParams.get('state');
if (state !== savedState) {
return null;
}
return parsed.searchParams.get('code');
}
// [END auth.handle-callback]
// Token Exchange
// [START auth.exchange-token]
export async function requestAccessToken(code) {
const { tokenEndpoint } = await discoverAuthEndpoints();
const requestBody = new URLSearchParams({
grant_type: 'authorization_code',
client_id: customerAccountsApiClientId,
redirect_uri: customerAccountsApiRedirectUri,
code: code,
code_verifier: codeVerifier,
});
const response = await fetch(tokenEndpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: requestBody.toString(),
});
const json = await response.json();
return {
accessToken: json.access_token,
refreshToken: json.refresh_token,
expiresIn: json.expires_in,
};
}
// [END auth.exchange-token]
// Authenticated Cart
// [START auth.create-authenticated-cart]
export async function createAuthenticatedCart(variantId, accessToken) {
const query = `
mutation cartCreate($input: CartInput!) {
cartCreate(input: $input) {
cart { checkoutUrl }
userErrors { field message }
}
}
`;
const variables = {
input: {
lines: [{ merchandiseId: variantId, quantity: 1 }],
buyerIdentity: { customerAccessToken: accessToken },
},
};
const response = await fetch(
`https://${shopDomain}/api/2026-01/graphql.json`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Shopify-Storefront-Access-Token': storefrontAccessToken,
},
body: JSON.stringify({ query, variables }),
},
);
const json = await response.json();
return json.data.cartCreate.cart.checkoutUrl;
}
// [END auth.create-authenticated-cart]
// Present Checkout
// [START auth.present-checkout]
export function presentCheckout(shopifyCheckout, checkoutUrl) {
shopifyCheckout.present(checkoutUrl);
}
// [END auth.present-checkout]