Call from your server
Background jobs and agents that work for a user while they're away, with their OK.
Some work happens on your server: a nightly digest, an agent that keeps going after the tab closes. The user approves that once in ChargeMyAI's window; your server then calls ChargeMyAI for them, paid from their balance within the daily limit they set for your app. It works like OAuth's authorization-code flow.
- 1In the console (https://app.chargemyai.com), open Sites, then Server keys, and make a key. Put its id and secret in your server's environment. The secret is shown once.
- 2In your page, ask the user:
const { code } = await charge.authorizeServer(). ChargeMyAI's window asks them to allow it, and you get a one-time code (good for 10 minutes). - 3Send the code to your server, which trades it for a refresh token. Keep the refresh token with the user's record.
- 4Whenever the server needs AI, it trades the refresh token for an access token (good for an hour) and uses it as the API key.
page.html
<button id="allow">Let us prepare your report every morning</button>
<script type="module">
allow.onclick = async () => {
const { code } = await charge.authorizeServer()
await fetch('/api/chargemyai/connect', { method: 'POST', body: JSON.stringify({ code }) })
}
</script> server.js
const TOKEN_URL = 'https://api.chargemyai.com/v1/oauth/token'
const key = { client_id: process.env.CHARGEMYAI_KEY_ID, client_secret: process.env.CHARGEMYAI_KEY_SECRET }
// Once, when the page sends the code: keep refresh_token with the user.
const { refresh_token, user } = await post({ grant_type: 'authorization_code', code, ...key })
// Each time the server needs AI for that user:
const { access_token } = await post({ grant_type: 'refresh_token', refresh_token, ...key })
const ai = new OpenAI({ baseURL: 'https://api.chargemyai.com/v1', apiKey: access_token })
const res = await ai.chat.completions.create({ model: 'standard', messages })
async function post(body) {
const r = await fetch(TOKEN_URL, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) })
if (!r.ok) throw new Error((await r.json()).error_description)
return r.json()
} - Keep the key secret and refresh tokens on your server only, never in pages or public code.
- If the user disconnects your app in their ChargeMyAI account, refreshing fails with
invalid_grant: ask them again next time they visit. Revoking a key in the console stops it at once. - A call that fails with
insufficient_balanceordaily_capcan't show a sheet from a server. Tell the user next time they open your app, wherecharge.fetchtakes care of it.
Read next
Still stuck? Talk to us and we'll help.