Exchange the Code
Turn the one-time authorization code into the connected business's account ID.
Exchange the Code
POST /v1/connect/oauth/token
Call this from your server after the redirect, with your own secret key. It returns the account_id you use for every call on the business's behalf.
The key's mode must match the client ID's mode: sk_test_ with cp_test_, sk_live_ with cp_live_.
Request
Nothing NestJS-specific here — this is the same Node.js client call.
Nothing Django-specific here — this is the same Python client call.
Nothing Flask-specific here — this is the same Python client call.
Nothing FastAPI-specific here — this is the same Python client call.
Nothing Laravel-specific here — this is the same PHP client call.
Nothing Spring Boot-specific here — this is the same Java client call.
curl https://api.e-pay.et/v1/connect/oauth/token \
-X POST \
-H "Authorization: Bearer sk_test_your_key_here" \
-H "Content-Type: application/json" \
-d '{
"grant_type": "authorization_code",
"client_id": "cp_test_your_client_id",
"code": "4f9c2e…",
"redirect_uri": "https://app.example.com/epay/callback",
"code_verifier": "the_verifier_you_stored"
}'app.get('/epay/callback', async (req, res) => {
const saved = req.session.epay;
if (!saved || req.query.state !== saved.state) {
return res.status(400).send('State mismatch');
}
if (req.query.error) return res.redirect('/settings?epay=cancelled');
const r = await fetch('https://api.e-pay.et/v1/connect/oauth/token', {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.EPAY_SECRET_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
grant_type: 'authorization_code',
client_id: process.env.EPAY_CLIENT_ID,
code: req.query.code,
redirect_uri: 'https://app.example.com/epay/callback',
code_verifier: saved.verifier,
}),
});
if (!r.ok) throw new Error(`ePay ${r.status}: ${await r.text()}`);
const { data } = await r.json();
await saveConnectedAccount(req.user.id, data.account_id); // acct_…
res.redirect('/settings?epay=connected');
});import os
import requests
from flask import abort, redirect, request, session
@app.get("/epay/callback")
def epay_callback():
saved = session.pop("epay", None)
if not saved or request.args.get("state") != saved["state"]:
abort(400)
if request.args.get("error"):
return redirect("/settings?epay=cancelled")
res = requests.post(
"https://api.e-pay.et/v1/connect/oauth/token",
headers={"Authorization": f"Bearer {os.environ['EPAY_SECRET_KEY']}"},
json={
"grant_type": "authorization_code",
"client_id": os.environ["EPAY_CLIENT_ID"],
"code": request.args["code"],
"redirect_uri": "https://app.example.com/epay/callback",
"code_verifier": saved["verifier"],
},
timeout=30,
)
res.raise_for_status()
account = res.json()["data"]
save_connected_account(current_user.id, account["account_id"]) # acct_…
return redirect("/settings?epay=connected")session_start();
$saved = $_SESSION['epay'] ?? null;
unset($_SESSION['epay']);
if (!$saved || ($_GET['state'] ?? '') !== $saved['state']) {
http_response_code(400);
exit('State mismatch');
}
$ch = curl_init('https://api.e-pay.et/v1/connect/oauth/token');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . getenv('EPAY_SECRET_KEY'),
'Content-Type: application/json',
],
CURLOPT_POSTFIELDS => json_encode([
'grant_type' => 'authorization_code',
'client_id' => getenv('EPAY_CLIENT_ID'),
'code' => $_GET['code'],
'redirect_uri' => 'https://app.example.com/epay/callback',
'code_verifier' => $saved['verifier'],
]),
]);
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);
if ($status !== 200) throw new RuntimeException("ePay {$status}: {$body}");
$account = json_decode($body, true)['data'];
save_connected_account($userId, $account['account_id']); // acct_…body, _ := json.Marshal(map[string]string{
"grant_type": "authorization_code",
"client_id": os.Getenv("EPAY_CLIENT_ID"),
"code": r.URL.Query().Get("code"),
"redirect_uri": "https://app.example.com/epay/callback",
"code_verifier": saved["verifier"], // after checking state
})
req, _ := http.NewRequestWithContext(ctx, http.MethodPost,
"https://api.e-pay.et/v1/connect/oauth/token", bytes.NewReader(body))
req.Header.Set("Authorization", "Bearer "+os.Getenv("EPAY_SECRET_KEY"))
req.Header.Set("Content-Type", "application/json")
res, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
return fmt.Errorf("ePay %d", res.StatusCode)
}
var out struct {
Data struct {
AccountID string `json:"account_id"`
Scope string `json:"scope"`
Status string `json:"status"`
} `json:"data"`
}
if err := json.NewDecoder(res.Body).Decode(&out); err != nil {
return err
}
return saveConnectedAccount(userID, out.Data.AccountID) // acct_…String json = """
{
"grant_type": "authorization_code",
"client_id": "%s",
"code": "%s",
"redirect_uri": "https://app.example.com/epay/callback",
"code_verifier": "%s"
}""".formatted(System.getenv("EPAY_CLIENT_ID"), code, savedVerifier);
HttpRequest request = HttpRequest.newBuilder(
URI.create("https://api.e-pay.et/v1/connect/oauth/token"))
.header("Authorization", "Bearer " + System.getenv("EPAY_SECRET_KEY"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(json))
.build();
HttpResponse<String> response =
HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() != 200) {
throw new IllegalStateException("ePay " + response.statusCode() + ": " + response.body());
}
// Parse data.account_id with your JSON library and store it.Node.js SDK support is coming soon. Switch to for a working example in Node.js today.
Python SDK support is coming soon. Switch to for a working example in Python today.
PHP SDK support is coming soon. Switch to for a working example in PHP today.
Java SDK support is coming soon. Switch to for a working example in Java today.
Go SDK support is coming soon. Switch to for a working example in Go today.
Body Parameters
Prop
Type
Response
Returns 200 OK.
{
"status": "success",
"data": {
"account_id": "acct_9Kd2mQ7xL4pR8sT1",
"scope": "read_write",
"livemode": false,
"livemode_enabled": false,
"status": "active"
}
}Prop
Type
Errors
OAuth errors return 400 with an error code and a human-readable error_description:
{
"status": "error",
"data": {
"error": "invalid_grant",
"error_description": "The authorization code is invalid or expired"
}
}| Status | error / code | Cause |
|---|---|---|
400 | unsupported_grant_type | grant_type isn't authorization_code. |
400 | invalid_client | The client ID is unknown, belongs to another business, doesn't match the key's mode, or the app can't be used in this mode. |
400 | invalid_grant | The code is unknown, expired or already used, redirect_uri doesn't match, or code_verifier is wrong. |
403 | product_not_available | Your business isn't active and KYB-verified. |
403 | connect_disabled | Connect is turned off in this environment. |
Never retry a code that was already exchanged. Reusing a code revokes the connection it created (OAuth replay protection). Send the business through the authorize flow again instead.