Token client
By the end of this track you can write a small service that charges, stores every event and notifies your app.
0/6 finished
Step 1
The idea
A gateway is a small service between your apps and Daraja: apps ask it to charge, it talks to Daraja, stores every event and tells apps the final result. You write it yourself, in your language, in the sandbox. It needs Foundations and Callbacks first. Start with a function that returns a cached token and refreshes it before expiry or on a 401. Keys come from environment variables, and nothing is printed.
Step 2
How it works
The shape of the gateway
Your apps call the gateway; only the gateway calls Daraja. Over six lessons you build its four parts: a token client, a charge endpoint, a callback receiver and a status job, plus notifications back to your apps.
This step
Reuse what you learned in F3: one function, get_token(), that returns a cached token, refreshes it a minute before expiry, and can be told to drop it after a 401. Keys come from environment variables.
Test it
Count outgoing HTTP requests: two calls in a row should make only one.
calls = 0# wrap your HTTP client so each OAuth request does calls += 1get_token(); get_token()assert calls == 1Step 3
Common mistakes
- Printing the token while debugging and leaving it in.
- A cache per request instead of per process.
Go deeper
How do you know the cache works?
Answer in your own words first.
Show the answerHide the answer
Two calls in a row make one HTTP request.