openapi: 3.1.0
info:
  title: Daraja API (M-PESA)
  version: 0.2.0
  summary: An independent, sandbox-verified description of Safaricom's Daraja API.
  description: |
    An open, machine-readable description of Safaricom's Daraja API for M-PESA,
    written from Safaricom's public documentation and checked against the Daraja sandbox.

    This project is independent and is not made or endorsed by Safaricom. "M-PESA",
    "Daraja" and "Safaricom" are used only to say which API this describes.

    ## Verification
    Each operation carries `x-daraja-verified`: the date its contract tests last passed
    against the Daraja sandbox, or `null` if it has not been verified yet. Treat
    unverified operations as documentation, not fact.

    ## Callbacks
    Daraja reports the outcome of an M-PESA Express (STK Push) payment by POSTing to the
    `CallBackURL` you send. These callbacks are not signed. Confirm a payment with the STK
    Push Query before you deliver goods, or receive callbacks through a gateway that
    verifies and reconciles them.
  license:
    name: Apache 2.0
    identifier: Apache-2.0
  contact:
    name: daraja-openapi maintainers
    url: https://github.com/ByteGigs-Labs/daraja-openapi
  x-daraja-docs: https://developer.safaricom.co.ke/

servers:
  - url: https://sandbox.safaricom.co.ke
    description: Sandbox
  - url: https://api.safaricom.co.ke
    description: Production

tags:
  - name: Authorization
    description: Exchange your app's consumer key and secret for a short-lived access token.
  - name: M-PESA Express
    description: |
      Also called STK Push or Lipa na M-PESA Online. Sends a payment prompt to the
      customer's phone; the customer approves it with their M-PESA PIN.
  - name: C2B
    description: Receive payments customers start themselves, from the M-PESA menu or app.
  - name: B2C
    description: Pay customers from your shortcode.
  - name: B2B
    description: Pay other businesses.
  - name: Reversal
    description: Undo a payment your shortcode received.
  - name: Transaction Status
    description: Look up any M-PESA transaction involving your shortcode.
  - name: Account Balance
    description: Read your shortcode's balances.
  - name: Dynamic QR
    description: QR codes customers scan to pay you.

security:
  - bearerAuth: []

paths:
  /oauth/v1/generate:
    get:
      operationId: generateAccessToken
      tags: [Authorization]
      summary: Generate an access token
      description: |
        Returns a bearer token for the other Daraja APIs. Tokens last about one hour
        (`expires_in` is a string of seconds). Cache the token and reuse it until it is
        close to expiry instead of requesting one per call.
      x-daraja-verified: "2026-12-01"
      security:
        - basicAuth: []
      parameters:
        - name: grant_type
          in: query
          required: true
          schema:
            type: string
            enum: [client_credentials]
      responses:
        "200":
          description: A new access token.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/AccessToken"
              example:
                access_token: c9SQxWWhmdVRlyh0zh8gZDTkubVF
                expires_in: "3599"
        "400":
          $ref: "#/components/responses/ErrorResponse"
        "401":
          $ref: "#/components/responses/ErrorResponse"

  /mpesa/stkpush/v1/processrequest:
    post:
      operationId: stkPush
      tags: [M-PESA Express]
      summary: Send an STK Push payment prompt
      description: |
        Asks the customer to approve a payment on their phone. A `ResponseCode` of `"0"`
        means only that Daraja accepted the request; the payment result arrives later at
        your `CallBackURL`, or can be read with the STK Push Query.
      x-daraja-verified: "2026-12-01"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/StkPushRequest"
            example:
              BusinessShortCode: "174379"
              Password: MTc0Mzc5YmZiMjc5ZjlhYTliZGJjZjE1OGU5N2RkNzFhNDY3Y2QyZTBjODkzMDU5YjEwZjc4ZTZiNzJhZGExZWQyYzkxOTIwMjYxMTMwMTAxMDAw
              Timestamp: "20261130101000"
              TransactionType: CustomerPayBillOnline
              Amount: 1
              PartyA: "254708374149"
              PartyB: "174379"
              PhoneNumber: "254708374149"
              CallBackURL: https://example.com/mpesa/callback
              AccountReference: INV-1001
              TransactionDesc: Invoice 1001
      responses:
        "200":
          description: Daraja accepted the request and sent the prompt.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/StkPushResponse"
              example:
                MerchantRequestID: 29115-34620561-1
                CheckoutRequestID: ws_CO_30112026101000123708374149
                ResponseCode: "0"
                ResponseDescription: Success. Request accepted for processing
                CustomerMessage: Success. Request accepted for processing
        "400":
          $ref: "#/components/responses/ErrorResponse"
        "401":
          $ref: "#/components/responses/ErrorResponse"
        "429":
          $ref: "#/components/responses/RateLimited"
        "500":
          $ref: "#/components/responses/ErrorResponse"
      callbacks:
        stkResult:
          "{$request.body#/CallBackURL}":
            post:
              operationId: stkPushCallback
              summary: The payment result
              description: |
                Daraja POSTs the outcome to your `CallBackURL`. `ResultCode` 0 means the
                customer paid; any other value means the payment did not happen.
                `CallbackMetadata` is present only when the payment succeeded. Respond
                with HTTP 200 quickly; the callback is not signed and may be lost, so
                reconcile unconfirmed payments with the STK Push Query.
              requestBody:
                required: true
                content:
                  application/json:
                    schema:
                      $ref: "#/components/schemas/StkCallback"
                    examples:
                      paid:
                        summary: The customer paid
                        value:
                          Body:
                            stkCallback:
                              MerchantRequestID: 29115-34620561-1
                              CheckoutRequestID: ws_CO_30112026101000123708374149
                              ResultCode: 0
                              ResultDesc: The service request is processed successfully.
                              CallbackMetadata:
                                Item:
                                  - Name: Amount
                                    Value: 1
                                  - Name: MpesaReceiptNumber
                                    Value: TKU3XXXXXX
                                  - Name: Balance
                                  - Name: TransactionDate
                                    Value: 20261130101012
                                  - Name: PhoneNumber
                                    Value: 254708374149
                      cancelled:
                        summary: The customer cancelled
                        value:
                          Body:
                            stkCallback:
                              MerchantRequestID: 29115-34620561-1
                              CheckoutRequestID: ws_CO_30112026101000123708374149
                              ResultCode: 1032
                              ResultDesc: Request cancelled by user
              responses:
                "200":
                  description: Acknowledge the callback.

  /mpesa/stkpushquery/v1/query:
    post:
      operationId: stkPushQuery
      tags: [M-PESA Express]
      summary: Check the result of an STK Push
      description: |
        Returns the outcome of an STK Push. Use it to confirm a payment before you deliver,
        and to recover results whose callbacks never arrived. While the customer is still
        deciding, Daraja answers with an error (`errorCode` `500.001.1001`, "The
        transaction is being processed"); retry after a few seconds. Querying too
        often, or right after the push, returns HTTP 429: wait at least a few seconds
        before the first query and back off between queries.
      x-daraja-verified: "2026-12-01"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/StkPushQueryRequest"
            example:
              BusinessShortCode: "174379"
              Password: MTc0Mzc5YmZiMjc5ZjlhYTliZGJjZjE1OGU5N2RkNzFhNDY3Y2QyZTBjODkzMDU5YjEwZjc4ZTZiNzJhZGExZWQyYzkxOTIwMjYxMTMwMTAxMDAw
              Timestamp: "20261130101000"
              CheckoutRequestID: ws_CO_30112026101000123708374149
      responses:
        "200":
          description: The current result of the STK Push.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/StkPushQueryResponse"
              example:
                ResponseCode: "0"
                ResponseDescription: The service request has been accepted successsfully
                MerchantRequestID: 29115-34620561-1
                CheckoutRequestID: ws_CO_30112026101000123708374149
                ResultCode: "0"
                ResultDesc: The service request is processed successfully.
        "400":
          $ref: "#/components/responses/ErrorResponse"
        "401":
          $ref: "#/components/responses/ErrorResponse"
        "429":
          $ref: "#/components/responses/RateLimited"
        "500":
          $ref: "#/components/responses/ErrorResponse"

  /mpesa/c2b/v2/registerurl:
    post:
      operationId: c2bRegisterUrl
      tags: [C2B]
      summary: Register C2B confirmation and validation URLs
      description: |
        Tells M-PESA where to send customer payments made to your paybill or till
        from the M-PESA menu or app. Validation is off unless Safaricom enables it for
        your shortcode; `ResponseType` decides what happens if your validation URL
        does not answer. In production a shortcode's URLs can be registered once;
        changing them needs Safaricom's help. Daraja refuses URLs that contain words
        such as `mpesa`, `safaricom`, `exec`, `cmd` or `sql`, so keep them out of
        your paths. Daraja spells the response field `OriginatorCoversationID`,
        without the second "n".
      x-daraja-verified: "2026-12-01"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/C2bRegisterUrlRequest"
            example:
              ShortCode: "600984"
              ResponseType: Completed
              ConfirmationURL: https://example.com/payments/c2b/confirmation
              ValidationURL: https://example.com/payments/c2b/validation
      responses:
        "200":
          description: The URLs were registered.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/C2bRegisterUrlResponse"
              example:
                OriginatorCoversationID: 7619-37765134-1
                ResponseCode: "0"
                ResponseDescription: success
        "400":
          $ref: "#/components/responses/ErrorResponse"
        "401":
          $ref: "#/components/responses/ErrorResponse"
        "500":
          $ref: "#/components/responses/ErrorResponse"
      callbacks:
        c2bValidation:
          "{$request.body#/ValidationURL}":
            post:
              operationId: c2bValidationCallback
              summary: Accept or reject an incoming payment
              description: |
                Sent before M-PESA completes the payment, only if validation is enabled
                for your shortcode. Answer within a few seconds; `ResultCode` `"0"` accepts.
              requestBody:
                required: true
                content:
                  application/json:
                    schema:
                      $ref: "#/components/schemas/C2bTransaction"
              responses:
                "200":
                  description: Your decision.
                  content:
                    application/json:
                      schema:
                        $ref: "#/components/schemas/C2bValidationResponse"
                      example:
                        ResultCode: "0"
                        ResultDesc: Accepted
        c2bConfirmation:
          "{$request.body#/ConfirmationURL}":
            post:
              operationId: c2bConfirmationCallback
              summary: A completed customer payment
              description: |
                Sent after the customer has paid. The payment has already happened, so
                record it and answer HTTP 200. Like other Daraja callbacks it is not
                signed; confirm large amounts with the Transaction Status query.
              requestBody:
                required: true
                content:
                  application/json:
                    schema:
                      $ref: "#/components/schemas/C2bTransaction"
                    example:
                      TransactionType: Pay Bill
                      TransID: TKU3XXXXXX
                      TransTime: "20261201101500"
                      TransAmount: "250.00"
                      BusinessShortCode: "600984"
                      BillRefNumber: INV-1001
                      InvoiceNumber: ""
                      OrgAccountBalance: "49197.00"
                      ThirdPartyTransID: ""
                      MSISDN: 2547 ***** 149
                      FirstName: JOHN
              responses:
                "200":
                  description: Acknowledge the payment.

  /mpesa/c2b/v2/simulate:
    post:
      operationId: c2bSimulate
      tags: [C2B]
      summary: Simulate a customer payment (sandbox only)
      description: |
        Makes the sandbox send your confirmation (and validation) callbacks as if a
        customer had paid. Not available in production.
      x-daraja-verified: "2026-12-01"
      x-daraja-sandbox-only: true
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/C2bSimulateRequest"
            example:
              ShortCode: "600984"
              CommandID: CustomerPayBillOnline
              Amount: 250
              Msisdn: "254708374149"
              BillRefNumber: INV-1001
      responses:
        "200":
          description: The simulated payment was accepted.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/C2bRegisterUrlResponse"
              example:
                OriginatorCoversationID: 53e3-4aa8-9fe0-8fb5e4092cdd3405976
                ResponseCode: "0"
                ResponseDescription: Accept the service request successfully.
        "400":
          $ref: "#/components/responses/ErrorResponse"
        "401":
          $ref: "#/components/responses/ErrorResponse"
        "500":
          $ref: "#/components/responses/ErrorResponse"

  /mpesa/b2c/v3/paymentrequest:
    post:
      operationId: b2cPayment
      tags: [B2C]
      summary: Send money from your shortcode to a customer
      description: |
        Pays a customer's M-PESA account: salaries, refunds, winnings, loan
        disbursements. Needs a B2C shortcode and an API initiator. The result
        arrives later at `ResultURL`; a timeout at `QueueTimeOutURL`.
        `OriginatorConversationID` is yours: reuse it when retrying so you can match
        results and avoid paying twice.
      x-daraja-verified: "2026-12-01"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/B2cRequest"
            example:
              OriginatorConversationID: 6f2b8c1e-3c1d-4a8e-9a55-0d1bc7a2f001
              InitiatorName: testapi
              SecurityCredential: EsJocK7+NjqZPC3I3EO+TbvS+xVb9TymWwaKABoaZr/Z/n0UysSs..
              CommandID: BusinessPayment
              Amount: 100
              PartyA: "600996"
              PartyB: "254708374149"
              Remarks: Refund INV-1001
              QueueTimeOutURL: https://example.com/mpesa/b2c/timeout
              ResultURL: https://example.com/mpesa/b2c/result
              Occassion: Refund
      responses:
        "200":
          $ref: "#/components/responses/AsyncAccepted"
        "400":
          $ref: "#/components/responses/ErrorResponse"
        "401":
          $ref: "#/components/responses/ErrorResponse"
        "500":
          $ref: "#/components/responses/ErrorResponse"
      callbacks:
        result:
          $ref: "#/components/callbacks/AsyncResult"
        timeout:
          $ref: "#/components/callbacks/QueueTimeout"

  /mpesa/b2b/v1/paymentrequest:
    post:
      operationId: b2bPayment
      tags: [B2B]
      summary: Pay another business's paybill or till
      description: |
        Moves money from your shortcode to another business: a supplier's paybill
        (`BusinessPayBill`) or till (`BusinessBuyGoods`). The result arrives at
        `ResultURL`. Daraja spells `RecieverIdentifierType` this way.
      x-daraja-verified: "2026-12-01"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/B2bRequest"
            example:
              Initiator: testapi
              SecurityCredential: EsJocK7+NjqZPC3I3EO+TbvS+xVb9TymWwaKABoaZr/Z/n0UysSs..
              CommandID: BusinessPayBill
              SenderIdentifierType: "4"
              RecieverIdentifierType: "4"
              Amount: 1000
              PartyA: "600992"
              PartyB: "600000"
              AccountReference: SUP-2201
              Requester: "254708374149"
              Remarks: Stock for December
              QueueTimeOutURL: https://example.com/mpesa/b2b/timeout
              ResultURL: https://example.com/mpesa/b2b/result
      responses:
        "200":
          $ref: "#/components/responses/AsyncAccepted"
        "400":
          $ref: "#/components/responses/ErrorResponse"
        "401":
          $ref: "#/components/responses/ErrorResponse"
        "500":
          $ref: "#/components/responses/ErrorResponse"
      callbacks:
        result:
          $ref: "#/components/callbacks/AsyncResult"
        timeout:
          $ref: "#/components/callbacks/QueueTimeout"

  /mpesa/reversal/v1/request:
    post:
      operationId: reversal
      tags: [Reversal]
      summary: Reverse a customer payment
      description: |
        Asks M-PESA to reverse a payment your shortcode received, identified by its
        receipt (`TransactionID`). Only the full amount can be reversed. The result
        arrives at `ResultURL`.
      x-daraja-verified: "2026-12-01"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/ReversalRequest"
            example:
              Initiator: testapi
              SecurityCredential: EsJocK7+NjqZPC3I3EO+TbvS+xVb9TymWwaKABoaZr/Z/n0UysSs..
              CommandID: TransactionReversal
              TransactionID: TKU3XXXXXX
              Amount: 250
              ReceiverParty: "600984"
              RecieverIdentifierType: "11"
              ResultURL: https://example.com/mpesa/reversal/result
              QueueTimeOutURL: https://example.com/mpesa/reversal/timeout
              Remarks: Paid twice
      responses:
        "200":
          $ref: "#/components/responses/AsyncAccepted"
        "400":
          $ref: "#/components/responses/ErrorResponse"
        "401":
          $ref: "#/components/responses/ErrorResponse"
        "500":
          $ref: "#/components/responses/ErrorResponse"
      callbacks:
        result:
          $ref: "#/components/callbacks/AsyncResult"
        timeout:
          $ref: "#/components/callbacks/QueueTimeout"

  /mpesa/transactionstatus/v1/query:
    post:
      operationId: transactionStatus
      tags: [Transaction Status]
      summary: Look up an M-PESA transaction
      description: |
        Returns the details of a transaction by its receipt (`TransactionID`), or by
        `OriginatorConversationID` for a B2C payment whose receipt you never got. Use
        it to confirm C2B payments and to recover lost results. The answer arrives at
        `ResultURL`, not in the response.
      x-daraja-verified: "2026-12-01"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/TransactionStatusRequest"
            example:
              Initiator: testapi
              SecurityCredential: EsJocK7+NjqZPC3I3EO+TbvS+xVb9TymWwaKABoaZr/Z/n0UysSs..
              CommandID: TransactionStatusQuery
              TransactionID: TKU3XXXXXX
              PartyA: "600984"
              IdentifierType: "4"
              ResultURL: https://example.com/mpesa/status/result
              QueueTimeOutURL: https://example.com/mpesa/status/timeout
              Remarks: Confirm payment
      responses:
        "200":
          $ref: "#/components/responses/AsyncAccepted"
        "400":
          $ref: "#/components/responses/ErrorResponse"
        "401":
          $ref: "#/components/responses/ErrorResponse"
        "500":
          $ref: "#/components/responses/ErrorResponse"
      callbacks:
        result:
          $ref: "#/components/callbacks/AsyncResult"
        timeout:
          $ref: "#/components/callbacks/QueueTimeout"

  /mpesa/accountbalance/v1/query:
    post:
      operationId: accountBalance
      tags: [Account Balance]
      summary: Read your shortcode's balances
      description: |
        Requests the balances of your shortcode's accounts. They arrive at
        `ResultURL` in the `AccountBalance` result parameter, as
        `Name|Currency|Amount|Reserved|Uncleared|Locked` groups separated by `&`.
      x-daraja-verified: "2026-12-01"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/AccountBalanceRequest"
            example:
              Initiator: testapi
              SecurityCredential: EsJocK7+NjqZPC3I3EO+TbvS+xVb9TymWwaKABoaZr/Z/n0UysSs..
              CommandID: AccountBalance
              PartyA: "600984"
              IdentifierType: "4"
              Remarks: Daily balance
              QueueTimeOutURL: https://example.com/mpesa/balance/timeout
              ResultURL: https://example.com/mpesa/balance/result
      responses:
        "200":
          $ref: "#/components/responses/AsyncAccepted"
        "400":
          $ref: "#/components/responses/ErrorResponse"
        "401":
          $ref: "#/components/responses/ErrorResponse"
        "500":
          $ref: "#/components/responses/ErrorResponse"
      callbacks:
        result:
          $ref: "#/components/callbacks/AsyncResult"
        timeout:
          $ref: "#/components/callbacks/QueueTimeout"

  /mpesa/qrcode/v1/generate:
    post:
      operationId: dynamicQr
      tags: [Dynamic QR]
      summary: Generate an M-PESA payment QR code
      description: |
        Returns a QR code that customers scan in the M-PESA app to pay a fixed amount
        to your paybill, till, agent or phone number. `QRCode` is a base64 PNG.
      x-daraja-verified: "2026-12-01"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/DynamicQrRequest"
            example:
              MerchantName: Mama Mboga Online
              RefNo: INV-1001
              Amount: 250
              TrxCode: PB
              CPI: "174379"
              Size: "300"
      responses:
        "200":
          description: The QR code.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/DynamicQrResponse"
              example:
                ResponseCode: AG_20191219_000043fdf61864fe9ff5
                RequestID: "16738-27456357-1"
                ResponseDescription: QR Code Successfully Generated.
                QRCode: iVBORw0KGgoAAAANSUhEUgAAASwAAAEsAQAAAABRBrPYAAAD
        "400":
          $ref: "#/components/responses/ErrorResponse"
        "401":
          $ref: "#/components/responses/ErrorResponse"
        "500":
          $ref: "#/components/responses/ErrorResponse"

components:
  callbacks:
    AsyncResult:
      "{$request.body#/ResultURL}":
        post:
          operationId: asyncResultCallback
          summary: The result of a B2C, B2B, reversal, status or balance request
          description: |
            `ResultCode` 0 means the request succeeded. Details arrive as key/value
            pairs in `ResultParameters`, which is missing when the request failed.
            Not signed: match it to your request by `OriginatorConversationID` and
            `ConversationID`, and answer HTTP 200.
          requestBody:
            required: true
            content:
              application/json:
                schema:
                  $ref: "#/components/schemas/AsyncResult"
                example:
                  Result:
                    ResultType: 0
                    ResultCode: 0
                    ResultDesc: The service request is processed successfully.
                    OriginatorConversationID: 6f2b8c1e-3c1d-4a8e-9a55-0d1bc7a2f001
                    ConversationID: AG_20261201_2010325b025970fbc403
                    TransactionID: TKU3XXXXXX
                    ResultParameters:
                      ResultParameter:
                        - Key: TransactionAmount
                          Value: 100
                        - Key: TransactionReceipt
                          Value: TKU3XXXXXX
                        - Key: ReceiverPartyPublicName
                          Value: 254708374149 - John Doe
                    ReferenceData:
                      ReferenceItem:
                        Key: QueueTimeoutURL
                        Value: https://internalsandbox.safaricom.co.ke/mpesa/b2cresults/v1/submit
          responses:
            "200":
              description: Acknowledge the result.
    QueueTimeout:
      "{$request.body#/QueueTimeOutURL}":
        post:
          operationId: queueTimeoutCallback
          summary: The request timed out in M-PESA's queue
          description: |
            M-PESA could not process the request in time. Its outcome is unknown:
            check with the Transaction Status query before retrying a payment.
          requestBody:
            required: true
            content:
              application/json:
                schema:
                  $ref: "#/components/schemas/AsyncResult"
          responses:
            "200":
              description: Acknowledge the timeout.

  securitySchemes:
    basicAuth:
      type: http
      scheme: basic
      description: Your Daraja app's consumer key and consumer secret.
    bearerAuth:
      type: http
      scheme: bearer
      description: An access token from `GET /oauth/v1/generate`.

  responses:
    AsyncAccepted:
      description: |
        Daraja queued the request. This is not the outcome: that arrives at `ResultURL`.
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/AsyncAccepted"
          example:
            ConversationID: AG_20261201_2010325b025970fbc403
            OriginatorConversationID: 6f2b8c1e-3c1d-4a8e-9a55-0d1bc7a2f001
            ResponseCode: "0"
            ResponseDescription: Accept the service request successfully.
    RateLimited:
      description: |
        Daraja's gateway is rate-limiting this app. Observed in the sandbox for an STK Push
        Query sent seconds after the STK Push (2026-12-01). The body does not follow the
        usual error shape, so read the status code, wait, and retry with backoff.
      headers:
        Retry-After:
          description: Seconds to wait, when Daraja sends it.
          schema:
            type: string
    ErrorResponse:
      description: |
        Daraja rejected the request. An HTTP 401 with "Invalid API call as no apiproduct
        match found" means your Daraja app does not have this API product enabled:
        add it to the app on the Daraja portal, then request a new access token.
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
          example:
            requestId: 4788-2930614-1
            errorCode: "400.002.02"
            errorMessage: "Bad Request - Invalid BusinessShortCode"

  schemas:
    AccessToken:
      type: object
      required: [access_token, expires_in]
      properties:
        access_token:
          type: string
          description: Bearer token for the other Daraja APIs.
        expires_in:
          type: string
          pattern: "^[0-9]+$"
          description: Seconds until the token expires, as a string.

    Error:
      type: object
      required: [errorCode, errorMessage]
      properties:
        requestId:
          type: string
        errorCode:
          type: string
          description: Daraja's error code, for example `400.002.02` or `500.001.1001`.
        errorMessage:
          type: string

    ShortCode:
      type: string
      pattern: "^[0-9]{5,7}$"
      description: A paybill or till number.

    Msisdn:
      type: string
      pattern: "^254(7|1)[0-9]{8}$"
      description: A Kenyan mobile number in international format without the plus, e.g. `254708374149`.

    Timestamp:
      type: string
      pattern: "^[0-9]{14}$"
      description: The time of the request in Kenyan time (EAT), formatted `YYYYMMDDHHmmss`.

    StkPassword:
      type: string
      description: Base64 of `BusinessShortCode + Passkey + Timestamp`.

    StkPushRequest:
      type: object
      additionalProperties: false
      required:
        - BusinessShortCode
        - Password
        - Timestamp
        - TransactionType
        - Amount
        - PartyA
        - PartyB
        - PhoneNumber
        - CallBackURL
        - AccountReference
        - TransactionDesc
      properties:
        BusinessShortCode:
          $ref: "#/components/schemas/ShortCode"
        Password:
          $ref: "#/components/schemas/StkPassword"
        Timestamp:
          $ref: "#/components/schemas/Timestamp"
        TransactionType:
          type: string
          enum: [CustomerPayBillOnline, CustomerBuyGoodsOnline]
          description: "`CustomerPayBillOnline` for a paybill, `CustomerBuyGoodsOnline` for a till."
        Amount:
          type: integer
          minimum: 1
          description: Whole Kenyan shillings.
        PartyA:
          $ref: "#/components/schemas/Msisdn"
        PartyB:
          $ref: "#/components/schemas/ShortCode"
        PhoneNumber:
          $ref: "#/components/schemas/Msisdn"
        CallBackURL:
          type: string
          format: uri
          pattern: "^https://"
          description: The public HTTPS URL that receives the result.
        AccountReference:
          type: string
          minLength: 1
          maxLength: 12
          description: Shown to the customer as the account number. Up to 12 characters.
        TransactionDesc:
          type: string
          minLength: 1
          maxLength: 13
          description: A short note about the payment. Up to 13 characters.

    StkPushResponse:
      type: object
      required: [MerchantRequestID, CheckoutRequestID, ResponseCode, ResponseDescription]
      properties:
        MerchantRequestID:
          type: string
        CheckoutRequestID:
          type: string
          description: Identifies this payment in the callback and the STK Push Query.
        ResponseCode:
          type: string
          description: '"0" means Daraja accepted the request.'
        ResponseDescription:
          type: string
        CustomerMessage:
          type: string

    StkPushQueryRequest:
      type: object
      additionalProperties: false
      required: [BusinessShortCode, Password, Timestamp, CheckoutRequestID]
      properties:
        BusinessShortCode:
          $ref: "#/components/schemas/ShortCode"
        Password:
          $ref: "#/components/schemas/StkPassword"
        Timestamp:
          $ref: "#/components/schemas/Timestamp"
        CheckoutRequestID:
          type: string

    StkPushQueryResponse:
      type: object
      required: [ResponseCode, ResponseDescription, MerchantRequestID, CheckoutRequestID, ResultCode, ResultDesc]
      properties:
        ResponseCode:
          type: string
        ResponseDescription:
          type: string
        MerchantRequestID:
          type: string
        CheckoutRequestID:
          type: string
        ResultCode:
          type: string
          description: The payment result as a string. "0" means paid. See `StkResultCode`.
        ResultDesc:
          type: string

    StkResultCode:
      type: integer
      description: |
        Common results. Daraja may return others; treat any non-zero code as not paid.
        - `0` paid
        - `1` insufficient balance
        - `1001` another transaction is in progress for this customer
        - `1019` the prompt expired
        - `1025` / `9999` Daraja could not send the prompt
        - `1032` the customer cancelled
        - `1037` the customer's phone could not be reached, or they did not respond
        - `2001` the customer entered the wrong PIN

    CallbackItem:
      type: object
      required: [Name]
      properties:
        Name:
          type: string
          description: "`Amount`, `MpesaReceiptNumber`, `Balance`, `TransactionDate` or `PhoneNumber`."
        Value:
          oneOf:
            - type: string
            - type: number
          description: Missing for some items, such as `Balance`. `TransactionDate` and `PhoneNumber` arrive as numbers.

    StkCallback:
      type: object
      required: [Body]
      properties:
        Body:
          type: object
          required: [stkCallback]
          properties:
            stkCallback:
              type: object
              required: [MerchantRequestID, CheckoutRequestID, ResultCode, ResultDesc]
              properties:
                MerchantRequestID:
                  type: string
                CheckoutRequestID:
                  type: string
                ResultCode:
                  $ref: "#/components/schemas/StkResultCode"
                ResultDesc:
                  type: string
                CallbackMetadata:
                  type: object
                  required: [Item]
                  properties:
                    Item:
                      type: array
                      items:
                        $ref: "#/components/schemas/CallbackItem"

    HttpsUrl:
      type: string
      format: uri
      pattern: "^https://"

    InitiatorName:
      type: string
      minLength: 1
      description: The API operator created on the M-PESA org portal. `testapi` in the sandbox.

    SecurityCredential:
      type: string
      description: |
        The initiator's password encrypted with Safaricom's public certificate
        (RSA, PKCS #1 v1.5 padding), base64-encoded. The sandbox and production use
        different certificates.

    Remarks:
      type: string
      minLength: 2
      maxLength: 100

    AsyncAccepted:
      type: object
      required: [ConversationID, OriginatorConversationID, ResponseCode, ResponseDescription]
      properties:
        ConversationID:
          type: string
        OriginatorConversationID:
          type: string
        ResponseCode:
          type: string
          description: '"0" means Daraja queued the request. The outcome comes to `ResultURL`.'
        ResponseDescription:
          type: string

    KeyValue:
      type: object
      required: [Key]
      properties:
        Key:
          type: string
        Value:
          oneOf:
            - type: string
            - type: number

    AsyncResult:
      type: object
      required: [Result]
      properties:
        Result:
          type: object
          required: [ResultType, ResultCode, ResultDesc, OriginatorConversationID, ConversationID]
          properties:
            ResultType:
              type: integer
            ResultCode:
              oneOf:
                - type: integer
                - type: string
              description: 0 means success. Some APIs send it as a string.
            ResultDesc:
              type: string
            OriginatorConversationID:
              type: string
            ConversationID:
              type: string
            TransactionID:
              type: string
            ResultParameters:
              type: object
              properties:
                ResultParameter:
                  description: One item or a list, depending on the API.
                  oneOf:
                    - type: array
                      items:
                        $ref: "#/components/schemas/KeyValue"
                    - $ref: "#/components/schemas/KeyValue"
            ReferenceData:
              type: object
              properties:
                ReferenceItem:
                  oneOf:
                    - type: array
                      items:
                        $ref: "#/components/schemas/KeyValue"
                    - $ref: "#/components/schemas/KeyValue"

    C2bRegisterUrlRequest:
      type: object
      additionalProperties: false
      required: [ShortCode, ResponseType, ConfirmationURL, ValidationURL]
      properties:
        ShortCode:
          $ref: "#/components/schemas/ShortCode"
        ResponseType:
          type: string
          enum: [Completed, Cancelled]
          description: What M-PESA does when your validation URL doesn't answer in time.
        ConfirmationURL:
          $ref: "#/components/schemas/HttpsUrl"
        ValidationURL:
          $ref: "#/components/schemas/HttpsUrl"

    C2bRegisterUrlResponse:
      type: object
      required: [ResponseCode, ResponseDescription]
      properties:
        OriginatorCoversationID:
          type: string
          description: Spelled this way by Daraja.
        ResponseCode:
          type: string
        ResponseDescription:
          type: string

    C2bSimulateRequest:
      type: object
      additionalProperties: false
      required: [ShortCode, CommandID, Amount, Msisdn]
      properties:
        ShortCode:
          $ref: "#/components/schemas/ShortCode"
        CommandID:
          type: string
          enum: [CustomerPayBillOnline, CustomerBuyGoodsOnline]
        Amount:
          type: integer
          minimum: 1
        Msisdn:
          $ref: "#/components/schemas/Msisdn"
        BillRefNumber:
          type: string
          description: The account number. Leave out for a till.

    C2bTransaction:
      type: object
      required: [TransactionType, TransID, TransTime, TransAmount, BusinessShortCode]
      properties:
        TransactionType:
          type: string
        TransID:
          type: string
          description: The M-PESA receipt.
        TransTime:
          $ref: "#/components/schemas/Timestamp"
        TransAmount:
          type: string
          description: Amount as a decimal string, e.g. `"250.00"`.
        BusinessShortCode:
          type: string
        BillRefNumber:
          type: string
        InvoiceNumber:
          type: string
        OrgAccountBalance:
          type: string
        ThirdPartyTransID:
          type: string
        MSISDN:
          type: string
          description: The payer's number. Recent Daraja versions mask or hash it.
        FirstName:
          type: string
        MiddleName:
          type: string
        LastName:
          type: string

    C2bValidationResponse:
      type: object
      required: [ResultCode, ResultDesc]
      properties:
        ResultCode:
          type: string
          description: '"0" accepts. Rejection codes include `C2B00011` (invalid MSISDN), `C2B00012` (invalid account number), `C2B00013` (invalid amount) and `C2B00016` (other).'
        ResultDesc:
          type: string

    B2cRequest:
      type: object
      additionalProperties: false
      required:
        - OriginatorConversationID
        - InitiatorName
        - SecurityCredential
        - CommandID
        - Amount
        - PartyA
        - PartyB
        - Remarks
        - QueueTimeOutURL
        - ResultURL
      properties:
        OriginatorConversationID:
          type: string
          minLength: 1
          description: Your unique ID for this payment. Reuse it on retries.
        InitiatorName:
          $ref: "#/components/schemas/InitiatorName"
        SecurityCredential:
          $ref: "#/components/schemas/SecurityCredential"
        CommandID:
          type: string
          enum: [SalaryPayment, BusinessPayment, PromotionPayment]
        Amount:
          type: integer
          minimum: 10
          description: Whole shillings. M-PESA's B2C minimum is KES 10.
        PartyA:
          $ref: "#/components/schemas/ShortCode"
        PartyB:
          $ref: "#/components/schemas/Msisdn"
        Remarks:
          $ref: "#/components/schemas/Remarks"
        QueueTimeOutURL:
          $ref: "#/components/schemas/HttpsUrl"
        ResultURL:
          $ref: "#/components/schemas/HttpsUrl"
        Occassion:
          type: string
          maxLength: 100
          description: Optional. Spelled this way by Daraja.

    B2bRequest:
      type: object
      additionalProperties: false
      required:
        - Initiator
        - SecurityCredential
        - CommandID
        - SenderIdentifierType
        - RecieverIdentifierType
        - Amount
        - PartyA
        - PartyB
        - AccountReference
        - Remarks
        - QueueTimeOutURL
        - ResultURL
      properties:
        Initiator:
          $ref: "#/components/schemas/InitiatorName"
        SecurityCredential:
          $ref: "#/components/schemas/SecurityCredential"
        CommandID:
          type: string
          enum: [BusinessPayBill, BusinessBuyGoods]
        SenderIdentifierType:
          type: string
          enum: ["4"]
          description: '"4" for a shortcode.'
        RecieverIdentifierType:
          type: string
          enum: ["4"]
          description: Spelled this way by Daraja.
        Amount:
          type: integer
          minimum: 1
        PartyA:
          $ref: "#/components/schemas/ShortCode"
        PartyB:
          $ref: "#/components/schemas/ShortCode"
        AccountReference:
          type: string
          minLength: 1
          maxLength: 13
        Requester:
          $ref: "#/components/schemas/Msisdn"
        Remarks:
          $ref: "#/components/schemas/Remarks"
        QueueTimeOutURL:
          $ref: "#/components/schemas/HttpsUrl"
        ResultURL:
          $ref: "#/components/schemas/HttpsUrl"
        Occassion:
          type: string

    ReversalRequest:
      type: object
      additionalProperties: false
      required:
        - Initiator
        - SecurityCredential
        - CommandID
        - TransactionID
        - Amount
        - ReceiverParty
        - RecieverIdentifierType
        - ResultURL
        - QueueTimeOutURL
        - Remarks
      properties:
        Initiator:
          $ref: "#/components/schemas/InitiatorName"
        SecurityCredential:
          $ref: "#/components/schemas/SecurityCredential"
        CommandID:
          type: string
          enum: [TransactionReversal]
        TransactionID:
          type: string
          description: The M-PESA receipt of the payment to reverse.
        Amount:
          type: integer
          minimum: 1
        ReceiverParty:
          $ref: "#/components/schemas/ShortCode"
        RecieverIdentifierType:
          type: string
          enum: ["11"]
          description: '"11" for a reversal. Spelled this way by Daraja.'
        ResultURL:
          $ref: "#/components/schemas/HttpsUrl"
        QueueTimeOutURL:
          $ref: "#/components/schemas/HttpsUrl"
        Remarks:
          $ref: "#/components/schemas/Remarks"
        Occasion:
          type: string

    TransactionStatusRequest:
      type: object
      additionalProperties: false
      required:
        - Initiator
        - SecurityCredential
        - CommandID
        - PartyA
        - IdentifierType
        - ResultURL
        - QueueTimeOutURL
        - Remarks
      description: Send `TransactionID`, or `OriginatorConversationID` for a B2C payment whose receipt you never got.
      properties:
        Initiator:
          $ref: "#/components/schemas/InitiatorName"
        SecurityCredential:
          $ref: "#/components/schemas/SecurityCredential"
        CommandID:
          type: string
          enum: [TransactionStatusQuery]
        TransactionID:
          type: string
          description: The M-PESA receipt. Required unless you send `OriginatorConversationID`.
        OriginatorConversationID:
          type: string
          description: The ID you gave a B2C payment, when you have no receipt.
        PartyA:
          type: string
          description: Your shortcode, or a phone number for `IdentifierType` "1".
        IdentifierType:
          type: string
          enum: ["1", "2", "4"]
          description: '"1" phone number, "2" till, "4" shortcode.'
        ResultURL:
          $ref: "#/components/schemas/HttpsUrl"
        QueueTimeOutURL:
          $ref: "#/components/schemas/HttpsUrl"
        Remarks:
          $ref: "#/components/schemas/Remarks"
        Occasion:
          type: string

    AccountBalanceRequest:
      type: object
      additionalProperties: false
      required:
        - Initiator
        - SecurityCredential
        - CommandID
        - PartyA
        - IdentifierType
        - Remarks
        - QueueTimeOutURL
        - ResultURL
      properties:
        Initiator:
          $ref: "#/components/schemas/InitiatorName"
        SecurityCredential:
          $ref: "#/components/schemas/SecurityCredential"
        CommandID:
          type: string
          enum: [AccountBalance]
        PartyA:
          $ref: "#/components/schemas/ShortCode"
        IdentifierType:
          type: string
          enum: ["2", "4"]
        Remarks:
          $ref: "#/components/schemas/Remarks"
        QueueTimeOutURL:
          $ref: "#/components/schemas/HttpsUrl"
        ResultURL:
          $ref: "#/components/schemas/HttpsUrl"

    DynamicQrRequest:
      type: object
      additionalProperties: false
      required: [MerchantName, RefNo, Amount, TrxCode, CPI, Size]
      properties:
        MerchantName:
          type: string
          minLength: 1
        RefNo:
          type: string
          minLength: 1
          description: The account number or reference shown to the customer.
        Amount:
          type: integer
          minimum: 1
        TrxCode:
          type: string
          enum: [BG, WA, PB, SM, SB]
          description: '`BG` buy goods (till), `WA` agent withdrawal, `PB` paybill, `SM` send money to a phone number, `SB` send to a business.'
        CPI:
          type: string
          description: The till, agent, paybill or phone number to pay.
        Size:
          type: string
          pattern: "^[0-9]+$"
          description: Width and height of the image in pixels, as a string.

    DynamicQrResponse:
      type: object
      required: [ResponseCode, ResponseDescription, QRCode]
      properties:
        ResponseCode:
          type: string
        RequestID:
          type: string
        ResponseDescription:
          type: string
        QRCode:
          type: string
          description: A PNG image, base64-encoded.
