Java
Compatibility
JDK 11+ (native HttpClient). No third-party dependencies.
Client Implementation
java
package com.example.brand;
import java.net.URI;
import java.net.http.*;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.time.Duration;
import java.util.UUID;
public class brandClient {
private static final String APP_ID = "cp_a1b2c3d4...";
private static final String SECRET = "f1e2d3c4...";
private static final String BASE = "https://api.coinepay.net";
private static final HttpClient HTTP = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(10))
.build();
/** Returns the raw HTTP response. Parse the body and check "code" — see Usage. */
public static HttpResponse<String> call(String path, String body, String idempotencyKey) throws Exception {
if (body == null) body = "{}";
String ts = String.valueOf(System.currentTimeMillis() / 1000);
byte[] nonceBytes = new byte[16];
new SecureRandom().nextBytes(nonceBytes);
String nonce = bytesToHex(nonceBytes);
String bodyHash = sha256Hex(body.getBytes("UTF-8"));
String signInput = "POST\n" + path + "\n\n" + ts + "\n" + nonce + "\n" + bodyHash;
String sig = hmacHex(SECRET, signInput);
HttpRequest.Builder b = HttpRequest.newBuilder()
.uri(URI.create(BASE + path))
.timeout(Duration.ofSeconds(30))
.header("X-App-Id", APP_ID)
.header("X-Timestamp", ts)
.header("X-Nonce", nonce)
.header("X-Signature", sig)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(body));
if (idempotencyKey != null) b.header("Idempotency-Key", idempotencyKey);
return HTTP.send(b.build(), HttpResponse.BodyHandlers.ofString());
}
/** Webhook signature verification */
public static boolean verifyWebhook(String sigHeader, String tsHeader,
byte[] rawBody, String webhookSecret) throws Exception {
if (sigHeader == null || !sigHeader.startsWith("v1,")) return false;
String sig = sigHeader.substring(3);
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(webhookSecret.getBytes("UTF-8"), "HmacSHA256"));
mac.update((tsHeader + ".").getBytes("UTF-8"));
mac.update(rawBody);
String expected = bytesToHex(mac.doFinal());
return constantTimeEquals(sig, expected);
}
private static String hmacHex(String key, String data) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256"));
return bytesToHex(mac.doFinal(data.getBytes("UTF-8")));
}
private static String sha256Hex(byte[] b) throws Exception {
return bytesToHex(MessageDigest.getInstance("SHA-256").digest(b));
}
private static String bytesToHex(byte[] b) {
StringBuilder sb = new StringBuilder(b.length * 2);
for (byte x : b) sb.append(String.format("%02x", x));
return sb.toString();
}
private static boolean constantTimeEquals(String a, String b) {
if (a.length() != b.length()) return false;
int diff = 0;
for (int i = 0; i < a.length(); i++) diff |= a.charAt(i) ^ b.charAt(i);
return diff == 0;
}
}Usage
The JDK has no JSON parser; the sample uses Jackson (com.fasterxml.jackson.core:jackson-databind) to read the response — any JSON library works.
java
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.http.HttpResponse;
import java.util.UUID;
public class Demo {
private static final ObjectMapper JSON = new ObjectMapper();
public static void main(String[] args) throws Exception {
// 1. List card headers
HttpResponse<String> resp = brandClient.call(
"/api/v1/openapi/card_headers/list",
"{\"page\":1,\"page_size\":20}",
null);
JsonNode env = JSON.readTree(resp.body());
// Success is "code": 0 — most business errors also arrive with HTTP 200,
// so never decide on resp.statusCode() alone
if (env.path("code").asInt(-1) != 0) {
throw new IllegalStateException("list failed: " + env.path("error_key").asText());
}
System.out.println(env.path("data").path("list").get(0).path("header_id").asText());
// 2. Apply virtual card
String idempotencyKey = UUID.randomUUID().toString(); // reuse the SAME key when retrying
String body = "{\"header_id\":\"hdr_5\",\"package_id\":\"pkg_12\","
+ "\"cardholder_id\":\"chd_1024\"}";
resp = brandClient.call("/api/v1/openapi/card/apply", body, idempotencyKey);
env = JSON.readTree(resp.body());
int code = env.path("code").asInt(-1);
String errorKey = env.path("error_key").asText(""); // stable — branch on this, never on "message"
if (code == 0) {
System.out.println("Created card: " + env.path("data").path("card_id").asText());
} else if (code == 40100) {
// HTTP 401 openapi_invalid_credentials: check APP_ID / SECRET / clock — retrying won't help
throw new IllegalStateException("auth failed: " + errorKey);
} else if (code == 42900) {
// HTTP 429 too_many_requests: wait Retry-After seconds, then retry with the same key
long wait = resp.headers().firstValueAsLong("Retry-After").orElse(60);
System.out.println("rate limited, retry in " + wait + " s");
} else if ("insufficient_balance".equals(errorKey)) {
System.out.println("top up your wallet first");
} else {
throw new IllegalStateException("apply rejected: code=" + code + " error_key=" + errorKey);
}
}
}Webhook Receiver (Spring Boot)
java
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;
import javax.servlet.http.HttpServletRequest;
@RestController
public class WebhookController {
private static final String WEBHOOK_SECRET = System.getenv("BRAND_WEBHOOK_SECRET");
@PostMapping(value = "/webhook", consumes = "application/json")
public ResponseEntity<String> handleWebhook(
@RequestBody byte[] rawBody,
@RequestHeader(value = "Webhook-Signature", required = false) String sig,
@RequestHeader(value = "Webhook-Timestamp", required = false) String ts,
@RequestHeader(value = "Webhook-Id", required = false) String eventId,
@RequestHeader(value = "Webhook-Type", required = false) String eventType
) throws Exception {
if (!brandClient.verifyWebhook(sig, ts, rawBody, WEBHOOK_SECRET)) {
return ResponseEntity.status(401).body("invalid signature");
}
long now = System.currentTimeMillis() / 1000;
if (Math.abs(now - Long.parseLong(ts)) > 300) {
return ResponseEntity.status(401).body("timestamp expired");
}
if (alreadyProcessed(eventId)) return ResponseEntity.ok("");
String payload = new String(rawBody, "UTF-8");
enqueue(eventType, payload);
markProcessed(eventId);
return ResponseEntity.ok("");
}
}Spring Boot raw body
Spring deserializes @RequestBody by default. Use byte[] to receive raw bytes — otherwise the body is parsed and re-serialized, breaking the signature.
Notes
secretSpecusesgetBytes("UTF-8")— never use platform default encoding- Java string
\nliterals in source are0x0A— no special handling needed - Use
MessageDigest.isEqualor your own constant-time compare;String.equalsis not constant-time