Spaces:
Paused
Paused
File size: 4,065 Bytes
16855a8 41de649 16855a8 41de649 16855a8 41de649 16855a8 41de649 16855a8 41de649 16855a8 41de649 16855a8 41de649 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 | import axios from 'axios';
const CLICKPESA_URL = 'https://api.clickpesa.com/third-parties';
const API_KEY = process.env.CLICKPESA_API_KEY;
const CLIENT_ID = process.env.CLICKPESA_CLIENT_ID;
// Helper for headers
const getHeaders = () => ({
'Content-Type': 'application/json',
'Authorization': `Bearer ${API_KEY}`,
'X-Client-ID': process.env.CLICKPESA_CLIENT_ID
});
export const initiateMobilePayment = async (amount, phoneNumber, reference) => {
try {
// Note: ClickPesa API payloads vary by integration type (Checkout vs Direct).
// This assumes a standard C2B (Collection) request.
// Check ClickPesa docs for exact field names.
// If in Dev mode and no API key, simulate success
if (process.env.NODE_ENV === 'development' && !API_KEY) {
console.log("DEV MODE: Simulating ClickPesa Request", payload);
return { success: true, transaction_id: 'SIMULATED_' + Date.now() };
}
const authToken = await getClickPesaAuthToken(CLIENT_ID, API_KEY);
const payload = {
amount: amount,
currency: 'TZS',
phoneNumber: phoneNumber, // Format: 2557XXXXXXXX
orderReference: reference, // Our Transaction ID
};
const url = `${CLICKPESA_URL}/payments/initiate-ussd-push-request`;
const response = await axios.post(url, payload, {
headers: {
'Authorization': authToken, // Assumes token includes "Bearer "
'Content-Type': 'application/json'
},
timeout: 20000
});
return response.data;
} catch (error) {
console.error("ClickPesa Error:", error.response?.data || error.message);
throw new Error("Payment initiation failed");
}
};
/**
* Generates a short-lived JWT Authorization token from ClickPesa.
* @param {string} clientId - Your ClickPesa Client ID.
* @param {string} apiKey - Your ClickPesa API Key.
* @returns {Promise<string>} The Bearer token string (e.g., "Bearer xxx...")
* @throws {Error} If token generation fails.
*/
export async function getClickPesaAuthToken(clientId, apiKey) {
if (!clientId || !apiKey) {
throw new Error('ClickPesa Client ID and API Key are required.');
}
const url = `${CLICKPESA_URL}/generate-token`;
try {
const response = await axios.post(url, null, { // No body needed for token generation
headers: {
'api-key': apiKey,
'client-id': clientId,
//'Content-Type': 'application/json' // Still good practice
},
timeout: 10000 // 10 seconds timeout
});
if (response.data && response.data.success && response.data.token) {
// Ensure the token includes "Bearer " if the API expects it directly
// The example shows "Bearer token" in the response, let's assume it needs adding
// return response.data.token.startsWith('Bearer ') ? response.data.token : `Bearer ${response.data.token}`;
// Update: Docs show response is just "Bearer token", so likely includes it. Let's just return it.
if (!response.data.token.includes('Bearer')) {
console.warn("ClickPesa token response did not include 'Bearer ' prefix. Adding it.");
return `Bearer ${response.data.token}`;
}
return response.data.token;
} else {
console.error("Unexpected ClickPesa token response:", response.data);
throw new Error('Failed to retrieve valid token from ClickPesa response.');
}
} catch (error) {
console.error('Error generating ClickPesa auth token:', error.response?.data || error.message);
console.log(error,"error")
throw new Error(`ClickPesa auth token generation failed: ${error.response?.data?.message || error.message}`);
}
}
|