-
Notifications
You must be signed in to change notification settings - Fork 47
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
(feat) : Add MPESA STK push functionality (#241)
* git eol sequence settings * feat: real time payment status notification * refactor: new mpesa backend url * feat: loading indicator on stk-push * Update packages/esm-billing-app/src/m-pesa/mpesa-resource.tsx refactor: removed comments for local test api Co-authored-by: Donald Kibet <[email protected]> * refactor: used translation for error message return Co-authored-by: Donald Kibet <[email protected]> * refactor: better error types for getting custom error * refactor: use custom hook instead of effect in component * refactor: return only poll trigger * feat: reading URL from configuration * feat: disable button to avoid recalling the API for pending requests * refactor: auto generated translation * refactor: Request status type on correct module --------- Co-authored-by: Amoh Prince <[email protected]> Co-authored-by: Donald Kibet <[email protected]>
- Loading branch information
1 parent
c8aa8e6
commit c1e8f28
Showing
9 changed files
with
174 additions
and
70 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
* text=auto eol=lf |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -83,3 +83,5 @@ dist | |
e2e/storageState.json | ||
.env | ||
|
||
#vscode | ||
.vscode/settings.json |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
import { useState, useEffect, SetStateAction } from 'react'; | ||
import { getRequestStatus, readableStatusMap, getErrorMessage } from '../m-pesa/mpesa-resource'; | ||
import { useTranslation } from 'react-i18next'; | ||
import { useConfig } from '@openmrs/esm-framework'; | ||
import { BillingConfig } from '../config-schema'; | ||
import { RequestStatus } from '../types'; | ||
|
||
type RequestData = { requestId: string; requestStatus: RequestStatus | null }; | ||
|
||
/** | ||
* useRequestStatus | ||
* @param setNotification a function to call with the appropriate notification type | ||
* @returns a function to trigger the polling. | ||
*/ | ||
export const useRequestStatus = ( | ||
setNotification: React.Dispatch<SetStateAction<{ type: 'error' | 'success'; message: string } | null>>, | ||
): [RequestData, React.Dispatch<React.SetStateAction<RequestData | null>>] => { | ||
const { t } = useTranslation(); | ||
const { mpesaAPIBaseUrl } = useConfig<BillingConfig>(); | ||
|
||
const [requestData, setRequestData] = useState<{ requestId: string; requestStatus: RequestStatus | null }>({ | ||
requestId: null, | ||
requestStatus: null, | ||
}); | ||
|
||
useEffect(() => { | ||
let interval: NodeJS.Timeout; | ||
|
||
if (requestData.requestId && !['COMPLETE', 'FAILED', 'NOT-FOUND'].includes(requestData.requestStatus)) { | ||
const fetchStatus = async () => { | ||
try { | ||
const status = await getRequestStatus(requestData.requestId, mpesaAPIBaseUrl); | ||
if (status === 'COMPLETE' || status === 'FAILED' || status === 'NOT-FOUND') { | ||
clearInterval(interval); | ||
} | ||
if (status === 'COMPLETE' || status === 'INITIATED') { | ||
setNotification({ type: 'success', message: readableStatusMap.get(status) }); | ||
} | ||
if (status === 'FAILED' || status === 'NOT-FOUND') { | ||
setNotification({ type: 'error', message: readableStatusMap.get(status) }); | ||
} | ||
} catch (error) { | ||
clearInterval(interval); | ||
setNotification({ type: 'error', message: getErrorMessage(error, t) }); | ||
} | ||
}; | ||
|
||
interval = setInterval(fetchStatus, 2000); | ||
|
||
return () => clearInterval(interval); | ||
} | ||
}, [mpesaAPIBaseUrl, requestData.requestId, requestData.requestStatus, setNotification, t]); | ||
|
||
return [requestData, setRequestData]; | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,39 +1,81 @@ | ||
import { Buffer } from 'buffer'; | ||
import { RequestStatus } from '../types'; | ||
|
||
export const generateStkAccessToken = async (authorizationUrl: string, setNotification) => { | ||
try { | ||
const consumerKey = ''; | ||
const consumerSecret = ''; | ||
const auth = Buffer.from(`${consumerKey}:${consumerSecret}`).toString('base64'); | ||
const headers = { | ||
'Content-Type': 'application/json', | ||
Authorization: `Basic ${auth}`, | ||
}; | ||
const response = await fetch(authorizationUrl, { method: 'GET', headers: headers }); | ||
const { access_token } = await response.json(); | ||
return access_token; | ||
} catch (error) { | ||
setNotification('Unable to reach the MPESA server, please try again later.'); | ||
throw error; | ||
} | ||
}; | ||
export const readableStatusMap = new Map<RequestStatus, string>(); | ||
readableStatusMap.set('COMPLETE', 'Complete'); | ||
readableStatusMap.set('FAILED', 'Failed'); | ||
readableStatusMap.set('INITIATED', 'Waiting for user...'); | ||
readableStatusMap.set('NOT-FOUND', 'Request not found'); | ||
|
||
export const initiateStkPush = async (payload, initiateUrl: string, authorizationUrl: string, setNotification) => { | ||
export const initiateStkPush = async ( | ||
payload, | ||
setNotification: (notification: { type: 'error' | 'success'; message: string }) => void, | ||
MPESA_PAYMENT_API_BASE_URL: string, | ||
): Promise<string> => { | ||
try { | ||
const access_token = await generateStkAccessToken(authorizationUrl, setNotification); | ||
const headers = { | ||
'Content-Type': 'application/json', | ||
Authorization: `Bearer ${access_token}`, | ||
}; | ||
const response = await fetch(initiateUrl, { | ||
const url = `${MPESA_PAYMENT_API_BASE_URL}/api/mpesa/stk-push`; | ||
|
||
const res = await fetch(url, { | ||
method: 'POST', | ||
headers: headers, | ||
body: JSON.stringify(payload), | ||
headers: { | ||
'Content-Type': 'application/json', | ||
}, | ||
body: JSON.stringify({ | ||
phoneNumber: payload.PhoneNumber, | ||
amount: payload.Amount, | ||
accountReference: payload.AccountReference, | ||
}), | ||
}); | ||
|
||
return await response.json(); | ||
if (!res.ok && res.status === 403) { | ||
const error = new Error('Health facility M-PESA data not configured.'); | ||
throw error; | ||
} | ||
|
||
const response: { requestId: string } = await res.json(); | ||
|
||
setNotification({ message: 'STK Push sent successfully', type: 'success' }); | ||
return response.requestId; | ||
} catch (err) { | ||
setNotification('Unable to initiate Lipa Na Mpesa, please try again later.'); | ||
throw err; | ||
const error = err as Error; | ||
setNotification({ | ||
message: error.message ?? 'Unable to initiate Lipa Na Mpesa, please try again later.', | ||
type: 'error', | ||
}); | ||
} | ||
}; | ||
|
||
export const getRequestStatus = async ( | ||
requestId: string, | ||
MPESA_PAYMENT_API_BASE_URL: string, | ||
): Promise<RequestStatus> => { | ||
const requestResponse = await fetch(`${MPESA_PAYMENT_API_BASE_URL}/api/mpesa/check-payment-state`, { | ||
method: 'POST', | ||
headers: { | ||
'Content-Type': 'application/json', | ||
}, | ||
body: JSON.stringify({ | ||
requestId, | ||
}), | ||
}); | ||
|
||
if (!requestResponse.ok) { | ||
const error = new Error(`HTTP error! status: ${requestResponse.status}`); | ||
|
||
if (requestResponse.statusText) { | ||
error.message = requestResponse.statusText; | ||
} | ||
throw error; | ||
} | ||
|
||
const requestStatus: { status: RequestStatus } = await requestResponse.json(); | ||
|
||
return requestStatus.status; | ||
}; | ||
|
||
export const getErrorMessage = (err: { message: string }, t) => { | ||
if (err.message) { | ||
return err.message; | ||
} | ||
|
||
return t('unKnownErrorMsg', 'An unknown error occurred'); | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters