/**
* Simple OAuth token fetcher for Shopify dev store.
* 1. Starts a local HTTP server on port 3456
* 2. Opens the OAuth authorize URL in the browser
* 3. Receives the callback with the auth code
* 4. Exchanges it for an access token
* 5. Prints the token and exits
*/
import http from 'node:http';
import { exec } from 'node:child_process';
import { URL } from 'node:url';
const CLIENT_ID = process.env.SHOPIFY_API_KEY ?? '';
const CLIENT_SECRET = process.env.SHOPIFY_API_SECRET ?? '';
const STORE = process.env.SHOPIFY_STORE_DOMAIN ?? '';
const SCOPES = 'read_products,read_orders,read_inventory,read_price_rules,read_discounts';
const REDIRECT_URI = 'http://localhost:3456/callback';
const PORT = 3456;
const server = http.createServer(async (req, res) => {
const url = new URL(req.url, `http://localhost:${PORT}`);
if (url.pathname !== '/callback') {
res.writeHead(404);
res.end('Not found');
return;
}
const code = url.searchParams.get('code');
if (!code) {
res.writeHead(400);
res.end('Missing code parameter');
return;
}
console.log(`\nReceived auth code: ${code.slice(0, 8)}...`);
console.log('Exchanging for access token...\n');
try {
const tokenResponse = await fetch(
`https://${STORE}/admin/oauth/access_token`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
client_id: CLIENT_ID,
client_secret: CLIENT_SECRET,
code,
}),
},
);
if (!tokenResponse.ok) {
const text = await tokenResponse.text();
throw new Error(`Token exchange failed: ${tokenResponse.status} ${text}`);
}
const data = await tokenResponse.json();
console.log('=== ACCESS TOKEN ===');
console.log(data.access_token);
console.log('====================');
console.log('\nFull response:', JSON.stringify(data, null, 2));
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('<h1>Success!</h1><p>Access token obtained. You can close this tab.</p>');
} catch (err) {
console.error('Error:', err.message);
res.writeHead(500);
res.end(`Error: ${err.message}`);
}
setTimeout(() => {
server.close();
process.exit(0);
}, 1000);
});
server.listen(PORT, () => {
const authorizeUrl =
`https://${STORE}/admin/oauth/authorize` +
`?client_id=${CLIENT_ID}` +
`&scope=${SCOPES}` +
`&redirect_uri=${encodeURIComponent(REDIRECT_URI)}`;
console.log(`\nOAuth server listening on port ${PORT}`);
console.log(`\nOpening browser for authorization...`);
console.log(`URL: ${authorizeUrl}\n`);
exec(`open "${authorizeUrl}"`);
});