|
1
|
import Whop from '@whop/sdk'; |
|
2
|
|
|
3
|
let clientPromise: Promise<Whop> | null = null; |
|
4
|
|
|
5
|
async function initWhopClient(): Promise<Whop> { |
|
6
|
const hostname = process.env.REPLIT_CONNECTORS_HOSTNAME; |
|
7
|
const xReplitToken = process.env.REPL_IDENTITY |
|
8
|
? "repl " + process.env.REPL_IDENTITY |
|
9
|
: process.env.WEB_REPL_RENEWAL |
|
10
|
? "depl " + process.env.WEB_REPL_RENEWAL |
|
11
|
: null; |
|
12
|
|
|
13
|
if (!hostname || !xReplitToken) { |
|
14
|
throw new Error( |
|
15
|
'Missing Replit environment variables. ' + |
|
16
|
'Ensure the Whop integration is connected via the Integrations tab.' |
|
17
|
); |
|
18
|
} |
|
19
|
|
|
20
|
const resp = await fetch( |
|
21
|
`https://${hostname}/api/v2/connection?include_secrets=true&connector_names=whop`, |
|
22
|
{ |
|
23
|
headers: { Accept: "application/json", X_REPLIT_TOKEN: xReplitToken }, |
|
24
|
signal: AbortSignal.timeout(10_000), |
|
25
|
} |
|
26
|
); |
|
27
|
|
|
28
|
if (!resp.ok) { |
|
29
|
throw new Error(`Failed to fetch Whop credentials: ${resp.status} ${resp.statusText}`); |
|
30
|
} |
|
31
|
|
|
32
|
const data = await resp.json(); |
|
33
|
const settings = data.items?.[0]?.settings; |
|
34
|
|
|
35
|
if (!settings?.api_key) { |
|
36
|
throw new Error( |
|
37
|
'Whop integration not connected or missing credentials. ' + |
|
38
|
'Connect Whop via the Integrations tab first.' |
|
39
|
); |
|
40
|
} |
|
41
|
|
|
42
|
return new Whop({ apiKey: settings.api_key }); |
|
43
|
} |
|
44
|
|
|
45
|
export function getWhopClient(): Promise<Whop> { |
|
46
|
if (!clientPromise) { |
|
47
|
clientPromise = initWhopClient().catch((err) => { |
|
48
|
clientPromise = null; |
|
49
|
throw err; |
|
50
|
}); |
|
51
|
} |
|
52
|
|
|
53
|
return clientPromise; |
|
54
|
} |