-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.js
More file actions
193 lines (168 loc) · 8.2 KB
/
index.js
File metadata and controls
193 lines (168 loc) · 8.2 KB
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
// MoMo (Mobile Money) API Server for MTN's Collection Product Service
// This server handles various endpoints to interact with the MTN MoMo API,
// facilitating operations like user creation, token generation, and payment requests.
const express = require('express');
const axios = require('axios');
require('dotenv').config(); // Load environment variables from .env file
const bodyParser = require('body-parser'); // Parse incoming request bodies
const cors = require('cors'); // Enable Cross-Origin Resource Sharing for all routes
const { v4: uuidv4 } = require('uuid'); // UUID generation for unique identifiers
const app = express();
const port = 3001; // Server listening port, can be set to any preferred available port
// Middleware configuration
app.use(bodyParser.json()); // Support for JSON-encoded bodies
app.use(cors()); // Apply CORS to all routes for wider accessibility
// MoMo API configuration
const momoHost = 'sandbox.momodeveloper.mtn.com'; // MoMo API host
const momoTokenUrl = `https://${momoHost}/collection/token/`; // Token endpoint
const momoRequestToPayUrl = `https://${momoHost}/collection/v1_0/requesttopay`; // Request to Pay endpoint
const MOMO_SUBSCRIPTION_KEY = process.env.MOMO_SUBSCRIPTION_KEY; //Subscription key (Primary or Secondary key) for MoMo API, ideally stored in .env file.
// Home route - Simple check to confirm the server is running
app.get('/', (req, res) => {
res.send('MoMo API Server is up and running!');
});
// Endpoint: Create MoMo API User
// This endpoint creates a new API user and returns the user ID (X-Reference-Id).
// This user ID is essential for further actions like retrieving the API key.
app.post('/create-api-user', async (req, res) => {
const apiUrl = `https://${momoHost}/v1_0/apiuser`;
// UUID generation for use in API calls where a unique identifier is required
let uuid = uuidv4();
// Headers for the MoMo API request
const headers = {
'X-Reference-Id': uuid,
'Ocp-Apim-Subscription-Key': MOMO_SUBSCRIPTION_KEY,
'Content-Type': 'application/json'
};
// Data payload for the API request
const data = {
providerCallbackHost: 'https://525e-41-210-145-67.ngrok-free.app' // replace with your Callback url
};
try {
const response = await axios.post(apiUrl, data, { headers: headers });
res.status(200).json({ response: response.data, userId: uuid }); // Returns the response from MoMo API along with the generated userId
} catch (error) {
res.status(500).json({ message: 'Error creating API user', error: error.message });
}
});
// Endpoint: Get Created User by User ID
// This endpoint retrieves details of a created user using their user ID.
// It's useful for validating that a user has been created successfully.
app.get('/get-created-user/:userId', async (req, res) => {
const userId = req.params.userId;
const apiUrl = `https://${momoHost}/v1_0/apiuser/${userId}`;
const headers = {
'Ocp-Apim-Subscription-Key': MOMO_SUBSCRIPTION_KEY
};
try {
const response = await axios.get(apiUrl, { headers: headers });
res.status(200).json(response.data); // Successful retrieval returns user details
} catch (error) {
res.status(500).json({ message: 'Error retrieving created user', error: error.message });
}
});
// Endpoint: Retrieve User API Key
// This endpoint retrieves the API key for a specific user, which is used as the password
// in user authentication when generating a MoMo token.
app.post('/retrieve-api-key/:userId', async (req, res) => {
const userId = req.params.userId;
const apiUrl = `https://${momoHost}/v1_0/apiuser/${userId}/apikey`;
const headers = {
'Ocp-Apim-Subscription-Key': MOMO_SUBSCRIPTION_KEY
};
try {
const response = await axios.post(apiUrl, {}, { headers: headers });
res.status(200).json(response.data); // Returns the user's API key
} catch (error) {
res.status(500).json({ message: 'Error retrieving API key', error: error.message });
}
});
// Endpoint: Generate MoMo Token
// This endpoint generates a token used for authorizing payment requests.
// The token is essential for making requests to the `/request-to-pay` endpoint.
app.post('/generate-api-token', async (req, res) => {
const apiUrl = momoTokenUrl;
console.log('Token request details:', req.body);
const { userId, apiKey } = req.body;
const username = userId; // Username (X-Reference-Id) from user creation step
const password = apiKey; // API Key retrieved from user API key step
const basicAuth = 'Basic ' + btoa(username + ':' + password); // Basic Auth header
const headers = {
'Authorization': basicAuth,
'Ocp-Apim-Subscription-Key': MOMO_SUBSCRIPTION_KEY
};
try {
const response = await axios.post(apiUrl, {}, { headers: headers });
res.status(200).json(response.data); // Returns the generated token
} catch (error) {
res.status(500).json({ message: 'Error generating API token', error: error.message });
}
});
// Endpoint: Request to Pay
// This endpoint initiates a payment request to a specified mobile number.
// It requires a valid MoMo token and transaction details.
app.post('/request-to-pay', async (req, res) => {
try {
console.log('Payment request details:', req.body);
const { total, phone, momoTokenId } = req.body;
if (!momoTokenId) {
return res.status(400).json({ error: 'MoMo token not available' });
}
const externalId = uuidv4();
const body = {
amount: total, // Total amount for the transaction
currency: 'EUR', // Currency for the transaction
externalId: externalId, // Unique ID for each transaction
payer: {
partyIdType: 'MSISDN',
partyId: phone, // Phone number of the payer
},
payerMessage: 'Payment for order',
payeeNote: 'Payment for order',
};
console.log('External Id: ', body.externalId);
const paymentRefId = uuidv4(); // New UUID for the request
console.log('PaymentRefId: ', paymentRefId);
const momoResponse = await axios.post(
momoRequestToPayUrl,
body,
{
headers: {
'X-Reference-Id': paymentRefId,
'X-Target-Environment': 'sandbox',
'Ocp-Apim-Subscription-Key': MOMO_SUBSCRIPTION_KEY,
Authorization: `Bearer ${momoTokenId}`,
'Content-Type': 'application/json',
},
}
);
res.json({ momoResponse: momoResponse.data, success: true, paymentRefId: paymentRefId, externalId: externalId }); // Returns response from MoMo API
} catch (error) {
console.error('Error in processing payment request:', error);
res.status(500).json({ error: `An error occurred: ${error.message}` });
}
});
// Endpoint: Get Request to Pay Transaction Status
// This operation is used to get the status of a request to pay. X-Reference-Id that was passed in the post is used as reference to the request.
// The Bearer Authentication Token generated using CreateAccessToken API Call use to make a payment request
// It is useful for confirming the status of a transaction initiated by the `/request-to-pay` endpoint.
app.get('/payment-status/:transactionId/:momoTokenId', async (req, res) => {
const transactionId = req.params.transactionId;
const momoTokenId = req.params.momoTokenId;
const apiUrl = `https://${momoHost}/collection/v1_0/requesttopay/${transactionId}`;
const headers = {
'Ocp-Apim-Subscription-Key': MOMO_SUBSCRIPTION_KEY,
Authorization: `Bearer ${momoTokenId}`,
'X-Target-Environment': 'sandbox'
};
try {
const response = await axios.get(apiUrl, { headers: headers });
res.status(200).json(response.data); // Returns the status of the payment transaction
} catch (error) {
console.error('Error in retrieving payment status:', error);
res.status(500).json({ error: `An error occurred: ${error.message}` });
}
});
app.listen(port, () => {
console.log(`Server listening at http://localhost:${port}`);
});