Rust SDK
The official RDCPASS SDK for Rust, published on crates.io as rdcpass. It signs every request, encrypts and decrypts payloads with AES-256-GCM, presents your mTLS client certificate, adds idempotency keys, retries transient failures and verifies webhooks — the complete security stack described in Authentication, handled for you.
Installation
Add rdcpass to your project:
cargo add rdcpass
cargo add tokio --features fullRequirements
- Rust 1.74+ (async, tokio) or later.
- Outbound HTTPS (TLS 1.2 or later) to
gateway.staging.rdcpass.cdfor the staging environment andapi.rdcpass.cdfor production. In production, calls must come from an IP address on your application’s allowlist. - An RDCPASS application with API credentials, created in the console — see Sandbox.
Configuration
Create one client and reuse it across your application: it is safe for concurrent use and keeps connections open between calls. The environment selects the base URL; keys and certificates issued for one environment are rejected by the other.
| Environment | RDCPASS_ENVIRONMENT | Base URL |
|---|---|---|
| Staging environment | sandbox | https://gateway.staging.rdcpass.cd |
| Production | production | https://api.rdcpass.cd |
Configure a client for the staging environment explicitly:
use rdcpass::{Client, Environment};
// Staging environment: https://gateway.staging.rdcpass.cd
pub fn client() -> Result<Client, rdcpass::Error> {
Client::builder()
.environment(Environment::Sandbox)
.key_id("key_test_3c7e1a9f42")
.key_secret(std::env::var("RDCPASS_KEY_SECRET").unwrap_or_default())
.encryption_key(std::env::var("RDCPASS_ENCRYPTION_KEY").unwrap_or_default())
.build()
}Credentials
| Credential | Environment variable | Description |
|---|---|---|
| Key ID | RDCPASS_KEY_ID | Public identifier of your HMAC key, sent with every request (key_test_… in staging, key_live_… in production). |
| Key secret | RDCPASS_KEY_SECRET | HMAC-SHA256 signing secret. Never sent over the network. |
| Payload Encryption Key | RDCPASS_ENCRYPTION_KEY | AES-256-GCM key used to encrypt requests and decrypt responses, and to verify webhook signatures. |
| Environment | RDCPASS_ENVIRONMENT | sandbox or production. Defaults to sandbox. |
| mTLS client certificate and key | — | Issued by RDCPASS for your application; required in production. Must belong to the same application as the key ID. Loaded from files in the client configuration. |
Production and environment variables
When no credentials are passed, the client reads the four environment variables above. In production, add your mTLS client certificate and private key:
use rdcpass::{Client, Identity};
// from_env() reads RDCPASS_KEY_ID, RDCPASS_KEY_SECRET,
// RDCPASS_ENCRYPTION_KEY and RDCPASS_ENVIRONMENT.
// Production (https://api.rdcpass.cd) also requires your mTLS client certificate.
pub fn client() -> Result<Client, Box<dyn std::error::Error>> {
let identity = Identity::from_pem_files("/etc/rdcpass/client.crt", "/etc/rdcpass/client.key")?;
Ok(Client::builder().from_env().identity(identity).build()?)
}Keep secrets out of source code
Load the key secret, the Payload Encryption Key and the certificate’s private key from environment variables or a secrets manager. Never commit them, and never ship them in a mobile or browser application — the SDK is for server-side use.Your first request
Validate a customer by RDCPASS ID with KYC Validation. The SDK encrypts and signs the request, decrypts the response and returns a typed kyc_validation object:
use rdcpass::kyc::KycValidationParams;
use rdcpass::{Client, Identifier, Match};
#[tokio::main]
async fn main() -> Result<(), rdcpass::Error> {
let client = Client::from_env()?;
let params = KycValidationParams::builder()
.reference("cust-0001")
.identifier(Identifier::rdcpass_id("COD-2103-0214-4937"))
.match_claims(Match::new().full_name("Kabeya Mwamba Tshisekedi").date_of_birth("1988-04-12"))
.purpose("customer_onboarding")
.scopes(["kyc.documents.primary", "kyc.phone_numbers"])
.build();
let validation = client.kyc().validations().create(¶ms).await?;
println!("{:?}", validation.result); // Verified
println!("{}", validation.kyc.basic.full_name); // Kabeya Mwamba Tshisekedi
println!("{:?}", validation.scopes_withheld); // []
Ok(())
}{
"id": "kyc_8d2f6a1c93",
"object": "kyc_validation",
"livemode": true,
"reference": "cust-0001",
"status": "completed",
"result": "verified",
"certified_account": true,
"identifier": {
"type": "rdcpass_id",
"value": "COD-2103-0214-4937"
},
"match": {
"full_name": "match",
"date_of_birth": "match",
"age": "not_provided",
"score": 0.98
},
"account": {
"rdcpass_id": "COD-2103-0214-4937",
"status": "active",
"certified": true,
"created_at": "2025-03-14T09:22:41Z",
"level_of_assurance": "LOA3"
},
"kyc": {
"basic": {
"full_name": "Kabeya Mwamba Tshisekedi",
"first_name": "Kabeya",
"last_name": "Tshisekedi",
"date_of_birth": "1988-04-12",
"age": 38,
"gender": "male",
"nationality": "COD"
},
"documents": {
"primary": {
"type": "passport",
"number": "OB1234567",
"issued_at": "2022-06-01",
"expires_at": "2027-05-31",
"issuing_authority": "Direction Générale de Migration",
"status": "valid",
"image": {
"content_type": "image/jpeg",
"url": "https://files.rdcpass.cd/d/9f2c41e8b7a3?sig=Qm9fX2t5Y19zaWc&exp=1790418002",
"expires_at": "2026-09-26T10:20:02Z"
}
}
},
"phone_numbers": [
{
"number": "+243812345678",
"operator": "Vodacom",
"is_primary": true,
"verified": true
},
{
"number": "+243991234567",
"operator": "Airtel",
"is_primary": false,
"verified": true
}
]
},
"scopes_applied": [
"kyc.basic",
"kyc.documents.primary",
"kyc.phone_numbers"
],
"scopes_withheld": [],
"purpose": "customer_onboarding",
"created_at": "2026-09-26T10:15:02Z"
}Every field is documented in KYC Validation.
Calling every service
Every service is exposed as a resource on the client, named after its endpoint. Parameters and responses use the same names and shapes as the API reference.
KYC Validation
Look up an identity by RDCPASS ID, passport, CENI voter card, driving licence or national ID. The result is verified, not_found or not_certified. Reference →
let params = KycValidationParams::builder()
.identifier(Identifier::passport("OB1234567"))
.purpose("customer_onboarding")
.scopes(Vec::<String>::new()) // basic KYC only
.build();
let validation = client.kyc().validations().create(¶ms).await?;
println!("{:?}", validation.result); // Verified | NotFound | NotCertifiedFace Recognition
Compare a photo — sent as base64 data or a url — with the enrolled face of an identity. reason is required; the result is match or no_match. Reference →
use base64::Engine;
let photo = std::fs::read("selfie.jpg")?;
let params = FaceRecognitionParams::builder()
.image(FaceImage::data(base64::engine::general_purpose::STANDARD.encode(photo)))
.identifier(Identifier::rdcpass_id("COD-2103-0214-4937"))
.reason("Current account opening at Gombe branch, Kinshasa")
.purpose("customer_onboarding")
.build();
let recognition = client.face().recognitions().create(¶ms).await?;
println!("{:?}", recognition.result); // Match | NoMatchAge Verification
Check whether a person is over a threshold without receiving their date of birth; read over_threshold. Reference →
let params = AgeVerificationParams::builder()
.identifier(Identifier::rdcpass_id("COD-2103-0214-4937"))
.threshold(18)
.purpose("age_gating")
.build();
let verification = client.age().verifications().create(¶ms).await?;
println!("{}", verification.over_threshold); // trueKYB Verification
Verify a business by rccm, id_nat or nif, and receive its officers and beneficial owners if your application is granted those scopes. Reference →
let params = KybVerificationParams::builder()
.identifier(BusinessIdentifier::rccm("CD/KIN/RCCM/23-B-01234"))
.match_claims(BusinessMatch::new().business_name("Congo Digital Solutions SARL"))
.purpose("customer_onboarding")
.scopes(["kyb.officers", "kyb.beneficial_owners"])
.build();
let business = client.kyb().verifications().create(¶ms).await?;
println!("{:?}", business.result);AML/CTF Screening
Screen a subject against the requested checks; enable monitoring to be notified of new hits. Read risk_level. Reference →
let params = AmlScreeningParams::builder()
.subject(AmlSubject::identifier(Identifier::rdcpass_id("COD-1907-5521-0386")))
.checks(["sanctions", "pep", "adverse_media", "watchlists", "high_risk_jurisdictions"])
.monitoring(true)
.purpose("regulatory_compliance")
.build();
let screening = client.aml().screenings().create(¶ms).await?;
println!("{:?}", screening.risk_level); // Low | Medium | HighCredit Scoring
Requires the customer’s consent in the RDCPASS app (consent.method: rdcpass_app). Returns a score and a band. Reference →
let params = CreditScoreParams::builder()
.identifier(Identifier::rdcpass_id("COD-2103-0214-4937"))
.consent(Consent::rdcpass_app("cns_5e8a2d71c4"))
.purpose("credit_assessment")
.build();
let credit = client.credit().scores().create(¶ms).await?;
println!("{} {:?}", credit.score, credit.band);Fraud Reporting
Report a confirmed or suspected fraud, such as identity_usurpation, against a subject, with a description. Reference →
let params = FraudReportParams::builder()
.kind("identity_usurpation") // serialized as "type"
.subject(FraudSubject::identifier(Identifier::rdcpass_id("COD-2103-0214-4937")))
.description("Account opened with a stolen passport at an agent in Lubumbashi.")
.build();
let report = client.fraud().reports().create(¶ms).await?;
println!("{} {:?}", report.id, report.status);Login with RDCPASS
The login helper builds the /v1/oidc/authorize URL with state and a PKCE code_challenge (S256), exchanges the authorization code at /v1/oidc/token with the matching code_verifier, and calls /v1/oidc/userinfo. See Login with RDCPASS.
use rdcpass::login::{AuthorizationUrlParams, ExchangeCodeParams};
// 1. Build the authorize URL. The SDK generates state and the PKCE
// code_verifier / code_challenge (S256) for you.
let auth = client.login().authorization_url(
&AuthorizationUrlParams::builder()
.client_id("app_8f2a1c0e9b")
.redirect_uri("https://yourapp.example.com/callback")
.scopes(["openid", "profile", "rdcpass:kyc.phone_numbers"])
.build(),
)?;
// Store auth.state and auth.code_verifier in the user's session,
// then redirect to auth.url.
// 2. On your callback, check state and exchange the code.
if returned_state != session.state {
return Err("state mismatch".into());
}
let tokens = client
.login()
.exchange_code(
&ExchangeCodeParams::builder()
.client_id("app_8f2a1c0e9b")
.code(code)
.code_verifier(&session.code_verifier)
.redirect_uri("https://yourapp.example.com/callback")
.build(),
)
.await?;
let user = client.login().user_info(&tokens.access_token).await?;Batches & async
Every service accepts batches at /batches: up to 50 items synchronously, or up to 10,000 asynchronously. With the async option the SDK sends Prefer: respond-async and returns a 202 job or batch object immediately.
- Wait — the wait helper polls
/v1/batches/{id}(or/v1/jobs/{id}for a single async call) with backoff until the status is final, or until your timeout elapses. - Iterate — the results helper pages through
/v1/batches/{id}/resultsand followsnext_cursorfor you. - Or subscribe — instead of polling, handle the
batch.completedandbatch.completed_with_errorswebhooks.
use std::time::Duration;
use futures::StreamExt;
use rdcpass::kyc::{KycValidationBatchParams, KycValidationParams};
use rdcpass::{Identifier, RequestOptions, WaitOptions};
// Submit up to 10,000 items asynchronously (Prefer: respond-async).
let params = KycValidationBatchParams::builder()
.purpose("customer_onboarding")
.item(KycValidationParams::builder().reference("cust-0001").identifier(Identifier::rdcpass_id("COD-2103-0214-4937")).build())
.item(KycValidationParams::builder().reference("cust-0002").identifier(Identifier::ceni("1234567890123")).build())
.build();
let batch = client
.kyc()
.validations()
.batches()
.create_with(¶ms, RequestOptions::new().respond_async())
.await?;
// Poll GET /v1/batches/{id} until the batch reaches a final status.
let done = client
.batches()
.wait(&batch.id, WaitOptions::new().poll_interval(Duration::from_secs(5)).timeout(Duration::from_secs(1800)))
.await?;
println!("{:?} {} {}", done.status, done.succeeded_items, done.failed_items);
// Stream every result; the SDK follows next_cursor page by page.
let mut results = client.batches().results(&batch.id).limit(500).stream();
while let Some(item) = results.next().await {
let item = item?;
println!("{} {:?}", item.reference, item.status);
}Batch quota is separate from single-call quota, and batch items are billed at the discounted batch rate — see Rate limits and Billing.
Webhooks
The webhook helper checks X-RDCPASS-Webhook-Signature — HMAC-SHA256 of {timestamp}.{rawBody} with your Payload Encryption Key — using a constant-time comparison, rejects deliveries whose X-RDCPASS-Webhook-Timestamp is more than 5 minutes from your clock (configurable), and parses the envelope { id, object: "event", type, livemode, created_at, data: { object, previous_attributes } } into a typed event.
use axum::{body::Bytes, extract::State, http::{HeaderMap, StatusCode}};
use rdcpass::webhooks::EventData;
// Use the raw body: the signature covers "{timestamp}.{raw_body}".
async fn rdcpass_webhook(State(client): State<rdcpass::Client>, headers: HeaderMap, body: Bytes) -> StatusCode {
let event = match client.webhooks().construct_event(&body, &headers) {
Ok(event) => event,
Err(_) => return StatusCode::BAD_REQUEST,
};
match event.data {
EventData::Job(job) if event.kind == "kyc_validation.completed" => println!("{} {:?}", job.id, job.status),
EventData::Batch(batch) => println!("{} {}", batch.id, batch.failed_items),
_ => {}
}
StatusCode::OK
}Pass the raw request body, exactly as received — a body parsed and re-serialized by your framework will not match the signature. Respond with a 2xx within 5 seconds and deduplicate on the event id, which is also sent as X-RDCPASS-Webhook-Id. See Webhooks.
Errors
Every API error — { error, message } in the response body — is raised as rdcpass::Error, which carries code, status, message, request_id. Network failures and timeouts that exhaust their retries raise a separate connection error. Quote the request ID when you contact RDCPASS support.
| Code | HTTP | What to do |
|---|---|---|
invalid_identifier | 400 | The identifier is malformed for its type. Fix the input; do not retry. |
insufficient_balance | 402 | Your prepaid balance is too low. Top up in the console. |
scope_not_granted | 403 | A requested scope is not granted to your application. Remove it or request it in the console. |
purpose_not_approved | 403 | The purpose is not approved for your application. |
rate_limited | 429 | Too many requests per second. Retried automatically after Retry-After. |
batch_quota_exceeded | 429 | Your batch quota is used up. Separate from single-call quota. |
let params = KycValidationParams::builder()
.identifier(Identifier::rdcpass_id("COD-2103-0214-4937"))
.purpose("customer_onboarding")
.scopes(["kyc.biometrics.iris"])
.build();
match client.kyc().validations().create(¶ms).await {
Ok(validation) => println!("{:?}", validation.result),
Err(rdcpass::Error::Api(e)) => {
eprintln!("{} {} {} {:?}", e.status, e.code, e.message, e.request_id);
if e.code == "scope_not_granted" {
// 403: request the scope for your application in the console
}
}
Err(other) => return Err(other.into()),
}The full list is in Errors.
Retries & idempotency
- Automatic idempotency keys. Every POST is sent with a generated
Idempotency-Key, reused on each retry of that request, so a retried call is never processed or billed twice. - What is retried.
429responses,5xxresponses, connection failures and timeouts. Other4xxerrors are raised immediately. - Backoff. Exponential backoff with jitter, starting at 0.5 seconds and capped at 8 seconds;
Retry-Afteris honoured when present. Up to 3 retries by default. - Configurable. Change the number of retries per client or per request, and pass your own idempotency key to keep retries safe across process restarts.
let client = Client::builder().from_env().max_retries(5).build()?; // default 3; 0 disables
// Every POST gets an Idempotency-Key automatically. Pass your own to make
// retries safe across process restarts:
let params = FraudReportParams::builder()
.kind("identity_usurpation")
.subject(FraudSubject::identifier(Identifier::rdcpass_id("COD-2103-0214-4937")))
.description("Account opened with a stolen passport.")
.build();
client
.fraud()
.reports()
.create_with(
¶ms,
RequestOptions::new().idempotency_key("fraud-case-INC-2026-88213").max_retries(1),
)
.await?;Timeouts & logging
Each attempt times out after 30 seconds by default; set a different timeout per client or per request. Logs are written through your language’s standard logging interface. They include method, path, status, duration, retry attempts and request ID — never decrypted payloads, secrets or personal data.
use std::time::Duration;
// The SDK emits `tracing` spans and events under the "rdcpass" target.
tracing_subscriber::fmt().with_env_filter("rdcpass=debug").init();
let client = Client::builder()
.from_env()
.timeout(Duration::from_secs(20)) // per attempt (default 30s)
.build()?;
// Override per request.
let params = AmlScreeningParams::builder()
.subject(AmlSubject::identifier(Identifier::rdcpass_id("COD-1907-5521-0386")))
.purpose("regulatory_compliance")
.build();
client
.aml()
.screenings()
.create_with(¶ms, RequestOptions::new().timeout(Duration::from_secs(60)))
.await?;Upgrading & versioning
rdcpassfollows semantic versioning: only major versions contain breaking changes.- Each major version receives security and bug fixes for 24 months after the next major version is released.
- Every release, with upgrade notes for each major version, is listed in the Changelog.
- New API fields and events arrive in minor releases, so keep the SDK up to date to use them.
Integrating without an SDK? See Authentication to sign, encrypt and send requests yourself.