opex-lenta-api
v0.1.4
Published
Lenta.com wrappper to get bonus card
Readme
opex-lenta-api
A modern, promise-based Node.js library for interacting with the Lenta.com API. It provides a simple and flexible interface for authentication, data retrieval, and now includes proxy support.
Features
- Modern Syntax: Written in ESM (ES Modules) with full support for
async/await. - Flexible State Management: Stateless design—you control session storage (file, database, etc.).
- Proxy Support: Easily configure proxy agents for all outgoing requests.
- Automatic Cookie Handling: Manages cookies automatically across requests.
- High-Level & Low-Level Methods: Use convenience methods like
getAllUserData()or specific endpoints likegetProfile(). - Helper Utilities: Automatically generates barcode image links for bonus cards.
- Multi-Account Support: Manage sessions for multiple users via separate API instances.
Installation
Requires https-proxy-agent:
npm install opex-lenta-api https-proxy-agentGetting Started
Example: Log in and retrieve user data with proxy support. Sessions are stored in all_sessions.json.
import { LentaAPI } from 'opex-lenta-api';
import { HttpsProxyAgent } from 'https-proxy-agent';
import fs from 'fs';
import readline from 'readline/promises';
const SESSIONS_FILE = 'all_sessions.json';
// Helper functions to manage state
function loadAllSessions() {
try {
return JSON.parse(fs.readFileSync(SESSIONS_FILE, 'utf-8'));
} catch {
return {};
}
}
function saveAllSessions(sessions) {
fs.writeFileSync(SESSIONS_FILE, JSON.stringify(sessions, null, 2));
}
async function main() {
const phone = process.argv[2];
if (!phone) {
console.log('Usage: node example.js <phone_number>');
console.log('Set proxy via HTTPS_PROXY environment variable.');
return;
}
// Check for proxy settings
const proxyUrl = process.env.HTTPS_PROXY || process.env.https_proxy;
let proxyAgent;
if (proxyUrl) {
console.log(`Using proxy: ${proxyUrl}`);
proxyAgent = new HttpsProxyAgent(proxyUrl);
}
const allSessions = loadAllSessions();
const initialState = allSessions[phone] || {};
const api = new LentaAPI(initialState, { proxyAgent }); // Pass proxy agent
if (!api.isLoggedIn()) {
console.log(`Starting login for ${phone}...`);
await api.requestLoginCode(phone);
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
const code = await rl.question('Enter SMS code: ');
rl.close();
await api.completeLogin(phone, code);
allSessions[phone] = api.getState();
saveAllSessions(allSessions);
console.log('Login successful! Session saved.');
} else {
console.log(`Already logged in as ${phone}.`);
}
console.log('\nFetching all user data...');
const userData = await api.getAllUserData();
console.log(JSON.stringify(userData, null, 2));
}
main().catch(console.error);To Run:
First login (without proxy):
node example.js 79123456789Subsequent runs (with proxy):
HTTPS_PROXY="http://user:[email protected]:8080" node example.js 79123456789API Reference
new LentaAPI(initialState, options)
Creates a new API client instance.
Parameters:
initialState(Object, optional): Saved session state. Default: new session with newdeviceId.options(Object, optional):proxyAgent(Object): Proxy agent instance (e.g.,https-proxy-agent).
Examples:
// New session without proxy
const api_newUser = new LentaAPI();
// New session with proxy
const proxyAgent = new HttpsProxyAgent('http://user:pass@host:port');
const api_withProxy = new LentaAPI({}, { proxyAgent });
// Restore saved session
const savedState = { deviceId: "...", kfpKsid: "...", authToken: "...", passportId: "..." };
const api_existingUser = new LentaAPI(savedState);State Management
api.getState()
Returns current session state for persistence.
Returns: Object
{
"deviceId": "a1b2c3k4-e5f6-9263-abcd-ef0123459579",
"kfpKsid": "f0e1d2c3-b4a5-4678-9532-3456789abcde",
"authToken": "FINAL-TOKEN-A1B9G5D4E5F6G7H8I9KG31L2M3N4O5P6",
"passportId": "92h28d84-6j44-4f14-b451-6928525c44c7"
}api.isLoggedIn()
Checks if authenticated.
Returns: boolean
Authentication
async api.requestLoginCode(phone)
Initiates login by requesting SMS code.
phone(string): User phone (e.g.,"79123456789").
Returns:Promise<Object>
async api.completeLogin(phone, code)
Verifies SMS code and updates auth state.
phone(string): User phone.code(string): 4-digit SMS code.
Returns:Promise<Object>
Data Fetching (Requires Authentication)
async api.getProfile()
Retrieves primary user profile.
Returns: Promise<Object>
async api.getClientMe()
Retrieves extended client data (agreements, brand info).
Returns: Promise<Object>
async api.getBonusCards()
Retrieves bonus cards (auto-adds barcodeImageUrl).
Returns: Promise<Object>
async api.getAllUserData()
Fetches combined data from getProfile(), getClientMe(), and getBonusCards() in parallel.
Returns: Promise<Object>
Error Handling
Handle errors with try...catch:
try {
const profile = await api.getProfile();
} catch (error) {
console.error('Failed to get profile:', error.message);
if (error.response) {
console.error('Server response:', error.response.data);
}
}