Java Implementation

Digicaisse API Client

← Retour à l'accueil

À propos de cet exemple

Cet exemple Java démontre comment intégrer l'API Digicaisse Abonnement en utilisant :

  • Java 11+ avec HttpClient natif
  • HMAC SHA256 pour l'authentification
  • Jackson pour la sérialisation JSON
  • Support des opérations Event Push et Batch JSON
DigicaisseClient.java
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.*;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * Digicaisse APIs Client - Java Implementation
 * 
 * This example demonstrates how to integrate with the Digicaisse APIs
 * using Java 11+ with HttpClient and HMAC SHA256 authentication.
 */
public class DigicaisseClient {
    private static final String API_BASE_URL = "http://localhost:5000";
    private static final String PUBLIC_KEY = "pk_prod_sonatel";
    private static final String SECRET_KEY = "sk_prod_secret_sonatel";
    
    /**
     * Generate HMAC SHA256 signature for API authentication.
     * 
     * @param secretKey The secret key
     * @param timestamp Unix timestamp in seconds
     * @param method HTTP method (GET, POST, etc.)
     * @param path API path
     * @param body Request body (empty string for GET requests)
     * @return HMAC signature in format "v1=<hex_signature>"
     */
    private static String generateHmacSignature(String secretKey, String timestamp, 
                                                String method, String path, String body) 
        throws Exception {
        String stringToSign = timestamp + "\n" + method + "\n" + path + "\n" + body;
        
        Mac mac = Mac.getInstance("HmacSHA256");
        SecretKeySpec secretKeySpec = new SecretKeySpec(
            secretKey.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
        mac.init(secretKeySpec);
        
        byte[] hash = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8));
        StringBuilder hexString = new StringBuilder();
        for (byte b : hash) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        
        return "v1=" + hexString.toString();
    }
    
    /**
     * Create a single Abonnement operation (Event Push).
     */
    public static void createOperation() throws Exception {
        // Prepare request body
        ObjectMapper mapper = new ObjectMapper();
        Map<String, Object> operation = new HashMap<>();
        operation.put("ligne_sonatel", "1001");
        operation.put("client_digicaisse", "221770001122");
        operation.put("type_operation", "MISE_EN_SERVICE");
        operation.put("date_effet", "2025-10-28");
        operation.put("details", "");
        
        String body = mapper.writeValueAsString(operation);
        String method = "POST";
        String path = "/v1/subscription/operations";
        String timestamp = String.valueOf(Instant.now().getEpochSecond());
        
        // Generate HMAC signature
        String signature = generateHmacSignature(SECRET_KEY, timestamp, method, path, body);
        
        // Create HTTP request
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create(API_BASE_URL + path))
            .header("Content-Type", "application/json")
            .header("X-Api-Key", PUBLIC_KEY)
            .header("X-Timestamp", timestamp)
            .header("X-Signature", signature)
            .header("Idempotency-Key", UUID.randomUUID().toString())
            .POST(HttpRequest.BodyPublishers.ofString(body))
            .build();
        
        // Send request
        HttpResponse<String> response = client.send(request, 
            HttpResponse.BodyHandlers.ofString());
        
        System.out.println("Status: " + response.statusCode());
        System.out.println("Response: " + response.body());
    }
    
    /**
     * Create multiple Abonnement operations (Batch JSON).
     */
    public static void createBatch() throws Exception {
        // Prepare batch request
        ObjectMapper mapper = new ObjectMapper();
        Map<String, Object> batch = new HashMap<>();
        batch.put("date", "2025-10-28");
        
        List<Map<String, Object>> operations = new ArrayList<>();
        
        // Operation 1
        Map<String, Object> op1 = new HashMap<>();
        op1.put("ligne_sonatel", "1001");
        op1.put("client_digicaisse", "221770001122");
        op1.put("type_operation", "MISE_EN_SERVICE");
        op1.put("date_effet", "2025-10-28");
        op1.put("details", "");
        operations.add(op1);
        
        // Operation 2
        Map<String, Object> op2 = new HashMap<>();
        op2.put("ligne_sonatel", "1002");
        op2.put("client_digicaisse", "221770001133");
        op2.put("type_operation", "SUSPENSION");
        op2.put("date_effet", "2025-10-28");
        op2.put("details", "Impayé");
        operations.add(op2);
        
        batch.put("operations", operations);
        
        String body = mapper.writeValueAsString(batch);
        String method = "POST";
        String path = "/v1/subscription/batch";
        String timestamp = String.valueOf(Instant.now().getEpochSecond());
        
        // Generate HMAC signature
        String signature = generateHmacSignature(SECRET_KEY, timestamp, method, path, body);
        
        // Create HTTP request
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create(API_BASE_URL + path))
            .header("Content-Type", "application/json")
            .header("X-Api-Key", PUBLIC_KEY)
            .header("X-Timestamp", timestamp)
            .header("X-Signature", signature)
            .header("Idempotency-Key", UUID.randomUUID().toString())
            .POST(HttpRequest.BodyPublishers.ofString(body))
            .build();
        
        // Send request
        HttpResponse<String> response = client.send(request, 
            HttpResponse.BodyHandlers.ofString());
        
        System.out.println("Status: " + response.statusCode());
        System.out.println("Response: " + response.body());
    }
    
    public static void main(String[] args) {
        try {
            System.out.println("Creating single operation...");
            createOperation();
            
            System.out.println("\nCreating batch operations...");
            createBatch();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Utilisation

Dépendances Maven :

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.15.2</version>
</dependency>

Compilation :

javac -cp ".:jackson-databind-2.15.2.jar" DigicaisseClient.java

Exécution :

java -cp ".:jackson-databind-2.15.2.jar:jackson-core-2.15.2.jar:jackson-annotations-2.15.2.jar" DigicaisseClient