@godaddy/react
Version:
The `createCheckoutSession` function creates a new checkout session with GoDaddy's commerce API.
49 lines (45 loc) • 1.72 kB
JavaScript
'use server';
import { f as createCheckoutSession$1, n as getEnvVar } from "./utils-DWBfAHfx.js";
//#region src/server.ts
let accessToken;
let accessTokenExpiresAt;
async function createCheckoutSession(input, options) {
const CLIENT_ID = options?.auth?.clientId || "";
const CLIENT_SECRET = options?.auth?.clientSecret || "";
const now = Date.now() / 1e3;
if (!accessToken || !accessTokenExpiresAt || accessTokenExpiresAt - 60 < now) {
const getAccessTokenResponse = await getAccessToken({
clientId: CLIENT_ID,
clientSecret: CLIENT_SECRET
});
accessToken = getAccessTokenResponse?.access_token;
accessTokenExpiresAt = now + (getAccessTokenResponse?.expires_in || 0);
}
if (!accessToken) throw new Error("Failed to get access token");
return await createCheckoutSession$1(input, {
accessToken,
apiHost: getEnvVar("GODADDY_API_HOST")
});
}
function getHostByEnvironment() {
return `https://${getEnvVar("GODADDY_API_HOST") || "api.godaddy.com"}`;
}
async function getAccessToken({ clientId, clientSecret }) {
if (!clientId || !clientSecret) return;
const host = getHostByEnvironment();
const data = new URLSearchParams();
data.append("grant_type", "client_credentials");
data.append("client_id", clientId);
data.append("client_secret", clientSecret);
data.append("scope", "commerce.product:read");
const response = await fetch(`${host}/v2/oauth2/token`, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: data.toString(),
cache: "no-store"
});
if (!response.ok) throw new Error(`Failed to get access token: ${response.status} ${response.statusText}`);
return await response.json();
}
//#endregion
export { createCheckoutSession };