Creating the app
Step-by-step creation of a Daraja sandbox app.
4. Step-by-Step Guide: Creating a Sandbox App
This section provides a detailed walkthrough of the process within the Daraja Developer Portal to create a functional sandbox application.
4.1. Navigation to "My Apps" / "Create New App"
Login to the Daraja Developer Portal: As described previously, go to
https://developer.safaricom.co.ke/and log in using your credentials.Access "My Apps": Once you're logged in, find the navigation menu. It's usually on the left side or at the top of the dashboard. Click on "My Apps."
Initiate New App Creation: On the "My Apps" page, you'll see a list of any applications you've already created. To make a new one, look for a prominent button labeled "Add New App," "Create New App," or something similar. Click this button.
UI Walkthrough: The "My Apps" page typically displays your applications in a table or list format. Each entry might show the app's name, when it was created, and its status (e.g., sandbox, production). The "Add New App" button is usually easy to spot, often colored differently or placed in a prominent location, such as the top-right corner of the application list.
💡 What is happening here: You start by logging into the Daraja Developer Portal, navigating to the "My Apps" section, and then clicking a button to begin creating a new application.
4.2. App Name and Description
After clicking "Add New App," a form will appear where you can define your new application. The first fields typically ask for an application name and a description.
App Name: This is a human-readable identifier for your application within the Daraja portal.
- Input: You can use a string of characters, usually alphanumeric, with some special characters allowed (like hyphens or underscores).
- Purpose: Its main purpose is to help you easily tell this application apart from others you might create. This is crucial for keeping things organized, especially if you manage many integrations.
- Best Practices:
- Descriptive: Choose a name that clearly indicates what the application does (e.g., "ECommerce_Sandbox_Payments," "Internal_Payroll_Test," "MobileApp_Dev_Env").
- Unique: While the portal might allow non-unique names, it's good practice to make them unique within your account to avoid confusion.
- Environment-Specific: Include "Sandbox" or "Dev" in the name to immediately identify its environment (e.g., "MyWebApp-Sandbox").
Description: This is an optional but highly recommended field where you can provide more context about the application.
- Input: A longer text string.
- Purpose: To explain more about the application's function, the project it belongs to, or any specific notes relevant to its use. This is particularly helpful when working in a team or revisiting an old project.
- Example: "Sandbox application for testing customer payments (STK Push, C2B) and refunds (B2C) for the new e-commerce platform v2.0."
💡 What is happening here: You give your new application a clear, descriptive name and an optional explanation. This helps you and your team understand its purpose and distinguish it from other applications.
4.3. Selecting APIs
This is a critical step where you define the specific Mpesa functionalities your application will be allowed to access. The Daraja portal typically presents a list of available APIs with checkboxes or toggle switches next to each. Selecting only the necessary APIs adheres to the principle of least privilege, a fundamental security concept that dictates a system or user should only be granted the minimum permissions required to perform its function.
Let's detail each core Mpesa API you might encounter and its purpose:
Mpesa Express (STK Push):
- What it is: Also known as STK Push (Sim Tool Kit Push), this API allows a business to initiate a payment request directly to a customer's mobile phone that is registered with Mpesa. The customer then receives a pop-up on their phone, asking them to enter their Mpesa PIN to complete the transaction.
- How it works: Your application sends a request to the Mpesa Express API. This request includes details like the customer's phone number, the amount to be paid, the business's shortcode (a unique number identifying the business), and a description of the transaction. Mpesa then sends a push notification to the customer's phone. Once the customer successfully enters their PIN, the transaction is completed, and a confirmation is sent to a callback URL you have configured.
- Use Cases: This is ideal for online shopping carts, paying utility bills, ride-hailing services, or any situation where a business wants to initiate a payment from a customer.
C2B (Customer to Business):
- What it is: This API makes it possible for customers to send payments from their Mpesa account directly to a business's Mpesa Paybill or Till Number. Unlike STK Push, the customer initiates the transaction themselves by going to the Mpesa menu on their phone, selecting "Lipa na Mpesa," and then choosing "Pay Bill" or "Buy Goods."
- How it works: The customer manually enters the business's Paybill/Till number, an account number (if required), and the amount. Mpesa then processes the payment. For businesses that want to receive real-time notifications about these payments, the C2B API provides a way to register a Validation URL (to accept or reject a transaction before it completes) and a Confirmation URL (to receive a notification after a transaction is successfully completed).
- Use Cases: This is commonly used by retail stores, supermarkets, schools, churches, and utility companies—essentially any business that receives payments initiated by the customer.
B2C (Business to Customer):
- What it is: This API allows a business to send funds from its Mpesa account to individual customer Mpesa accounts.
- How it works: Your application sends a request to the B2C API with details such as the customer's phone number, the amount, and a transaction description. The funds are then transferred from the business's Mpesa account to the customer's account. This API typically requires an Initiator Username and an encrypted Security Credential for authentication, as it involves money moving out of the business's account.
- Use Cases: This is used for salary payments, refunds, prize money disbursements, loan disbursements, and affiliate payouts.
- Security Implications: Because it involves disbursing funds, B2C transactions are highly sensitive. They require robust security measures, including strong authentication and often IP whitelisting (only allowing requests from specific, approved IP addresses) in a production environment.
B2B (Business to Business):
- What it is: This API facilitates payments from one business's Mpesa account to another business's Mpesa account. It is typically used for transfers between companies or payments to suppliers.
- How it works: Similar to B2C, your application sends a request containing the recipient business's shortcode, the amount, and other relevant details. It also requires an Initiator Username and Security Credential.
- Use Cases: This is used for supplier payments, transfers between different branches of a company, or payments to distributors and partners.
Account Balance:
- What it is: This API allows your application to check the current Mpesa balance of a specified business shortcode (either a Paybill or Till Number).
- How it works: Your application sends a request with the business shortcode. The API then returns the current available balance. This API also requires an Initiator Username and Security Credential.
- Use Cases: This is useful for monitoring a business's Mpesa account liquidity, reconciling financial records, or triggering alerts when balances fall below a certain threshold.
Transaction Status:
- What it is: This API allows your application to check the status of a specific Mpesa transaction (such as an STK Push, C2B, B2C, or B2B transaction) using its unique transaction ID.
- How it works: Your application sends a request with the transaction ID. The API then returns detailed information about the transaction, including its current status (e.g., completed, pending, failed). This API also requires an Initiator Username and Security Credential.
- Use Cases: This is crucial for reconciling transactions, providing customer support, handling delayed confirmations, and verifying if a payment was successful.
Reversal:
- What it is: This API enables a business to reverse a previously completed Mpesa transaction. This is typically used in situations involving erroneous payments or customer disputes.
- How it works: Your application sends a request with the original transaction ID and the amount to be reversed. The funds are then returned to the sender of the original transaction. This API also requires an Initiator Username and Security Credential.
- Use Cases: This is used for correcting mistaken payments or processing refunds for returned goods (if the original payment was C2B/STK Push).
- Operational Considerations: Reversals are sensitive operations and often have time limits or require specific conditions to be met.
Register URL (for C2B):
- What it is: This API is specifically for configuring the callback URLs for C2B transactions. It tells Mpesa where to send validation and confirmation messages for payments made to your Paybill/Till number.
- How it works: Your application sends a request specifying your Validation URL (where Mpesa sends a request before completing a C2B transaction, allowing your system to accept or reject it) and your Confirmation URL (where Mpesa sends a notification after a C2B transaction is successfully completed).
- Importance of Secure Callbacks: These URLs must be publicly accessible and secured with HTTPS (Hypertext Transfer Protocol Secure). They are critical for your application to receive real-time updates on incoming payments.
💡 What is happening here: You choose which Mpesa services your application needs, like accepting payments or sending money. Each service has specific requirements, and selecting only what's necessary improves security by limiting what your application can do.
Why Select Specific APIs?
- Security: Limiting API access reduces the attack surface. If an application's credentials are compromised, an attacker can only access the functionalities that have been explicitly enabled.
- Clarity: Selecting specific APIs makes it clear exactly what the application is designed to do.
- Performance (Indirect): While not directly impacting API call performance, a leaner application with fewer enabled features might be simpler to manage and secure, which indirectly contributes to overall system stability.
UI Walkthrough: The API selection section typically presents a list of API names, each with a checkbox next to it. You simply click the checkbox for every API your application will use. For a basic e-commerce setup, you would likely select Mpesa Express, C2B, B2C, Transaction Status, and potentially Reversal.
4.4. Generating Sandbox Credentials
After you have named your application and selected the APIs it will use, the Daraja portal will either generate or prompt you to generate the necessary credentials. These credentials are unique to your sandbox application and are completely separate from any production credentials.
Consumer Key:
- What it is: This is a unique identifier for your application. It is publicly visible in the sense that it's part of every API request, but its purpose is to identify your specific application to the Daraja platform.
- Purpose: It is used together with the Consumer Secret to obtain an OAuth 2.0 Access Token. It tells the Daraja authentication server which client (your application) is requesting a token.
- Format: Typically a long alphanumeric string.
Consumer Secret:
- What it is: This is a confidential string that acts like a password for your application. It must be kept absolutely secret and should never be exposed in client-side code, public code repositories, or insecure communication channels.
- Purpose: It is used with the Consumer Key to authenticate your application and obtain an OAuth 2.0 Access Token. The Daraja server verifies that the provided Consumer Secret matches the one associated with the Consumer Key.
- Format: Typically a long alphanumeric string.
Passkey (for STK Push - Mpesa Express):
- What it is: This is a unique key specifically used in conjunction with the Mpesa Express (STK Push) API. It serves as a security measure to ensure that only authorized applications can initiate STK Push requests.
- Purpose: The Passkey is not sent directly in the API request. Instead, it is combined with the business shortcode and a timestamp, then encoded using Base64 to form the
Passwordparameter in the STK Push request. This dynamic password generation adds an extra layer of security, making it harder for unauthorized parties to forge STK Push requests. - Format: Typically a long alphanumeric string.
Shortcode (Paybill/Till Number):
- What it is: In the sandbox environment, Safaricom provides specific test shortcodes (Paybill or Till Numbers) that you can use for simulating transactions. These are not real-world shortcodes.
- Purpose: To identify the business account involved in a transaction. For C2B, it's the number customers pay to. For STK Push, B2C, B2B, Account Balance, Transaction Status, and Reversal, it identifies the business initiating or receiving funds.
- Sandbox Example: Common sandbox shortcodes include
600999(for Paybill) or174379(for STK Push, which is also a Paybill number). The portal will typically display the sandbox shortcode(s) associated with your application.
Initiator Username and Security Credential (for B2C/B2B/Reversal/Account Balance/Transaction Status):
- What they are: These are required for APIs that involve the business initiating a transaction that moves funds out of its account (B2C, B2B, Reversal) or querying sensitive account information (Account Balance, Transaction Status).
- Initiator Username: A username linked to the business's Mpesa account that is authorized to perform these specific operations.
- Security Credential: An encrypted string that represents the password for the Initiator Username. This password is encrypted using a public key provided by Safaricom, ensuring it is transmitted securely.
- Purpose: To provide an additional layer of authentication and authorization for sensitive outbound transactions. It ensures that only authorized personnel or systems within the business can initiate these types of operations.
- How to Generate the Encrypted Security Credential: This is a multi-step process:
- Obtain Safaricom's Public Certificate: Safaricom provides a specific public key certificate (e.g., a
.cerfile) that is used for encrypting the Initiator password. This certificate is specific to the environment (sandbox vs. production). - Encrypt the Initiator Password: Using a cryptographic library (e.g., OpenSSL, Java Cryptography Architecture, Python's
cryptographylibrary), the Initiator password is encrypted using Safaricom's public key. The encryption algorithm is typically RSA with OAEP padding. - Base64 Encode: The resulting encrypted binary data is then encoded using Base64 to produce a string that can be safely transmitted in JSON or XML requests.
- Obtain Safaricom's Public Certificate: Safaricom provides a specific public key certificate (e.g., a
- Sandbox Specifics: For the sandbox, you will typically use a test Initiator Username (e.g.,
testapi) and a simple password (e.g.,Safaricom999!). You will need to download the sandbox public certificate from the Daraja portal or documentation to perform the encryption.
- What they are: These are required for APIs that involve the business initiating a transaction that moves funds out of its account (B2C, B2B, Reversal) or querying sensitive account information (Account Balance, Transaction Status).
💡 What is happening here: The portal generates unique keys and identifiers for your application. These include a Consumer Key and Secret for general access, a Passkey for STK Push, and an Initiator Username/Security Credential for sensitive transactions like sending money. These are all crucial for your application to securely communicate with Mpesa.
Relationship between Credentials and OAuth 2.0:
The Consumer Key and Consumer Secret are the primary credentials used to obtain an Access Token through the OAuth 2.0 Client Credentials Grant flow. This Access Token is a bearer token, meaning anyone who possesses it can use it, and it grants temporary access to the Mpesa APIs. All subsequent API calls (e.g., STK Push, C2B, B2C) will include this Access Token in the Authorization header (e.g., Authorization: Bearer <access_token>). The other credentials (Passkey, Initiator Username, Security Credential) are then used within the data payload of specific API requests for their respective functionalities, providing an additional layer of transaction-specific security.
UI Walkthrough: After selecting APIs and clicking "Create App" (or a similar button), the portal will display a summary page for your new application. This page will prominently feature the generated Consumer Key and Consumer Secret. It will also list the sandbox shortcodes and provide instructions or links to download the sandbox public certificate for encrypting the Initiator password. It is crucial to copy and securely store the Consumer Secret immediately, as it is often shown only once and cannot be retrieved later. If lost, it must be regenerated.
4.5. Viewing and Managing App Details
Once the sandbox application is created, you will be redirected to its detail page or back to the "My Apps" list.
Dashboard View of the Newly Created App:
- Clicking on the app name from the "My Apps" list will take you to its dedicated dashboard.
- This page typically displays:
- The App Name and Description.
- The Consumer Key (often partially hidden for security).
- An option to reveal or copy the Consumer Secret (if it's still available, or to regenerate it).
- A list of the APIs you enabled for this application.
- The Sandbox Shortcodes.
- Links to download necessary certificates.
- Usage statistics (primarily for production applications).
- Options to edit the app's details or delete the app.
How to Retrieve Credentials Later:
- The Consumer Key is usually always visible on the app's detail page.
- The Consumer Secret is often only shown once immediately after creation. If you lose it, you will need to regenerate it. Regenerating a secret invalidates the old one, meaning any applications using the old secret will stop working until they are updated with the new one.
- Passkeys and Initiator details are typically displayed on the app's detail page.
Options for Regenerating Keys:
- The Daraja portal provides buttons or links such as "Regenerate Consumer Secret" or "Regenerate Passkey."
- Why regenerate?
- Security Compromise: If you suspect your secret key has been exposed or compromised.
- Security Policy: Many organizations have policies that require periodic key rotation.
- Loss: If you failed to save the secret when it was first displayed.
- Impact of Regeneration: Regenerating a key immediately invalidates the previous key. Any running application using the old key will fail to authenticate until it is updated with the new key. This requires careful coordination, especially in production environments. In a sandbox, the impact is minimal, but it's good practice to understand the implications.
💡 What is happening here: After creating your app, you can view all its details and credentials on its dedicated dashboard. It's crucial to securely save your Consumer Secret immediately, as it's often shown only once. You can also regenerate keys if needed, but this will invalidate old keys.