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} 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}`); } }