How to Use DecodeHash Free API

Learn how to decode Mpesa hashes using our Free API.

Introduction

Welcome to the DecodeHash Free API user guide.

Whether you're a developer integrating Mpesa hash decoding into your application, an analyst exploring how to decode hashed MSISDN, or simply curious about how the process works, this guide will provide you with step-by-step instructions for effective API usage.

Decoding M-Pesa Till or Paybill Customer Numbers

When receiving payments to your M-Pesa till or paybill, Safaricom now provides a hashed version of the customer's phone number instead of the actual number. To decode or reveal the customer number from these mpesa till or paybill transactions, our Free API can help. You can easily query the original phone number by providing the hash from the transaction notification.

(Please note: If you integrate your till or paybill directly with our portal, manual decoding is unnecessary. Our system automatically handles the decoding of customer phone numbers for you.)

Getting Started

DecodeHash's Free API offers a simple and efficient way to decode Mpesa hashes.

Follow the steps below to get started decoding Mpesa hashes today!

Here's how to start using the Free API to decode Mpesa hashes:

  1. On Windows, you can use the command shell and execute the following command: curl -X GET "https://decodehash.com/app/api/v1/decode-hash/free/some-sha-hash" -H "Accept: application/json"
  2. In Windows, you can use powershell to execute the following command: Invoke-RestMethod -Uri "https://decodehash.com/app/api/v1/decode-hash/free/some-sha-hash" -Headers @{"Accept" = "application/json"}
  3. In macOs or Linux, you can use the terminal to execute the following command: curl -X GET "https://decodehash.com/app/api/v1/decode-hash/free/some-sha-hash" -H "Accept: application/json"
  4. In Postman, you can decode the MSISDN using the following steps:
    • Create a new GET request.
    • Enter the URL as https://decodehash.com/app/api/v1/decode-hash/free/some-sha-hash
    • Click on Headers tab and add the following headers:
      • Key: Accept
      • Value: application/json
    • Click Send.

Examples for Developers

Below are examples of sending a request to the API in various popular languages:


                  curl -X GET "https://decodehash.com/app/api/v1/decode-hash/free/some-sha-hash" \
                  -H "Accept: application/json"
                  

                import requests
                from typing import Optional
                from pydantic import BaseModel

                class DecodeHashResponseModel(BaseModel):
                    msisdn: Optional[str] = None
                    hash: Optional[str] = None
                    success: Optional[bool] = False
                    detail: Optional[str] = None

                SERVER = "https://decodehash.com"
                DECODEHASH_END_POINT = "/app/api/v1/decode-hash/free/"

                def get_msisdn(hash_str: str) -> DecodeHashResponseModel:
                    url = f"{SERVER}{DECODEHASH_END_POINT}{hash_str}"
                    headers = {"Accept": "application/json"}

                    try:
                        response = requests.get(url, headers=headers)

                        data = response.json()

                        decode_hash_response_model = DecodeHashResponseModel(
                            detail=data.get("detail"),
                            msisdn=data.get("msisdn"),
                            hash=data.get("hash"),
                            success=("msisdn" in data)  # Determine success based on available data
                        )

                        return decode_hash_response_model

                    except requests.exceptions.RequestException as e:
                        print(f"Error fetching data: {e}")
                        return DecodeHashResponseModel(success=False)

                    except json.JSONDecodeError as e:
                        print(f"Error decoding JSON: {e}")
                        return DecodeHashResponseModel(success=False)

                # Test the function
                if __name__ == "__main__":
                    hash_str = "some-sha-hash"
                    get_msisdn_response = get_msisdn(hash_str)
                    print(f"Response model: {get_msisdn_response}")
                  

                  const axios = require('axios');

                  class DecodeHashResponseModel {
                      constructor(msisdn = null, hash = null, success = false, detail = null) {
                          this.msisdn = msisdn;
                          this.hash = hash;
                          this.success = success;
                          this.detail = detail;
                      }
                  }

                  const SERVER = "https://decodehash.com";
                  const DECODEHASH_END_POINT = "/app/api/v1/decode-hash/free/";

                  async function getMsisdn(hashStr) {
                      const url = `${SERVER}${DECODEHASH_END_POINT}${hashStr}`;
                      const headers = { "Accept": "application/json" };

                      try {
                          const response = await axios.get(url, { headers });
                          const data = response.data;

                          const decodeHashResponseModel = new DecodeHashResponseModel(
                              data.msisdn,
                              data.hash,
                              "msisdn" in data,  // Determine success based on available data
                              data.detail
                          );

                          return decodeHashResponseModel;

                      } catch (error) {
                          console.error(`Error fetching data: ${error}`);
                          return new DecodeHashResponseModel();
                      }
                  }

                  // Test the function
                  (async () => {
                      const hashStr = "some-sha-hash";
                      const getMsisdnResponse = await getMsisdn(hashStr);
                      console.log(`Response model: ${JSON.stringify(getMsisdnResponse)}`);
                  })();

                    

                package main

                import (
                  "encoding/json"
                  "fmt"
                  "net/http"
                  "time"
                )

                type DecodeHashResponseModel struct {
                  Msisdn  *string `json:"msisdn"`
                  Hash    *string `json:"hash"`
                  Success bool    `json:"success"`
                  Detail  *string `json:"detail"`
                }

                const (
                  Server = "https://decodehash.com"
                  DecodeHashEndPoint = "/app/api/v1/decode-hash/free/"
                )

                func getMsisdn(hashStr string) DecodeHashResponseModel {
                  url := Server + DecodeHashEndPoint + hashStr
                  client := &http.Client{Timeout: 10 * time.Second}
                  req, err := http.NewRequest("GET", url, nil)
                  if err != nil {
                    fmt.Printf("Error creating request: %v\n", err)
                    return DecodeHashResponseModel{Success: false}
                  }

                  req.Header.Set("Accept", "application/json")

                  resp, err := client.Do(req)
                  if err != nil {
                    fmt.Printf("Error fetching data: %v\n", err)
                    return DecodeHashResponseModel{Success: false}
                  }
                  defer resp.Body.Close()

                  var data map[string]interface{}
                  if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
                    fmt.Printf("Error decoding JSON: %v\n", err)
                    return DecodeHashResponseModel{Success: false}
                  }

                  msisdn, _ := data["msisdn"].(string)
                  hash, _ := data["hash"].(string)
                  detail, _ := data["detail"].(string)
                  success := msisdn != ""

                  return DecodeHashResponseModel{
                    Msisdn:  &msisdn,
                    Hash:    &hash,
                    Success: success,
                    Detail:  &detail,
                  }
                }

                func main() {
                  hashStr := "some-sha-hash"
                  getMsisdnResponse := getMsisdn(hashStr)
                  responseJSON, _ := json.MarshalIndent(getMsisdnResponse, "", "  ")
                  fmt.Printf("Response model: %s\n", string(responseJSON))
                }

                  

Notes

The free API has a limit of 10 requests per day.

If you would like to increase your daily limit, please sign up for a free account.

Last updated 1 month ago

Was this article helpful?