Skip to content
Ivan William edited this page Aug 29, 2026 · 1 revision

Usage

Basic Usage Pattern

All API calls follow the same pattern:

  1. Initialize OAuth2Client — auto-loads env credentials
  2. Initialize SSRequest with the OAuth2 client
  3. Build a FHIR payload using DataType + PayloadBuilder
  4. Send via $ss->post() / $ss->get() / etc.
  5. Inspect the SSResponse
use Satusehat\Integration\SSRequest\SSRequest;
use Satusehat\Integration\OAuth2Client;

// Initialize
$ss = new SSRequest(new OAuth2Client());

// Send a POST request
$resp = $ss->post('Patient', $patientPayload);

// Check result
if ($resp->isSuccess()) {
    $id = $resp->getResourceId();
} else {
    $errors = $resp->getErrorMessages();
}

OAuth2 Flow

The OAuth2Client handles the full OAuth2 flow automatically:

  1. On first request, obtains a bearer token from SATUSEHAT auth endpoint
  2. Attaches the token to all subsequent requests
  3. When the server returns HTTP 401, automatically refreshes the token and retries
use Satusehat\Integration\OAuth2Client;
use Satusehat\Integration\SSRequest\SSRequest;

// Token is obtained and refreshed automatically
$oauth2 = new OAuth2Client();
$ss = new SSRequest($oauth2);

// You can also provide a pre-existing token
$ss = new SSRequest(token: 'your-bearer-token-here');

// Or with a custom base URL
$ss = new SSRequest(
    oauth2: new OAuth2Client(),
    baseUrl: 'https://api-satusehat-stg.dto.kemkes.go.id/fhir-r4/v1'
);

Manual Token Access

$oauth2 = new OAuth2Client();
$token = $oauth2->token(); // Get current bearer token

// Force token refresh
$oauth2->refreshToken();

// Check environment
$env = $oauth2->satusehat_env; // 'DEV' | 'STG' | 'PROD'
$orgId = $oauth2->organization_id;

SSRequest Methods

GET — Read a resource

// Get a single resource by ID
$resp = $ss->get('Patient/12345678-1234-1234-1234-123456789012');

// Search with query parameters
$resp = $ss->get('Patient', [
    'identifier' => 'https://fhir.kemkes.go.id/id/NIK|3312345678901234',
    'birthdate' => '1990-01-15',
    '_count' => 20,
]);

POST — Create a resource

$resp = $ss->post('Patient', $patientPayload);

PUT — Update (full) a resource

$resp = $ss->put('Patient/12345678-1234-1234-1234-123456789012', $patientPayload);

PATCH — Partial update

// JSON Patch (application/json-patch+json)
$resp = $ss->patch('Patient/12345678-1234-1234-1234-123456789012', [
    ['op' => 'replace', 'path' => '/name/0/given/0', 'value' => 'Jane']
]);

// FHIRPath Patch
$resp = $ss->patchFhirPath('Patient/12345678-1234-1234-1234-123456789012', [
    ['path' => 'Patient.name.given[0]', 'value' => 'Jane']
]);

DELETE — Remove a resource

$resp = $ss->delete('Patient/12345678-1234-1234-1234-123456789012');

Bundle — Batch / Transaction

$resp = $ss->postBundle('Bundle', $bundlePayload);

SSResponse Methods

$resp = $ss->post('Patient', $patientPayload);

// Check success
$resp->isSuccess();    // bool — true if 2xx
$resp->isError();      // bool — true if non-2xx

// Get HTTP status code
$resp->getHttpCode();  // int

// Get the parsed response body as array
$resp->getBody();      // array

// Get raw response string
$resp->getContent();   // string

// Extract resource ID (works for POST responses, Bundle entries)
$resp->getResourceId();     // string|null
$resp->get('Patient');     // alias for getResourceId()

// Extract OperationOutcome error messages
$resp->getErrorMessages();  // string[] — extracts issue[].details.text from OperationOutcome

Complete Example: Patient + Encounter + Observation

