### Initiate Internet Top-Up Source: https://docs.oneclickdz.com/quickstart Initiates an internet top-up for a specified number and value. ```APIDOC ## POST /v3/internet/send ### Description Recharges an ADSL line or other internet service with a specified amount. ### Method POST ### Endpoint `/v3/internet/send` #### Headers - **Content-Type** (string) - Required - Set to `application/json`. - **X-Access-Token** (string) - Required - Your API key. #### Request Body - **type** (string) - Required - The type of internet service (e.g., "ADSL"). - **number** (string) - Required - The internet service number to recharge. - **value** (number) - Required - The amount to top up in DZD. - **ref** (string) - Required - A unique reference for the transaction. ### Request Example ```json { "type": "ADSL", "number": "036362608", "value": 1000, "ref": "internet-001" } ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the request was successful. - **data** (object) - Contains the top-up initiation details. - **topupId** (string) - The unique ID generated for the top-up. - **topupRef** (string) - The reference ID provided for the transaction. #### Response Example ```json { "success": true, "data": { "topupId": "6901616fe9e88196b4eb64b1", "topupRef": "internet-001" } } ``` ``` -------------------------------- ### Get Gift Card Codes Source: https://docs.oneclickdz.com/quickstart This section details how to retrieve gift card codes. It includes a PHP code example for calling the `getGiftCardCodes` function and an example of the expected JSON response when the status is 'FULFILLED'. ```APIDOC ## GET /api/giftcards/codes ### Description Retrieves a list of gift card codes. The function checks the status of the operation and returns the card details if fulfilled. ### Method GET ### Endpoint /api/giftcards/codes ### Parameters #### Query Parameters - **customerId** (string) - Required - The ID of the customer. - **apiKey** (string) - Required - Your API key for authentication. ### Request Example ```php [ "status" => "FULFILLED", "cards" => [ ["value" => "XXXX-XXXX-XXXX-XXXX", "serial" => "123456789"] ] ] ]; $status = $response['data']['status']; if ($status === 'FULFILLED') { return $response['data']['cards']; } sleep(5); // Wait 5 seconds // In a real scenario, you might retry or handle other statuses return null; // Or handle non-fulfilled status appropriately } $cards = getGiftCardCodes('6901616fe9e88196b4eb64c0', 'YOUR_API_KEY'); print_r($cards); ?> ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the operation was successful. - **data** (object) - Contains the response data. - **status** (string) - The status of the gift card retrieval (e.g., 'FULFILLED'). - **cards** (array) - An array of gift card objects if the status is 'FULFILLED'. - **value** (string) - The gift card code. - **serial** (string) - The serial number of the gift card. #### Response Example ```json { "success": true, "data": { "status": "FULFILLED", "cards": [ { "value": "XXXX-XXXX-XXXX-XXXX", "serial": "123456789" } ] } } ``` ``` -------------------------------- ### Send Mobile Top-Up Source: https://docs.oneclickdz.com/quickstart Initiates a mobile top-up transaction for a specified mobile number and amount. ```APIDOC ## POST /v3/mobile/send ### Description Sends a mobile top-up to a given mobile number. ### Method POST ### Endpoint https://api.oneclickdz.com/v3/mobile/send ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **plan_code** (string) - Required - The code for the mobile plan (e.g., "PREPAID_DJEZZY"). - **MSSIDN** (string) - Required - The mobile number to top up (e.g., "0778037340"). - **amount** (integer) - Required - The amount to top up in DZD. - **ref** (string) - Required - A unique reference for the transaction (e.g., "order-001"). ### Headers - **Content-Type** (string) - Required - Set to "application/json". - **X-Access-Token** (string) - Required - Your API key. ### Request Example ```json { "plan_code": "PREPAID_DJEZZY", "MSSIDN": "0778037340", "amount": 500, "ref": "order-001" } ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the top-up request was successful. - **data** (object) - Contains details about the top-up. - **topupId** (string) - The unique ID of the top-up. - **topupRef** (string) - The reference provided for the transaction. #### Response Example ```json { "success": true, "data": { "topupId": "6901616fe9e88196b4eb64b0", "topupRef": "order-001" } } ``` ``` -------------------------------- ### Sandbox Testing Scenarios Source: https://docs.oneclickdz.com/quickstart Outlines special scenarios for sandbox testing, particularly for mobile top-ups, to test different transaction behaviors. ```APIDOC ## Sandbox Testing: Mobile Top-Ups ### Description Sandbox mode allows testing of various mobile top-up scenarios using specific phone numbers to simulate different outcomes and ensure robust error handling and transaction flow. ### Method N/A (Applies to mobile top-up endpoints in sandbox) ### Endpoint N/A (Applies to mobile top-up endpoints in sandbox) ### Parameters N/A ### Request Example N/A ### Response N/A ### Sandbox Scenarios | Phone Number | Behavior | Purpose | | ------------------- | ----------------------------------------- | ----------------------------- | | `0778037340` | Success: PENDING → HANDLING → FULFILLED | Test successful transactions | | `0600000001` | REFUNDED with error message | Test refund handling | | `0600000002` | REFUNDED with suggested alternative plans | Test plan mismatch | | `0600000003` | UNKNOWN_ERROR status | Test uncertain state handling | ``` -------------------------------- ### Verify API Key Source: https://docs.oneclickdz.com/quickstart This endpoint allows you to test if your API key is valid and functioning correctly. ```APIDOC ## GET /v3/validate ### Description Verifies the provided API key. ### Method GET ### Endpoint https://api.oneclickdz.com/v3/validate ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Headers - **X-Access-Token** (string) - Required - Your API key. ### Request Example ```bash curl https://api.oneclickdz.com/v3/validate \ -H "X-Access-Token: YOUR_API_KEY" ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the validation was successful. - **data** (object) - Contains details about the API key and user. - **username** (string) - The username associated with the API key. - **apiKey** (object) - Details of the API key. - **type** (string) - The type of the API key (e.g., SANDBOX, PRODUCTION). - **scope** (string) - The scope of the API key (e.g., READ-WRITE). - **isEnabled** (boolean) - Indicates if the API key is enabled. #### Response Example ```json { "success": true, "data": { "username": "+213665983439", "apiKey": { "type": "SANDBOX", "scope": "READ-WRITE", "isEnabled": true } } } ``` ``` -------------------------------- ### POST /v3/gift-cards/placeOrder Source: https://docs.oneclickdz.com/quickstart Places an order for a gift card. Requires product ID, type ID, and quantity, along with authentication. ```APIDOC ## POST /v3/gift-cards/placeOrder ### Description Places a gift card order. You need to provide the `productId`, `typeId`, and `quantity` in the request body. ### Method POST ### Endpoint https://api.oneclickdz.com/v3/gift-cards/placeOrder ### Parameters #### Headers - **Content-Type** (string) - Required - Should be `application/json`. - **X-Access-Token** (string) - Required - Your API key for authentication. #### Request Body - **productId** (string) - Required - The ID of the product for the gift card. - **typeId** (string) - Required - The ID of the type for the gift card. - **quantity** (number) - Required - The number of gift cards to order. ### Request Example ```json { "productId": "PRODUCT_ID", "typeId": "TYPE_ID", "quantity": 1 } ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the request was successful. - **data** (object) - **orderId** (string) - The unique identifier for the placed order. ### Response Example ```json { "success": true, "data": { "orderId": "6901616fe9e88196b4eb64c0" } } ``` ``` -------------------------------- ### GET /v3/gift-cards/catalog Source: https://docs.oneclickdz.com/quickstart Retrieves the product catalog to display available gift cards. This endpoint requires an API key for authentication. ```APIDOC ## GET /v3/gift-cards/catalog ### Description Retrieves the product catalog to see available gift cards. ### Method GET ### Endpoint https://api.oneclickdz.com/v3/gift-cards/catalog ### Parameters #### Headers - **X-Access-Token** (string) - Required - Your API key for authentication. ### Response #### Success Response (200) - **success** (boolean) - Indicates if the request was successful. - **data** (object) - Contains the gift card catalog information. - **products** (array) - A list of available gift card products. - **id** (string) - The unique identifier for the product. - **name** (string) - The name of the gift card product. - **typeId** (string) - The identifier for the gift card type. - **value** (number) - The monetary value of the gift card. ### Request Example ```bash curl https://api.oneclickdz.com/v3/gift-cards/catalog \ -H "X-Access-Token: YOUR_API_KEY" ``` ### Response Example ```json { "success": true, "data": { "products": [ { "id": "PRODUCT_ID_1", "name": "Example Gift Card $10", "typeId": "TYPE_ID_1", "value": 10 } ] } } ``` ``` -------------------------------- ### Check Internet Top-Up Status Source: https://docs.oneclickdz.com/quickstart Checks the status of an internet top-up using its reference ID. ```APIDOC ## GET /v3/internet/check-ref/{ref} ### Description Checks the status of an internet top-up using the provided transaction reference. ### Method GET ### Endpoint `/v3/internet/check-ref/{ref}` #### Path Parameters - **ref** (string) - Required - The reference ID of the internet top-up transaction. #### Headers - **X-Access-Token** (string) - Required - Your API key. ### Response #### Success Response (200) - **success** (boolean) - Indicates if the request was successful. - **data** (object) - Contains the top-up status details. - **status** (string) - The current status of the top-up (e.g., FULFILLED). - **card_code** (string) - The top-up card code (if applicable). - **num_trans** (string) - The transaction number. #### Response Example ```json { "success": true, "data": { "status": "FULFILLED", "card_code": "123456789012", "num_trans": "AT-2025-001" } } ``` ``` -------------------------------- ### Current v2 API Client (JavaScript, PHP, Python) Source: https://docs.oneclickdz.com/migration-from-v2 Demonstrates the structure and functionality of the current v2 API client wrapper in JavaScript, PHP, and Python. These examples show how to initialize the client, make requests, get account balance, and send top-up requests. ```javascript class FlexyAPI { constructor(apiKey) { this.apiKey = apiKey; this.baseUrl = "https://flexy-api.oneclickdz.com"; } async request(endpoint, options = {}) { const response = await fetch(`${this.baseUrl}${endpoint}`, { ...options, headers: { ...options.headers, authorization: this.apiKey, }, }); return response.json(); } async getBalance() { const data = await this.request("/v2/account/balance"); return data.balance; } async sendTopup(params) { return await this.request("/v2/topup/sendTopup", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(params), }); } } ``` ```php class FlexyAPI { private $apiKey; private $baseUrl = 'https://flexy-api.oneclickdz.com'; public function __construct($apiKey) { $this->apiKey = $apiKey; } private function request($endpoint, $options = []) { $ch = curl_init($this->baseUrl . $endpoint); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'authorization: ' . $this->apiKey ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); if (isset($options['method']) && $options['method'] === 'POST') { curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $options['body']); } $response = curl_exec($ch); return json_decode($response, true); } public function getBalance() { $data = $this->request('/v2/account/balance'); return $data['balance']; } public function sendTopup($params) { return $this->request('/v2/topup/sendTopup', [ 'method' => 'POST', 'body' => json_encode($params) ]); } } ``` ```python import requests class FlexyAPI: def __init__(self, api_key): self.api_key = api_key self.base_url = 'https://flexy-api.oneclickdz.com' def request(self, endpoint, method='GET', data=None): headers = {'authorization': self.api_key} url = f"{self.base_url}{endpoint}" if method == 'GET': response = requests.get(url, headers=headers) else: headers['Content-Type'] = 'application/json' response = requests.post(url, headers=headers, json=data) return response.json() def get_balance(self): data = self.request('/v2/account/balance') return data['balance'] def send_topup(self, params): return self.request('/v2/topup/sendTopup', method='POST', data=params) ``` -------------------------------- ### Run Unit Tests Source: https://docs.oneclickdz.com/ocpay-guides/6-php-sdk-integration Provides the command to install development dependencies and run unit tests using PHPUnit for the OCPay SDK. This ensures the library functions as expected. ```bash composer install --dev vendor/bin/phpunit ``` -------------------------------- ### Send Mobile Top-Up with cURL, Node.js, Python, PHP Source: https://docs.oneclickdz.com/quickstart Initiate a mobile top-up transaction using the /v3/mobile/send endpoint. This example demonstrates how to send a 500 DZD top-up to a Djezzy number with a reference ID, using cURL, Node.js, Python, and PHP. Replace 'YOUR_API_KEY' with your valid API key. ```cURL curl https://api.oneclickdz.com/v3/mobile/send \ -X POST \ -H "Content-Type: application/json" \ -H "X-Access-Token: YOUR_API_KEY" \ -d '{ "plan_code": "PREPAID_DJEZZY", "MSSIDN": "0778037340", "amount": 500, "ref": "order-001" }' ``` ```Node.js const response = await fetch("https://api.oneclickdz.com/v3/mobile/send", { method: "POST", headers: { "Content-Type": "application/json", "X-Access-Token": "YOUR_API_KEY", }, body: JSON.stringify({ plan_code: "PREPAID_DJEZZY", MSSIDN: "0778037340", amount: 500, ref: "order-001", }), }); const data = await response.json(); ``` ```Python import requests response = requests.post( 'https://api.oneclickdz.com/v3/mobile/send', headers={ 'Content-Type': 'application/json', 'X-Access-Token': 'YOUR_API_KEY' }, json={ 'plan_code': 'PREPAID_DJEZZY', 'MSSIDN': '0778037340', 'amount': 500, 'ref': 'order-001' } ) print(response.json()) ``` ```PHP 'PREPAID_DJEZZY', 'MSSIDN' => '0778037340', 'amount' => 500, 'ref' => 'order-001' ])); $response = curl_exec($ch); echo $response; ?> ``` -------------------------------- ### Get Gift Card Catalog (cURL, Node.js, Python, PHP) Source: https://docs.oneclickdz.com/quickstart Retrieves a list of available gift cards from the OneClickDZ API. Requires an API key for authentication. Returns a JSON object containing gift card product details. ```bash curl https://api.oneclickdz.com/v3/gift-cards/catalog \ -H "X-Access-Token: YOUR_API_KEY" ``` ```javascript const response = await fetch( "https://api.oneclickdz.com/v3/gift-cards/catalog", { headers: { "X-Access-Token": "YOUR_API_KEY" }, } ); const data = await response.json(); console.log(data); ``` ```python import requests response = requests.get( 'https://api.oneclickdz.com/v3/gift-cards/catalog', headers={'X-Access-Token': 'YOUR_API_KEY'} ) print(response.json()) ``` ```php ``` -------------------------------- ### API Response Format Source: https://docs.oneclickdz.com/quickstart Details the general structure of all API responses, including success status, data payload, and metadata. ```APIDOC ## General API Response Format ### Description All API responses adhere to a consistent structure that includes operational status, the main data payload, and relevant metadata. ### Method N/A (Applies to all endpoints) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response #### Success Response (200) - **success** (boolean) - Indicates the overall success of the API operation. - **data** (object) - Contains the primary data returned by the API. The structure of this object varies depending on the endpoint. - **meta** (object) - Contains metadata about the response. - **timestamp** (string) - The timestamp when the response was generated. - **pagination** (object) - Pagination details if the response includes a list of items (may be null if not applicable). - **requestId** (string) - A unique identifier for the request, useful for tracking and support. #### Response Example ```json { "success": true, "data": { ... }, "meta": { "timestamp": "2023-10-27T10:00:00Z", "pagination": { ... } }, "requestId": "a1b2c3d4-e5f6-7890-1234-567890abcdef" } ``` ``` -------------------------------- ### Install OCPay PHP SDK via Composer Source: https://docs.oneclickdz.com/ocpay-guides/6-php-sdk-integration This snippet shows how to install the OCPay PHP SDK using Composer. It can be added directly to the command line or by updating the composer.json file. This ensures the SDK is available for use in your PHP project. ```bash composer require oneclickdz/ocpay-php-sdk ``` ```json { "require": { "oneclickdz/ocpay-php-sdk": "^1.0" } } ``` -------------------------------- ### GET /v3/gift-cards/checkOrder/{orderId} Source: https://docs.oneclickdz.com/quickstart Checks the status of a gift card order and retrieves gift card codes once the order is fulfilled. Requires the order ID and API key. ```APIDOC ## GET /v3/gift-cards/checkOrder/{orderId} ### Description Retrieves gift card codes by checking the status of an order. This endpoint is designed to be polled until the order status is 'FULFILLED'. ### Method GET ### Endpoint https://api.oneclickdz.com/v3/gift-cards/checkOrder/{orderId} ### Parameters #### Path Parameters - **orderId** (string) - Required - The ID of the order to check. #### Headers - **X-Access-Token** (string) - Required - Your API key for authentication. ### Response #### Success Response (200) - **success** (boolean) - Indicates if the request was successful. - **data** (object) - **status** (string) - The current status of the order (e.g., 'HANDLING', 'FULFILLED'). - **cards** (array, optional) - An array of gift card objects if the order is fulfilled. - **value** (number) - The value of the gift card. - **serial** (string) - The serial number or code of the gift card. ### Request Example ```bash curl https://api.oneclickdz.com/v3/gift-cards/checkOrder/6901616fe9e88196b4eb64c0 \ -H "X-Access-Token: YOUR_API_KEY" ``` ### Response Example (Order Handling) ```json { "success": true, "data": { "status": "HANDLING" } } ``` ### Response Example (Order Fulfilled) ```json { "success": true, "data": { "status": "FULFILLED", "cards": [ { "value": 10, "serial": "GCCODE123456789" } ] } } ``` ``` -------------------------------- ### Check Mobile Top-Up Status Source: https://docs.oneclickdz.com/quickstart Check the status of a mobile top-up using its reference ID. ```APIDOC ## GET /v3/mobile/check-ref/{order-id} ### Description Checks the status of a mobile top-up using the provided order reference. ### Method GET ### Endpoint `/v3/mobile/check-ref/{order-id}` #### Path Parameters - **order-id** (string) - Required - The reference ID of the order to check. #### Headers - **X-Access-Token** (string) - Required - Your API key. ### Response #### Success Response (200) - **success** (boolean) - Indicates if the request was successful. - **data** (object) - Contains the top-up status details. - **status** (string) - The current status of the top-up (e.g., PENDING, HANDLING, FULFILLED). - **MSSIDN** (string) - The mobile number that was topped up. - **topup_amount** (number) - The amount of the top-up. #### Response Example ```json { "success": true, "data": { "status": "FULFILLED", "MSSIDN": "0778037340", "topup_amount": 500 } } ``` ``` -------------------------------- ### Place Gift Card Order (cURL, Node.js, Python, PHP) Source: https://docs.oneclickdz.com/quickstart Places a new gift card order with the OneClickDZ API. Requires an API key and specific product/type IDs and quantity. Returns an order ID upon successful placement. ```bash curl https://api.oneclickdz.com/v3/gift-cards/placeOrder \ -X POST \ -H "Content-Type: application/json" \ -H "X-Access-Token: YOUR_API_KEY" \ -d '{ "productId": "PRODUCT_ID", "typeId": "TYPE_ID", "quantity": 1 }' ``` ```javascript const response = await fetch( "https://api.oneclickdz.com/v3/gift-cards/placeOrder", { method: "POST", headers: { "Content-Type": "application/json", "X-Access-Token": "YOUR_API_KEY", }, body: JSON.stringify({ productId: "PRODUCT_ID", typeId: "TYPE_ID", quantity: 1, }), } ); const data = await response.json(); console.log(data); ``` ```python import requests response = requests.post( 'https://api.oneclickdz.com/v3/gift-cards/placeOrder', headers={ 'Content-Type': 'application/json', 'X-Access-Token': 'YOUR_API_KEY' }, json={ 'productId': 'PRODUCT_ID', 'typeId': 'TYPE_ID', 'quantity': 1 } ) print(response.json()) ``` ```php 'PRODUCT_ID', 'typeId' => 'TYPE_ID', 'quantity' => 1 ])); $response = curl_exec($ch); echo $response; ?> ``` -------------------------------- ### Verify API Key with cURL, Node.js, Python, PHP Source: https://docs.oneclickdz.com/quickstart Validate your OneClickDZ API key by sending a GET request to the /v3/validate endpoint. This example shows how to perform the verification using cURL, Node.js, Python, and PHP. Ensure you replace 'YOUR_API_KEY' with your actual API key. ```cURL curl https://api.oneclickdz.com/v3/validate \ -H "X-Access-Token: YOUR_API_KEY" ``` ```Node.js const response = await fetch("https://api.oneclickdz.com/v3/validate", { headers: { "X-Access-Token": "YOUR_API_KEY" }, }); const data = await response.json(); console.log(data); ``` ```Python import requests response = requests.get( "https://api.oneclickdz.com/v3/validate", headers={"X-Access-Token": "YOUR_API_KEY"} ) print(response.json()) ``` ```PHP ``` -------------------------------- ### Get Gift Card Codes (PHP) Source: https://docs.oneclickdz.com/quickstart This PHP code snippet demonstrates how to retrieve gift card codes by calling the getGiftCardCodes function. It checks the status of the response, returning the card details if the status is 'FULFILLED' or waiting for 5 seconds if not. The example includes placeholders for the transaction ID and API key. ```php $status = $response['data']['status']; if ($status === 'FULFILLED') { return $response['data']['cards']; } sleep(5); // Wait 5 seconds } } $cards = getGiftCardCodes('6901616fe9e88196b4eb64c0', 'YOUR_API_KEY'); print_r($cards); ?> ``` -------------------------------- ### Initialize OCPay PHP SDK Source: https://docs.oneclickdz.com/ocpay-guides/6-php-sdk-integration Demonstrates how to initialize the OCPay PHP SDK in your application. It includes including the autoloader and instantiating the OCPay class with an API access token. It also shows how to load the token from environment variables for better security. ```php > /var/log/payment-check.log 2>&1 # Or for Python */20 * * * * /usr/bin/python3 /path/to/cron-job.py >> /var/log/payment-check.log 2>&1 # Or for PHP */20 * * * * /usr/bin/php /path/to/cron-check-payments.php >> /var/log/payment-check.log 2>&1 ``` -------------------------------- ### Internal Server Error Response Example (JSON) Source: https://docs.oneclickdz.com/api-reference/account/get-balance Example of a 500 Internal Server Error response from the API. This indicates a server-side issue, and the message suggests that developers are being notified. ```json { "success": false, "error": { "code": "INTERNAL_SERVER_ERROR", "message": "Developer was notified and will check shortly" }, "requestId": "req_abc123" } ``` -------------------------------- ### Asynchronous Top-up Processing with Queues Source: https://docs.oneclickdz.com/mobile-topup-guides/3-sending-topups Code examples for processing top-up requests asynchronously using message queues. This improves performance by decoupling the request from the immediate fulfillment. It includes queuing a job and processing it, with error handling and potential refunds. ```javascript const Queue = require('bull'); const topupQueue = new Queue('topup-processing'); // Add job to queue async function queueTopUp(orderData) { const order = await db.orders.create({ ...orderData, status: 'QUEUED' }); await topupQueue.add({ orderId: order.id }); return order; } // Process queue topupQueue.process(async (job) => { const { orderId } = job.data; const order = await db.orders.findOne({ where: { id: orderId } }); try { // Send top-up const result = await sendTopUp({ planCode: order.planCode, phone: order.phone, amount: order.amount, ref: order.ref }); // Update order await db.orders.update({ apiTopupId: result.topupId, status: 'PROCESSING' }, { where: { id: orderId } }); // Start status polling (another queue) await pollQueue.add({ topupId: result.topupId, orderId }); } catch (error) { // Handle error await db.orders.update({ status: 'FAILED', errorMessage: error.message }, { where: { id: orderId } }); // Refund user await refundUser(order.userId, order.cost); } }); ``` ```python from celery import Celery app = Celery('topup', broker='redis://localhost:6379/0') @app.task def process_topup(order_id): """Process top-up asynchronously""" order = db.orders.find_one({'_id': order_id}) try: # Send top-up result = send_topup( order['plan_code'], order['phone'], order['amount'], order['ref'] ) # Update order db.orders.update_one( {'_id': order_id}, { '$set': { 'api_topup_id': result['topup_id'], 'status': 'PROCESSING' } } ) # Start status polling poll_topup_status.delay(result['topup_id'], order_id) except Exception as error: # Handle error db.orders.update_one( {'_id': order_id}, { '$set': { 'status': 'FAILED', 'error_message': str(error) } } ) # Refund user refund_user(order['user_id'], order['cost']) # Queue top-up def queue_topup(order_data): order = db.orders.insert_one({ **order_data, 'status': 'QUEUED' }) process_topup.delay(str(order.inserted_id)) return order ``` -------------------------------- ### OCPay SDK Constructor Example Source: https://docs.oneclickdz.com/ocpay-guides/7-nodejs-sdk-integration This example shows how to instantiate the OCPay class with an API access token and optional configuration options like timeout and custom base URL. ```typescript const ocpay = new OCPay('your-api-key', { timeout: 60000, // 60 seconds }); ``` -------------------------------- ### Check Internet Products (v3) - JavaScript, PHP, Python Source: https://docs.oneclickdz.com/migration-from-v2 Fetches a list of available internet products using the v3 API. It makes a GET request to the /v3/internet/products?type=:type endpoint with query parameters and requires an 'X-Access-Token' header for authorization. It checks the 'success' field in the response and accesses the products list from result.data.products. ```javascript const response = await fetch( "https://api.oneclickdz.com/v3/internet/products?type=ADSL", { headers: { "X-Access-Token": API_KEY }, } ); const result = await response.json(); if (result.success) { result.data.products.forEach((card) => { console.log(`${card.value} DA - Available: ${card.available}`); }); } ``` ```php $ch = curl_init('https://api.oneclickdz.com/v3/internet/products?type=ADSL'); curl_setopt($ch, CURLOPT_HTTPHEADER, ['X-Access-Token: ' . $apiKey]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); $result = json_decode($response, true); if ($result['success']) { foreach ($result['data']['products'] as $card) { echo $card['value'] . " DA - Available: " . $card['available'] . "\n"; } } ``` ```python response = requests.get( 'https://api.oneclickdz.com/v3/internet/products?type=ADSL', headers={'X-Access-Token': API_KEY} ) result = response.json() if result['success']: for card in result['data']['products']: print(f"{card['value']} DA - Available: {card['available']}") ``` -------------------------------- ### Unauthorized API Response Example (JSON) Source: https://docs.oneclickdz.com/api-reference/account/get-balance Example of a 401 Unauthorized error response from the API, indicating an invalid access token. The response includes error details and a request ID for tracking. ```json { "success": false, "error": { "code": "INVALID_ACCESS_TOKEN", "message": "The provided access token is invalid" }, "requestId": "req_abc123" } ``` -------------------------------- ### Build Product UI Options (JavaScript) Source: https://docs.oneclickdz.com/internet-topup-guides/1-loading-products Constructs a UI-ready structure for displaying product options, typically for internet services. This function fetches products, filters for availability, calculates customer prices with markup, and sorts the options. It returns an object containing service details and an array of formatted options for UI display. Dependencies include a `cache` object and assumes product data includes `value`, `cost`, and `available` properties. ```javascript async function buildProductOptions(type, markupPercent = 5) { const products = await cache.get(type); return { serviceType: type, serviceName: type === 'ADSL' ? 'ADSL Internet' : '4G LTE Internet', options: products .filter(p => p.available) .map(p => ({ value: p.value, label: `${p.value} DA`, price: Math.ceil(p.cost * (1 + markupPercent / 100)), inStock: true, })) .sort((a, b) => a.value - b.value) // Sort by value ascending }; } // Usage const adslOptions = await buildProductOptions('ADSL', 5); const lteOptions = await buildProductOptions('4G', 5); // Returns UI-ready structure: // { // serviceType: 'ADSL', // serviceName: 'ADSL Internet', // options: [ // { value: 500, label: '500 DA', price: 515, inStock: true }, // { value: 1000, label: '1000 DA', price: 1029, inStock: true }, // ... // ] // } ``` -------------------------------- ### Get Account Balance using Node.js Source: https://docs.oneclickdz.com/api-reference/account/get-balance This Node.js example shows how to fetch your account balance using the fetch API. It uses environment variables for the API key and logs the balance if the request is successful. ```javascript const response = await fetch("https://api.oneclickdz.com/v3/account/balance", { headers: { "X-Access-Token": process.env.ONECLICKDZ_API_KEY, }, }); const data = await response.json(); if (data.success) { console.log(`Balance: ${data.data.balance} DZD`); } ``` -------------------------------- ### OCPay Class Constructor Source: https://docs.oneclickdz.com/ocpay-guides/6-php-sdk-integration Initializes the OCPay SDK client with your API access token and optional configuration. ```APIDOC ## OCPay Class Constructor ### Description Initializes the OCPay SDK. You need to provide your API access token obtained from the OneClickDZ dashboard. ### Method __construct ### Parameters #### Path Parameters - **accessToken** (string) - Required - Your unique API access token. #### Query Parameters - **options** (array) - Optional - An array of options for configuring the underlying HTTP client (e.g., Guzzle). - **timeout** (int) - Optional - The request timeout in seconds. Defaults to 30 seconds. ### Request Example ```php require 'vendor/autoload.php'; use OneClickDz\OCPay\OCPay; // Ensure ONECLICK_API_KEY is set in your environment variables $apiKey = getenv('ONECLICK_API_KEY'); // Initialize with API key and custom timeout $ocpay = new OCPay($apiKey, ['timeout' => 60]); ``` ``` -------------------------------- ### Check Mobile Top-up Status Across Languages Source: https://docs.oneclickdz.com/api-reference/mobile/check-by-id These examples demonstrate how to check the status of a mobile top-up using a provided top-up ID and an API key. They cover cURL, Node.js, Python, and PHP, illustrating different request methods and response handling. ```bash curl https://api.oneclickdz.com/v3/mobile/check-id/6901616fe9e88196b4eb64b0 \ -H "X-Access-Token: YOUR_API_KEY" ``` ```javascript const topupId = "6901616fe9e88196b4eb64b0"; const response = await fetch( `https://api.oneclickdz.com/v3/mobile/check-id/${topupId}`, { headers: { "X-Access-Token": "YOUR_API_KEY" } } ); const { data } = await response.json(); console.log(data.status); ``` ```python import requests topup_id = '6901616fe9e88196b4eb64b0' response = requests.get( f'https://api.oneclickdz.com/v3/mobile/check-id/{topup_id}', headers={'X-Access-Token': 'YOUR_API_KEY'} ) status = response.json()['data']['status'] ``` ```php ``` -------------------------------- ### Caching Strategy: Get Catalog (Node.js, Python) Source: https://docs.oneclickdz.com/api-reference/gift-cards/get-catalog Implements a caching strategy to reduce the number of calls to the gift card catalog API. The cache stores data for a specified duration (TTL) to improve performance. This example shows implementations in both Node.js and Python. ```javascript // Cache for 24 hours const cache = { data: null, timestamp: 0, ttl: 24 * 60 * 60 * 1000, // 24 hours }; async function getCatalog() { const now = Date.now(); if (cache.data && now - cache.timestamp < cache.ttl) { return cache.data; } const response = await fetch( "https://api.oneclickdz.com/v3/gift-cards/catalog", { headers: { "X-Access-Token": process.env.API_KEY }, } ); cache.data = await response.json(); cache.timestamp = now; return cache.data; } ``` ```python from datetime import datetime, timedelta import requests class CatalogCache: def __init__(self): self.data = None self.timestamp = None self.ttl = timedelta(minutes=10) def get(self): if self.data and datetime.now() - self.timestamp < self.ttl: return self.data response = requests.get( 'https://api.oneclickdz.com/v3/gift-cards/catalog', headers={'X-Access-Token': 'YOUR_API_KEY'} ) self.data = response.json() self.timestamp = datetime.now() return self.data catalog_cache = CatalogCache() ``` -------------------------------- ### GET /checkPayment Source: https://docs.oneclickdz.com/ocpay-guides/6-php-sdk-integration This endpoint is used to check the current status of a payment using its reference. It helps in confirming if a payment has been successfully processed. ```APIDOC ## GET /checkPayment ### Description Checks the status of a payment using its unique reference ID. This is crucial for backend systems to confirm successful transactions and update order statuses accordingly. ### Method GET ### Endpoint /checkPayment ### Parameters #### Query Parameters - **paymentRef** (string) - Required - The unique reference ID of the payment to check. ### Request Example ```php // Assuming $ocpay is an initialized OCPay object try { $status = $ocpay->checkPayment('abcdef12345'); // Replace with actual paymentRef if ($status->isConfirmed()) { echo "Payment confirmed!"; } elseif ($status->isFailed()) { echo "Payment failed."; } else { echo "Payment is pending."; } } catch (ApiException $e) { // Handle API errors error_log("Status check failed: " . $e->getMessage()); } ``` ### Response #### Success Response (200) - **status** (string) - The current status of the payment (e.g., 'CONFIRMED', 'PENDING', 'FAILED'). This is a PaymentStatus enum. - **message** (string) - A human-readable message describing the status. - **paymentRef** (string) - The payment reference ID. - **transactionDetails** (object) - Details about the transaction if the payment is confirmed. #### Helper Methods - **isConfirmed()**: Returns true if the payment status is 'CONFIRMED'. - **isPending()**: Returns true if the payment status is 'PENDING'. - **isFailed()**: Returns true if the payment status is 'FAILED'. #### Response Example ```json { "status": "CONFIRMED", "message": "Payment successful", "paymentRef": "abcdef12345", "transactionDetails": { "transactionId": "txn_xyz789", "amount": 8000, "currency": "DZD", "timestamp": "2023-10-27T10:00:00Z" } } ``` ```