API Code Examples
Here are examples of how to integrate with the Mopay API using different programming languages. These examples demonstrate common operations like retrieving user profiles and login activity history.
JavaScript
// Using fetch API to get user profile
const getUserProfile = async () => {
// Current timestamp
const timestamp = Math.floor(Date.now() / 1000).toString();
// Create timestamp object for signature
const timestampObj = { timestamp };
// Generate signature using HMAC-SHA512
const signature = crypto
.createHmac('sha512', 'YOUR_SECRET_KEY')
.update(JSON.stringify(timestampObj))
.digest('hex');
const response = await fetch('https://service.mopay-ng.com/?req=user_profile_get_info', {
method: 'GET',
headers: {
'MPY-SECUREKEY': 'YOUR_PUBLIC_KEY',
'MPY-TIMESTAMP': timestamp,
'MPY-REQSIGNAL': signature,
'Content-Type': 'application/json'
}
});
const data = await response.json();
console.log(data);
return data;
};
// Using axios to get login activity
const getLoginActivity = async (page = null) => {
const axios = require('axios');
try {
const url = 'https://service.mopay-ng.com/?req=user_login_fetch';
// Current timestamp
const timestamp = Math.floor(Date.now() / 1000).toString();
// Create timestamp object for signature
const timestampObj = { timestamp };
// Generate signature using HMAC-SHA512
const signature = crypto
.createHmac('sha512', 'YOUR_SECRET_KEY')
.update(JSON.stringify(timestampObj))
.digest('hex');
const config = {
headers: {
'MPY-SECUREKEY': 'YOUR_PUBLIC_KEY',
'MPY-TIMESTAMP': timestamp,
'MPY-REQSIGNAL': signature,
'Content-Type': 'application/json'
}
};
// Add pagination parameter if provided
if (page) {
config.params = { page };
}
const response = await axios.get(url, config);
console.log(response.data);
return response.data;
} catch (error) {
console.error('Error fetching login activity:', error);
throw error;
}
};
// Example usage
const handleUserData = async () => {
try {
// First get user profile
const profile = await getUserProfile();
if (profile && profile.REQUEST.STATUS === 'OK') {
const userData = profile.DATA;
console.log('User Profile Retrieved:');
console.log(`Name: ${userData.firstName} ${userData.lastName}`);
console.log(`Email: ${userData.emailAddress} (Verification: ${userData.emailVerify})`);
console.log(`Phone: ${userData.phoneNumber} (Verification: ${userData.phoneVerify})`);
// Then get login activity
const loginActivity = await getLoginActivity();
if (loginActivity && loginActivity.REQUEST.STATUS === 'OK') {
console.log('\nRecent Login Activity:');
loginActivity.DATA.result.forEach((login, index) => {
const date = new Date(parseInt(login.recorded) * 1000);
console.log(`${index + 1}. IP: ${login.ipaddx}, Time: ${date.toLocaleString()}`);
});
// Example of pagination
const nextPage = loginActivity.DATA.pagination;
console.log(`\nFor more login history, use pagination value: ${nextPage}`);
}
}
} catch (error) {
console.error('Error in data retrieval:', error);
}
};Python
import requests
import datetime
import hashlib
import hmac
import json
import time
# Get user profile information
def get_user_profile():
url = "https://service.mopay-ng.com/?req=user_profile_get_info"
# Current timestamp
timestamp = str(int(time.time()))
# Create timestamp object for signature
timestamp_obj = {"timestamp": timestamp}
# Generate signature
signature = hmac.new(
'YOUR_SECRET_KEY'.encode('utf-8'),
json.dumps(timestamp_obj).encode('utf-8'),
hashlib.sha512
).hexdigest()
headers = {
"MPY-SECUREKEY": "YOUR_PUBLIC_KEY",
"MPY-TIMESTAMP": timestamp,
"MPY-REQSIGNAL": signature,
"Content-Type": "application/json"
}
response = requests.get(url, headers=headers)
if response.status_code == 200:
return response.json()
else:
print(f"Error: {response.status_code}")
print(response.text)
return None
# Get login activity history
def get_login_activity(page=None):
url = "https://service.mopay-ng.com/?req=user_login_fetch"
# Current timestamp
timestamp = str(int(time.time()))
# Create timestamp object for signature
timestamp_obj = {"timestamp": timestamp}
# Generate signature
signature = hmac.new(
'YOUR_SECRET_KEY'.encode('utf-8'),
json.dumps(timestamp_obj).encode('utf-8'),
hashlib.sha512
).hexdigest()
headers = {
"MPY-SECUREKEY": "YOUR_PUBLIC_KEY",
"MPY-TIMESTAMP": timestamp,
"MPY-REQSIGNAL": signature,
"Content-Type": "application/json"
}
params = {}
if page:
params["page"] = page
response = requests.get(url, headers=headers, params=params)
if response.status_code == 200:
return response.json()
else:
print(f"Error: {response.status_code}")
print(response.text)
return None
# Example usage
user_data = get_user_profile()
if user_data:
print("User Profile Information:")
print(f"Name: {user_data.get('firstName')} {user_data.get('lastName')}")
print(f"Email: {user_data.get('emailAddress')} (Verification: {user_data.get('emailVerify')})")
print(f"Phone: {user_data.get('phoneNumber')} (Verification: {user_data.get('phoneVerify')})")
print(f"Account Status: {user_data.get('status')}")
print(f"Member Since: {user_data.get('activeDate')}")
# Then get login activity
activity = get_login_activity()
if activity:
print("
Login Activity History:")
for entry in activity.get('data', []):
print(f"Date: {entry.get('date')} - Device: {entry.get('device')}")
print(f"Location: {entry.get('location')} - IP: {entry.get('ipAddress')}")
print("---")PHP
<?php
// Get user profile information
function getUserProfile() {
$url = "https://service.mopay-ng.com/?req=user_profile_get_info";
// Current timestamp
$timestamp = time();
// Create timestamp object for signature
$timestampObj = json_encode(["timestamp" => $timestamp]);
// Generate signature
$signature = hash_hmac('sha512', $timestampObj, 'YOUR_SECRET_KEY');
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
"MPY-SECUREKEY: YOUR_PUBLIC_KEY",
"MPY-TIMESTAMP: $timestamp",
"MPY-REQSIGNAL: $signature",
"Content-Type: application/json"
]
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error: " . $err;
return null;
} else {
return json_decode($response, true);
}
}
// Get login activity history
function getLoginActivity($page = null) {
$url = "https://service.mopay-ng.com/?req=user_login_fetch";
if ($page) {
$url .= "?page=" . $page;
}
// Current timestamp
$timestamp = time();
// Create timestamp object for signature
$timestampObj = json_encode(["timestamp" => $timestamp]);
// Generate signature
$signature = hash_hmac('sha512', $timestampObj, 'YOUR_SECRET_KEY');
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
"MPY-SECUREKEY: YOUR_PUBLIC_KEY",
"MPY-TIMESTAMP: $timestamp",
"MPY-REQSIGNAL: $signature",
"Content-Type: application/json"
]
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error: " . $err;
return null;
} else {
return json_decode($response, true);
}
}
// Format timestamp to human-readable date
function formatTimestamp($timestamp) {
return date('Y-m-d H:i:s', (int)$timestamp);
}
// Example usage
function main() {
// First, get user profile
$profile = getUserProfile();
if ($profile && $profile['REQUEST']['STATUS'] === 'OK') {
$userData = $profile['DATA'];
echo "User Profile Retrieved:\n";
echo "Name: " . $userData['firstName'] . " " . $userData['lastName'] . "\n";
echo "Email: " . $userData['emailAddress'] . " (Verification: " . $userData['emailVerify'] . ")\n";
echo "Phone: " . $userData['phoneNumber'] . " (Verification: " . $userData['phoneVerify'] . ")\n";
echo "Account Status: " . $userData['status'] . "\n";
echo "Member Since: " . $userData['activeDate'] . "\n";
// Then get login activity
$loginActivity = getLoginActivity();
if ($loginActivity && $loginActivity['REQUEST']['STATUS'] === 'OK') {
echo "\nRecent Login Activity:\n";
foreach ($loginActivity['DATA']['result'] as $index => $login) {
$timestamp = formatTimestamp($login['recorded']);
echo ($index + 1) . ". IP: " . $login['ipaddx'] . ", Time: " . $timestamp . "\n";
}
// Example of pagination
$nextPage = $loginActivity['DATA']['pagination'];
echo "\nFor more login history, use pagination value: " . $nextPage . "\n";
// Example of fetching next page
echo "\nFetching next page...\n";
$nextActivity = getLoginActivity($nextPage);
if ($nextActivity && $nextActivity['REQUEST']['STATUS'] === 'OK') {
foreach ($nextActivity['DATA']['result'] as $index => $login) {
$timestamp = formatTimestamp($login['recorded']);
echo ($index + 1) . ". IP: " . $login['ipaddx'] . ", Time: " . $timestamp . "\n";
}
}
} else {
echo "Failed to fetch login activity.\n";
}
} else {
echo "Failed to fetch user profile.\n";
}
}
// Run the example
// main();
?>