Docs/Use it in your stack

React Native, Flutter and mobile apps

Sign users in through the system browser and call the API with their token. No secret in the app.

A native app can't load charge.js, so it signs the user in on ChargeMyAI's own page, opened in the system browser: ASWebAuthenticationSession on iOS, Custom Tabs on Android. The page sends the user back to your app with a one-time code, and the app trades the code for the user's token. It is OAuth 2.0's authorization-code flow with PKCE, so the app holds no secret.

  1. 1Claim your site in the console (https://app.chargemyai.com). The app signs users in as that site: the same daily limit, balance and earnings as your web app.
  2. 2In the console, open Sites, then App sign-in, and add the address your app opens with, like yourapp://auth. Set the same scheme up in the app (Expo's scheme in app.json, or CFBundleURLSchemes and an Android intent filter).
  3. 3Make a random code verifier and its SHA-256 challenge, then open https://api.chargemyai.com/account/?mode=authorize with origin (your site), redirect_uri, state, code_challenge and code_challenge_method=S256.
  4. 4The user signs in, picks your app's daily limit and comes back to yourapp://auth?code=…&state=…. Check that state is the one you sent.
  5. 5POST the code and the verifier to https://api.chargemyai.com/v1/oauth/token. You get access_token, refresh_token and user. Keep both tokens in the Keychain or Keystore.
  6. 6Use access_token as the API key for /v1/chat/completions, like an OpenAI key. It lasts 7 days; when a call returns 401, trade refresh_token for new tokens.

React Native (Expo)

expo-web-browser opens ASWebAuthenticationSession on iOS and a Custom Tab on Android.

chargemyai.js
import * as WebBrowser from 'expo-web-browser'
import * as Crypto from 'expo-crypto'
import * as Linking from 'expo-linking'
import * as SecureStore from 'expo-secure-store'

const API = 'https://api.chargemyai.com'
const SITE = 'https://yourapp.in'   // your claimed site
const REDIRECT = 'yourapp://auth'   // added under App sign-in in the console

const query = (o) => Object.entries(o).map(([k, v]) => k + '=' + encodeURIComponent(v)).join('&')
const b64url = (s) => s.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')

export async function signIn() {
  const verifier = Crypto.randomUUID() + Crypto.randomUUID()
  const state = Crypto.randomUUID()
  const challenge = b64url(await Crypto.digestStringAsync(Crypto.CryptoDigestAlgorithm.SHA256, verifier,
    { encoding: Crypto.CryptoEncoding.BASE64 }))
  const url = API + '/account/?' + query({ mode: 'authorize', origin: SITE, redirect_uri: REDIRECT, state,
    code_challenge: challenge, code_challenge_method: 'S256' })
  const result = await WebBrowser.openAuthSessionAsync(url, REDIRECT)
  if (result.type !== 'success') return false   // they closed it
  const back = Linking.parse(result.url).queryParams
  if (back.state !== state || !back.code) return false   // "Not now", or not our sign-in
  return save(await token({ grant_type: 'authorization_code', code: back.code, code_verifier: verifier }))
}

// Ask AI for the signed-in user. Their balance pays; a 401 refreshes once.
export async function chat(messages) {
  for (let attempt = 0; ; attempt++) {
    const saved = JSON.parse(await SecureStore.getItemAsync('chargemyai'))
    const res = await fetch(API + '/v1/chat/completions', {
      method: 'POST',
      headers: { Authorization: 'Bearer ' + saved?.access, 'Content-Type': 'application/json' },
      body: JSON.stringify({ model: 'standard', messages }),
    })
    if (res.status !== 401 || attempt) return res.json()
    if (!saved) { if (!(await signIn())) return null; continue }
    try { await save(await token({ grant_type: 'refresh_token', refresh_token: saved.refresh })) }
    catch { if (!(await signIn())) return null }
  }
}

async function token(body) {
  const r = await fetch(API + '/v1/oauth/token', { 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()
}

async function save(t) {
  // Each refresh returns a new refresh_token: always keep the latest.
  await SecureStore.setItemAsync('chargemyai', JSON.stringify({ access: t.access_token, refresh: t.refresh_token }))
  return true
}

Flutter

flutter_web_auth_2 opens ASWebAuthenticationSession on iOS and a Custom Tab on Android. Keep the tokens with flutter_secure_storage.

chargemyai.dart
import 'dart:convert';
import 'dart:math';
import 'package:crypto/crypto.dart';
import 'package:flutter_web_auth_2/flutter_web_auth_2.dart';
import 'package:http/http.dart' as http;

const api = 'https://api.chargemyai.com';
const site = 'https://yourapp.in'; // your claimed site
const scheme = 'yourapp';          // yourapp://auth is added under App sign-in in the console

String _b64(List<int> bytes) => base64UrlEncode(bytes).replaceAll('=', '');
String _random(int n) => _b64(List.generate(n, (_) => Random.secure().nextInt(256)));

/// Signs the user in. Returns access_token, refresh_token and user, or throws if they cancel.
Future<Map<String, dynamic>?> signIn() async {
  final verifier = _random(32);
  final state = _random(16);
  final url = Uri.parse('$api/account/').replace(queryParameters: {
    'mode': 'authorize',
    'origin': site,
    'redirect_uri': '$scheme://auth',
    'state': state,
    'code_challenge': _b64(sha256.convert(utf8.encode(verifier)).bytes),
    'code_challenge_method': 'S256',
  });
  final result = await FlutterWebAuth2.authenticate(url: url.toString(), callbackUrlScheme: scheme);
  final back = Uri.parse(result).queryParameters;
  if (back['state'] != state || back['code'] == null) return null; // "Not now", or not our sign-in
  return token({'grant_type': 'authorization_code', 'code': back['code']!, 'code_verifier': verifier});
}

/// Also for refreshing: token({'grant_type': 'refresh_token', 'refresh_token': saved}).
/// Each refresh returns a new refresh_token: always keep the latest.
Future<Map<String, dynamic>> token(Map<String, String> body) async {
  final r = await http.post(Uri.parse('$api/v1/oauth/token'),
      headers: {'Content-Type': 'application/json'}, body: jsonEncode(body));
  final data = jsonDecode(r.body) as Map<String, dynamic>;
  if (r.statusCode != 200) throw Exception(data['error_description']);
  return data;
}

Future<Map<String, dynamic>> chat(String accessToken, List<Map<String, String>> messages) async {
  final r = await http.post(Uri.parse('$api/v1/chat/completions'),
      headers: {'Authorization': 'Bearer $accessToken', 'Content-Type': 'application/json'},
      body: jsonEncode({'model': 'standard', 'messages': messages}));
  return jsonDecode(r.body) as Map<String, dynamic>; // 401: refresh, then try again
}

Good to know

  • A refresh token works once. Sending an old one again ends that sign-in, in case it was copied, and the user signs in again.
  • invalid_grant when refreshing means the user disconnected your app in their account, or the sign-in ended. Sign them in again.
  • insufficient_balance (402): open https://api.chargemyai.com/account/ with WebBrowser.openBrowserAsync or a Custom Tab so they can top up by UPI. abroad_not_allowed: sign in again with need=abroad added to the address.
  • Use the system browser, not a WebView. Google refuses sign-in inside WebViews, and in the system browser users see they are on ChargeMyAI's address.
  • Only your site's own pages and the addresses you added under App sign-in can receive a code. A link with any other redirect_uri is refused before the user signs in.
  • Web pages need none of this, even inside WhatsApp or Instagram: when an in-app browser can't open the sign-in window, charge.js signs in on the same page and comes back with a code.

Read next

Still stuck? Talk to us and we'll help.