Handles OAuth 2.0 authentication with the Daraja API.
Cached vs uncached tokens
Use get_token/1 for the recommended entry point. It returns a cached token
when Daraja.TokenCache is running, and falls back to a fresh network fetch
otherwise:
client = Daraja.Client.new()
{:ok, token} = Daraja.Auth.get_token(client)Add Daraja.Supervisor to your application's supervision tree to enable
caching:
children = [
{Daraja.Supervisor, []}
]fetch_token/1 always hits the network and is unaffected by the cache.
Umbrella apps / custom cache names
get_token/1 looks up the cache registered as Daraja.TokenCache by
default. To use a cache started under a custom name, set the config key:
config :daraja, token_cache: :billing_cacheThe :token_cache value must be an atom. Omit the key entirely to use the
default Daraja.TokenCache.
Summary
Functions
Fetches a fresh access token for the given client.
Returns a cached access token when Daraja.TokenCache is running; otherwise
fetches a fresh one from the network.
Types
@type token_info() :: %{access_token: String.t(), expires_in: pos_integer()}
Functions
@spec fetch_token(Daraja.Client.t()) :: {:ok, String.t()} | {:error, :auth_failed, term()} | {:error, :http_error, term()}
Fetches a fresh access token for the given client.
Encodes the client's Consumer Key and Consumer Secret as a Basic Auth
credential and requests a client_credentials token from the Daraja
Authorization API. Every call hits the network.
Returns
{:ok, token}— a valid access token string.{:error, :auth_failed, %Daraja.APIError{}}— the request completed but credentials were rejected or the response body could not be parsed.{:error, :http_error, reason}— a network or transport-level failure.
@spec get_token(Daraja.Client.t()) :: {:ok, String.t()} | {:error, :auth_failed, term()} | {:error, :http_error, term()}
Returns a cached access token when Daraja.TokenCache is running; otherwise
fetches a fresh one from the network.
The cache name is read from Application.get_env(:daraja, :token_cache, Daraja.TokenCache). The config value must be an atom; omit the key to use
the default Daraja.TokenCache.
Returns
{:ok, token}— a valid access token string.{:error, :auth_failed, %Daraja.APIError{}}— credentials were rejected or the response body could not be parsed.{:error, :http_error, reason}— a network or transport-level failure.