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.
- 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.
- 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'sschemein app.json, orCFBundleURLSchemesand an Android intent filter). - 3Make a random code verifier and its SHA-256 challenge, then open
https://api.chargemyai.com/account/?mode=authorizewithorigin(your site),redirect_uri,state,code_challengeandcode_challenge_method=S256. - 4The user signs in, picks your app's daily limit and comes back to
yourapp://auth?code=…&state=…. Check thatstateis the one you sent. - 5POST the code and the verifier to
https://api.chargemyai.com/v1/oauth/token. You getaccess_token,refresh_tokenanduser. Keep both tokens in the Keychain or Keystore. - 6Use
access_tokenas the API key for/v1/chat/completions, like an OpenAI key. It lasts 7 days; when a call returns 401, traderefresh_tokenfor 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_grantwhen refreshing means the user disconnected your app in their account, or the sign-in ended. Sign them in again.insufficient_balance(402): openhttps://api.chargemyai.com/account/withWebBrowser.openBrowserAsyncor a Custom Tab so they can top up by UPI.abroad_not_allowed: sign in again withneed=abroadadded 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_uriis 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
PreviousLovable, Bolt, v0, Replit and Cursor NextKeep your AI code: OpenAI SDK, Vercel AI SDK, LangChain
Still stuck? Talk to us and we'll help.