use Satusehat\Integration\SSRequest\SSRequest;
use Satusehat\Integration\OAuth2Client;
use Satusehat\Integration\DataType\Identifier;
use Satusehat\Integration\DataType\HumanName;
use Satusehat\Integration\DataType\Address;
use Satusehat\Integration\DataType\ContactPoint;
use Satusehat\Integration\DataType\CodeableConcept;
use Satusehat\Integration\DataType\Reference;
use Satusehat\Integration\DataType\Period;
use Satusehat\Integration\DataType\Quantity;
use Satusehat\Integration\DataType\Range;
use Satusehat\Integration\DataType\Coding;
use Satusehat\Integration\Builder\PayloadBuilderPatient;
use Satusehat\Integration\Builder\PayloadBuilderEncounter;
use Satusehat\Integration\Builder\PayloadBuilderObservation;

$ss = new SSRequest(new OAuth2Client());

// --- Build Patient ---
$patient = (new PayloadBuilderPatient)
    ->addIdentifier(new Identifier(
        system: 'https://fhir.kemkes.go.id/id/NIK',
        value: '3312345678901234'
    ))
    ->addName(new HumanName(
        family: 'Doe',
        given: ['John'],
        use: 'official'
    ))
    ->addTelecom(new ContactPoint(
        system: 'phone',
        value: '081234567890',
        use: 'mobile'
    ))
    ->addAddress(new Address(
        use: 'home',
        line: ['Jl. Sudirman No.1'],
        city: 'Jakarta Selatan',
        district: 'Kebayoran Baru',
        state: 'DKI Jakarta',
        postalCode: '12190',
        country: 'ID'
    ))
    ->setGender('male')
    ->setBirthDate('1990-01-15')
    ->setActive(true)
    ->build();

$resp = $ss->post('Patient', $patient);
if (!$resp->isSuccess()) {
    throw new \RuntimeException(implode('; ', $resp->getErrorMessages()));
}
$patientId = $resp->getResourceId();

// --- Build Encounter ---
$encounter = (new PayloadBuilderEncounter)
    ->setStatus('finished')
    ->setClass(new Coding(
        system: 'http://terminology.hl7.org/CodeSystem/v3-ActCode',
        code: 'AMB',
        display: 'ambulatory'
    ))
    ->setSubject(new Reference(
        reference: "Patient/{$patientId}",
        display: 'John Doe'
    ))
    ->setPeriodStart(date('c'))
    ->addReasonText('Pemeriksaan umum')
    ->build();

$resp = $ss->post('Encounter', $encounter);
if (!$resp->isSuccess()) {
    throw new \RuntimeException(implode('; ', $resp->getErrorMessages()));
}
$encounterId = $resp->getResourceId();

// --- Build Observation (Heart Rate) ---
$observation = (new PayloadBuilderObservation)
    ->setStatus('final')
    ->addCategory(new CodeableConcept(
        coding: [new Coding(
            system: 'http://terminology.hl7.org/CodeSystem/observation-category',
            code: 'vital-signs',
            display: 'Vital Signs'
        )]
    ))
    ->setCode(new CodeableConcept(
        coding: [new Coding(
            system: 'http://loinc.org',
            code: '8867-4',
            display: 'Heart rate'
        )]
    ))
    ->setSubject(new Reference(
        reference: "Patient/{$patientId}",
        display: 'John Doe'
    ))
    ->setEncounter(new Reference(
        reference: "Encounter/{$encounterId}"
    ))
    ->setEffectiveDateTime(date('c'))
    ->setValueQuantity(new Quantity(
        value: 72,
        unit: 'beats/minute',
        system: 'http://unitsofmeasure.org',
        code: '/min'
    ))
    ->addReferenceRange(
        low: new Quantity(value: 60, unit: 'bpm', system: 'http://unitsofmeasure.org', code: '/min'),
        high: new Quantity(value: 100, unit: 'bpm', system: 'http://unitsofmeasure.org', code: '/min'),
        text: '60-100 bpm'
    )
    ->build();

$resp = $ss->post('Observation', $observation);

Retry & Error Handling

SSRequest handles retry automatically:

HTTP Code Behavior
401 Unauthorized Auto-refresh token + retry (up to maxRetries)
429 Rate Limited Wait Retry-After header + retry
5xx Server Error Exponential backoff retry
400/403/404/409/412/422 Return immediately (no retry — likely a payload error)
// Custom config
$ss = new SSRequest($oauth2, config: [
    'timeout' => 60,
    'maxRetries' => 3,
    'verify' => true,
    'headers' => ['X-Custom-Header' => 'value'],
]);

Clone this wiki locally