PHPackages                             keenops/php-nhiftz - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. keenops/php-nhiftz

ActiveLibrary[API Development](/categories/api)

keenops/php-nhiftz
==================

PHP wrapper for the NHIF Tanzania ServiceHub and OCS APIs

v0.1.0(3w ago)03↓100%MITPHPPHP ^8.2

Since May 18Pushed 2w agoCompare

[ Source](https://github.com/keenops/php-nhiftz)[ Packagist](https://packagist.org/packages/keenops/php-nhiftz)[ Docs](https://github.com/keenops/php-nhiftz)[ RSS](/packages/keenops-php-nhiftz/feed)WikiDiscussions main Synced 1w ago

READMEChangelog (2)Dependencies (5)Versions (3)Used By (0)

PHP NHIF Tanzania API Wrapper
=============================

[](#php-nhif-tanzania-api-wrapper)

A framework-agnostic PHP 8.2+ library for integrating with NHIF Tanzania's ServiceHub and OCS (Online Claims Submission) APIs.

Features
--------

[](#features)

- Full coverage of NHIF ServiceHub API (Verification, Admissions, Approvals, Referrals, etc.)
- Full coverage of NHIF OCS API (Claims, Packages, Facilities, Reference)
- OAuth2 client credentials authentication with automatic token refresh
- PSR-18 HTTP client compatible (Guzzle included by default)
- PSR-16 cache support for token caching
- Laravel and Symfony framework integrations
- Strongly typed DTOs for request/response handling

Requirements
------------

[](#requirements)

- PHP 8.2 or higher
- Guzzle HTTP client (or any PSR-18 compatible client)

Installation
------------

[](#installation)

```
composer require keenops/php-nhiftz
```

Quick Start
-----------

[](#quick-start)

### Basic Usage

[](#basic-usage)

```
use Keenops\PhpNhiftz\NhifClient;
use Keenops\PhpNhiftz\Config\Configuration;
use Keenops\PhpNhiftz\Config\Environment;

$config = new Configuration(
    clientId: 'your_client_id',
    clientSecret: 'your_client_secret',
    facilityCode: 'FAC001',
    environment: Environment::SANDBOX, // or Environment::PRODUCTION
);

$nhif = new NhifClient($config);
$nhif->setUsername('your_username');

// Verify a card
$response = $nhif->serviceHub()->verification()->getCardDetails('12345678');

if ($response->isSuccessful()) {
    $cardDetails = $response->json();
    // Process card details...
}
```

### Card Verification with Biometrics

[](#card-verification-with-biometrics)

```
use Keenops\PhpNhiftz\DTOs\ServiceHub\VerifyCardModel;

$verification = new VerifyCardModel(
    cardNo: '12345678',
    verifierId: 'VER001',
    cardTypeId: '1',
    visitTypeId: 1,
    biometricMethod: 'fingerprint',
    fpCode: 'R1',
);

$response = $nhif->serviceHub()->verification()->verifyCard($verification);
```

### Patient Admission

[](#patient-admission)

```
use Keenops\PhpNhiftz\DTOs\ServiceHub\PatientAdmissionModel;

$admission = new PatientAdmissionModel(
    authorizationNo: 'AUTH123',
    fullName: 'John Doe',
    gender: 'M',
    dateOfBirth: new DateTime('1990-01-15'),
    admissionTypeId: 1,
    wardTypeId: 2,
    roomTypeId: 1,
    chargesPerDay: 50000.00,
    practitionerNo: 'PRAC001',
    dateAdmitted: new DateTime(),
);

$response = $nhif->serviceHub()->admissions()->admitPatient($admission);
```

### Claim Submission

[](#claim-submission)

```
use Keenops\PhpNhiftz\DTOs\OCS\Folio;
use Keenops\PhpNhiftz\DTOs\OCS\FolioItem;
use Keenops\PhpNhiftz\DTOs\OCS\FolioDisease;

$folio = new Folio(
    facilityCode: 'FAC001',
    claimYear: 2026,
    claimMonth: 3,
    folioNo: 1,
    cardNo: '12345678',
    firstName: 'John',
    lastName: 'Doe',
    gender: 'M',
    dateOfBirth: new DateTime('1990-01-15'),
    attendanceDate: new DateTime('2026-03-15'),
    authorizationNo: 'AUTH123',
    amountClaimed: 150000.00,
    folioItems: [
        new FolioItem(
            itemCode: 'ITEM001',
            unitPrice: 50000.00,
            itemQuantity: 3,
            amountClaimed: 150000.00,
        ),
    ],
    folioDiseases: [
        new FolioDisease(diseaseCode: 'A00'),
    ],
);

$response = $nhif->ocs()->claims()->submitFolio($folio);
```

Laravel Integration
-------------------

[](#laravel-integration)

### Service Provider Registration

[](#service-provider-registration)

Add the service provider to your `config/app.php` (Laravel &lt; 11) or it will be auto-discovered:

```
'providers' => [
    // ...
    Keenops\PhpNhiftz\Integrations\Laravel\NhifServiceProvider::class,
],

'aliases' => [
    // ...
    'Nhif' => Keenops\PhpNhiftz\Integrations\Laravel\NhifFacade::class,
],
```

### Publish Configuration

[](#publish-configuration)

```
php artisan vendor:publish --tag=nhif-config
```

### Environment Variables

[](#environment-variables)

Add to your `.env` file:

```
NHIF_CLIENT_ID=your_client_id
NHIF_CLIENT_SECRET=your_client_secret
NHIF_FACILITY_CODE=FAC001
NHIF_ENVIRONMENT=sandbox
NHIF_SCOPE=onlineServices
NHIF_TIMEOUT=30
```

### Username Resolver

[](#username-resolver)

The NHIF API requires a username for token authentication. Instead of calling `setUsername()` before every request, you can configure a username resolver that dynamically resolves the username (e.g., from the authenticated user).

**Option 1: Class-based resolver (recommended, config-cache safe)**

Create an invokable class:

```
// app/Nhif/StaffUsernameResolver.php
namespace App\Nhif;

use Keenops\PhpNhiftz\Contracts\UsernameResolverInterface;

class StaffUsernameResolver implements UsernameResolverInterface
{
    public function __invoke(): ?string
    {
        // Resolve username from your application's context
        return auth()->user()?->nhif_username;
    }
}
```

Then set it in `config/nhif.php`:

```
'username_resolver' => \App\Nhif\StaffUsernameResolver::class,
```

**Option 2: Closure in AppServiceProvider**

```
// app/Providers/AppServiceProvider.php
public function boot(): void
{
    app('nhif')->setUsernameResolver(function () {
        return auth()->user()?->nhif_username;
    });
}
```

**Option 3: Manual (per-request)**

```
Nhif::setUsername('username');
```

### Usage with Facade

[](#usage-with-facade)

```
use Keenops\PhpNhiftz\Integrations\Laravel\NhifFacade as Nhif;

$response = Nhif::serviceHub()->verification()->getCardDetails('12345678');
```

### Usage with Dependency Injection

[](#usage-with-dependency-injection)

```
use Keenops\PhpNhiftz\NhifClient;

class PatientController extends Controller
{
    public function verify(NhifClient $nhif, string $cardNo)
    {
        return $nhif->serviceHub()->verification()->getCardDetails($cardNo);
    }
}
```

Symfony Integration
-------------------

[](#symfony-integration)

### Register the Bundle

[](#register-the-bundle)

```
// config/bundles.php
return [
    // ...
    Keenops\PhpNhiftz\Integrations\Symfony\NhifBundle::class => ['all' => true],
];
```

### Configuration

[](#configuration)

```
# config/packages/nhif.yaml
nhif:
    client_id: '%env(NHIF_CLIENT_ID)%'
    client_secret: '%env(NHIF_CLIENT_SECRET)%'
    facility_code: '%env(NHIF_FACILITY_CODE)%'
    environment: '%env(NHIF_ENVIRONMENT)%'
    username_resolver: App\Nhif\StaffUsernameResolver  # Optional: service ID of an invokable class
```

### Username Resolver

[](#username-resolver-1)

Register your resolver as a service, then reference it in the config:

```
// src/Nhif/StaffUsernameResolver.php
namespace App\Nhif;

use Keenops\PhpNhiftz\Contracts\UsernameResolverInterface;

class StaffUsernameResolver implements UsernameResolverInterface
{
    public function __invoke(): ?string
    {
        // Resolve username from your application's context
        return $this->security->getUser()?->getNhifUsername();
    }
}
```

### Usage

[](#usage)

```
use Keenops\PhpNhiftz\NhifClient;

class PatientController extends AbstractController
{
    public function __construct(private NhifClient $nhif) {}

    public function verify(string $cardNo): Response
    {
        $response = $this->nhif->serviceHub()->verification()->getCardDetails($cardNo);
        // ...
    }
}
```

Comprehensive Documentation
---------------------------

[](#comprehensive-documentation)

For detailed API documentation including all endpoints, parameters, payloads, and expected responses, see:

- **[ServiceHub API Documentation](docs/SERVICEHUB.md)** - Complete guide to all 9 ServiceHub services (~85 endpoints)
- **[OCS API Documentation](docs/OCS.md)** - Complete guide to all 4 OCS services (28 endpoints)

Available Services
------------------

[](#available-services)

### ServiceHub API

[](#servicehub-api)

ServiceDescriptionEndpoints`verification()`Card verification, member details, biometrics18`admissions()`Patient admission, discharge, transfer15`approvals()`Service authorization and approval requests31`attendance()`Practitioner login/logout2`history()`Patient visit history and medical records3`issues()`Claim issues management7`preApprovals()`Pre-approval service requests6`reference()`Reference data (facilities, visit types, etc.)4`referrals()`Service and treatment referrals7### OCS API

[](#ocs-api)

ServiceDescriptionEndpoints`claims()`Folio submission, signing, claim retrieval9`facilities()`Facility listing1`packages()`Price packages, benefit schemes, services16`reference()`Disease codes, cache management2Error Handling
--------------

[](#error-handling)

```
use Keenops\PhpNhiftz\Exceptions\AuthenticationException;
use Keenops\PhpNhiftz\Exceptions\ApiException;
use Keenops\PhpNhiftz\Exceptions\NetworkException;
use Keenops\PhpNhiftz\Exceptions\ValidationException;

try {
    $response = $nhif->serviceHub()->verification()->getCardDetails('12345678');
} catch (AuthenticationException $e) {
    // Handle authentication errors (invalid credentials, expired token)
} catch (ApiException $e) {
    // Handle API errors (4xx, 5xx responses)
    $statusCode = $e->getCode();
    $context = $e->getContext();
} catch (NetworkException $e) {
    // Handle network errors (connection failures, timeouts)
} catch (ValidationException $e) {
    // Handle validation errors
}
```

Custom HTTP Client
------------------

[](#custom-http-client)

You can provide your own PSR-18 compatible HTTP client:

```
use GuzzleHttp\Client;

$httpClient = new Client([
    'timeout' => 60,
    'verify' => true,
]);

$nhif = new NhifClient($config, $httpClient);
```

Token Caching
-------------

[](#token-caching)

Provide a PSR-16 compatible cache to persist tokens:

```
use Symfony\Component\Cache\Psr16Cache;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;

$cache = new Psr16Cache(new FilesystemAdapter());
$nhif = new NhifClient($config, null, $cache);
```

Testing
-------

[](#testing)

```
composer test
```

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE) for more information.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

Security
--------

[](#security)

If you discover any security related issues, please email  instead of using the issue tracker.

###  Health Score

37

—

LowBetter than 81% of packages

Maintenance96

Actively maintained with recent releases

Popularity4

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity37

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

2

Last Release

22d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/979e7b5ad115c575c452f36f2316011ad49f9bb01cf45c5eb68d069af01ed64e?d=identicon)[kimwalu](/maintainers/kimwalu)

---

Top Contributors

[![keenops](https://avatars.githubusercontent.com/u/37520787?v=4)](https://github.com/keenops "keenops (1 commits)")

---

Tags

apisdktanzaniahealthcareocsclaimsnhifservicehub

###  Code Quality

TestsPest

### Embed Badge

![Health badge](/badges/keenops-php-nhiftz/health.svg)

```
[![Health](https://phpackages.com/badges/keenops-php-nhiftz/health.svg)](https://phpackages.com/packages/keenops-php-nhiftz)
```

###  Alternatives

[civicrm/civicrm-core

Open source constituent relationship management for non-profits, NGOs and advocacy organizations.

744284.3k34](/packages/civicrm-civicrm-core)[tempest/framework

The PHP framework that gets out of your way.

2.2k31.1k11](/packages/tempest-framework)[theodo-group/llphant

LLPhant is a library to help you build Generative AI applications.

1.7k371.6k5](/packages/theodo-group-llphant)[telnyx/telnyx-php

Official Telnyx PHP SDK — APIs for Voice, SMS, MMS, WhatsApp, Fax, SIP Trunking, Wireless IoT, Call Control, and more. Build global communications on Telnyx's private carrier-grade network.

35729.6k2](/packages/telnyx-telnyx-php)[yoti/yoti-php-sdk

Yoti SDK for quickly integrating your PHP backend with Yoti

27565.3k1](/packages/yoti-yoti-php-sdk)[n1ebieski/ksef-php-client

PHP API client that allows you to interact with the API Krajowego Systemu e-Faktur

8554.6k](/packages/n1ebieski-ksef-php-client)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
