MonCash /oauth/token returns 401 invalid_client — how do I call it correctly?

poze 5 months ago123 gadeen

7

I have my client_id and client_secret from the MonCash business portal, but every call to get an access token fails with 401 and invalid_client. I'm sending the credentials as JSON in the body. What am I doing wrong?

Anviwònman:Node.js 20Express

Dyagnostik IA

Se IA ki fè l. Se pa yon repons — kominote a anba a konfime oswa korije l. Toujou verifye anvan ou fye l.

2 Repons

9
✓
✓ Repons yo aksepte

The token endpoint is a standard OAuth2 client-credentials call. It does not take JSON:

  • Credentials go in an HTTP Basic Authorization header: base64(client_id:client_secret).
  • The body is form-encoded: scope=read,write&grant_type=client_credentials.
const BASE = process.env.MONCASH_API_BASE!; // sandbox: https://sandbox.moncashbutton.digicelgroup.com/Api
 
export async function getMonCashToken(): Promise<string> {
  const basic = Buffer.from(
    process.env.MONCASH_CLIENT_ID + ":" + process.env.MONCASH_CLIENT_SECRET,
  ).toString("base64");
 
  const res = await fetch(BASE + "/oauth/token", {
    method: "POST",
    headers: {
      Authorization: "Basic " + basic,
      "Content-Type": "application/x-www-form-urlencoded",
      Accept: "application/json",
    },
    body: "scope=read,write&grant_type=client_credentials",
  });
  if (!res.ok) throw new Error("MonCash token failed: " + res.status + " " + (await res.text()));
  const json = await res.json();
  return json.access_token;
}

Other causes of invalid_client:

  1. Sandbox credentials against the live host, or the reverse. Each environment has its own keys.
  2. Stray whitespace or a newline in the .env value, from copy-pasting out of the portal. Trim it.
  3. The wrong header scheme: it's Basic for this call, and Bearer <access_token> for every call after it.

Keep this call on your server. The secret must never reach a browser or a mobile app.

Konekte pou di lòt moun si li te mache.

answered 5 months ago
0

Same error here with PHP. My problem was http_build_query producing scope=read%2Cwrite. That's actually fine, but I had also set CURLOPT_POSTFIELDS to an array, which makes cURL send multipart/form-data. Passing the string "scope=read,write&grant_type=client_credentials" fixed it.

Konekte pou di lòt moun si li te mache.

answered 5 months ago

Sign in and verify your email to post an answer.