PHP code example of manh21 / rajaongkir-laravel

1. Go to this page and download the library: Download manh21/rajaongkir-laravel library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

manh21 / rajaongkir-laravel example snippets


return [
    'api_key' => env('RAJAONGKIR_API_KEY'),
    'base_url' => env('RAJAONGKIR_BASE_URL', 'https://rajaongkir.komerce.id/api/v1'),
    'cost_cache_duration' => env('RAJAONGKIR_COST_CACHE_DURATION', 60), // in minutes
    'location_cache_duration' => env('RAJAONGKIR_LOCATION_CACHE_DURATION', 1440), // in minutes (1 day
];

use Komodo\RajaOngkir\Rajaongkir;
use Komodo\RajaOngkir\Constants\Courier;

$rajaongkir = new Rajaongkir();

// Ambil semua provinsi
$provinces = $rajaongkir->getProvinces();

// Ambil kota berdasarkan provinsi
$cities = $rajaongkir->getCities(11); // DKI Jakarta

// Ambil kecamatan berdasarkan kota
$districts = $rajaongkir->getDistricts(152); // Jakarta Pusat

// Ambil kelurahan berdasarkan kecamatan  
$subdistricts = $rajaongkir->getSubdistricts(1234);

// Menggunakan Courier Enum (Recommended)
$cost = $rajaongkir->calculateDistrictCost(
    originId: 152,           // ID Kecamatan asal
    destinationId: 153,      // ID Kecamatan tujuan
    weight: 1000,           // Berat dalam gram (1kg)
    courier: [              // Array kurir enum
        Courier::JNE,
        Courier::TIKI,
        Courier::SICEPAT
    ],
    sortBy: 'lowest'        // Urutkan berdasarkan harga terendah
);

// Atau menggunakan string values
$cost = $rajaongkir->calculateDistrictCost(
    originId: 152,
    destinationId: 153,
    weight: 1000,
    courier: ['jne', 'tiki', 'sicepat'], // Array string
    sortBy: 'lowest'
);

// Mix enum dan string juga didukung
$cost = $rajaongkir->calculateDistrictCost(
    originId: 152,
    destinationId: 153,
    weight: 1000,
    courier: [
        Courier::JNE,      // Enum
        'tiki',            // String
        Courier::SICEPAT   // Enum
    ],
    sortBy: 'lowest'
);

use Komodo\RajaOngkir\Constants\Courier;
use Komodo\RajaOngkir\Rules\CourierRule;

// Menggunakan enum untuk type safety
$courierCode = Courier::JNE->value; // 'jne'

// Cek kemampuan kurir
if (CourierRule::supportsInternationalCost('jne')) {
    // JNE mendukung ongkir internasional
}

if (CourierRule::supportsAwb('sicepat')) {
    // SiCepat mendukung pelacakan resi
}

// Validasi array kurir (mixed enum & string)
$couriers = [Courier::JNE, 'tiki', Courier::SICEPAT];

if (CourierRule::validateCouriers($couriers)) {
    // Semua kurir valid
    $courierValues = CourierRule::convertCouriersToValues($couriers);
    // Result: ['jne', 'tiki', 'sicepat']
}

// Cek kurir yang tidak valid
$invalidCouriers = CourierRule::getInvalidCouriers(['jne', 'invalid', 'tiki']);
// Result: ['invalid']

// Menggunakan Courier enum
$tracking = $rajaongkir->trackAWB(
    waybill: 'JNE123456789',
    courier: Courier::JNE
);

// Menggunakan string
$tracking = $rajaongkir->trackAWB(
    waybill: 'TIKI987654321',
    courier: 'tiki'
);

// Dengan nomor telepon (untuk kurir tertentu)
$tracking = $rajaongkir->trackAWB(
    waybill: 'SICEPAT123456',
    courier: Courier::SICEPAT,
    last_phone_number: '12345' // 5 digit terakhir nomor penerima
);

// Pencarian destinasi domestik
$destinations = $rajaongkir->searchDomesticDestinations(
    search: 'Jakarta',
    limit: 10,
    offset: 0
);

// Pencarian destinasi internasional
$intlDestinations = $rajaongkir->searchInternationalDestinations(
    search: 'Singapore',
    limit: 10,
    offset: 0
);

// Set custom cache duration
$rajaongkir->setLocationCacheDuration(7200)  // 2 jam untuk data lokasi
          ->setCostCacheDuration(1800);      // 30 menit untuk ongkir

// Clear cache
$rajaongkir->clearLocationCache();           // Hapus cache lokasi
$rajaongkir->clearCostCache();              // Hapus cache ongkir
$rajaongkir->clearCache();                  // Hapus semua cache

use Komodo\RajaOngkir\Exceptions\ApiException;
use Illuminate\Validation\ValidationException;

try {
    $cost = $rajaongkir->calculateDistrictCost(
        originId: 152,
        destinationId: 152, // Error: sama dengan origin
        weight: 50000,      // Error: melebihi batas
        courier: ['invalid'] // Error: kurir tidak valid
    );
} catch (ValidationException $e) {
    // Handle validation errors
    $errors = $e->validator->errors();
    
} catch (ApiException $e) {
    // Handle API errors
    $message = $e->getMessage();
    $statusCode = $e->getStatusCode();
    $response = $e->getResponse();
}

// Example test usage
use Komodo\RajaOngkir\Constants\Courier;
use Komodo\RajaOngkir\Rules\CourierRule;

// Test courier validation
$validator = validator(['courier' => Courier::JNE], [
    'courier' => new CourierRule()
]);
expect($validator->passes())->toBeTrue();

// Test courier conversion
$converted = CourierRule::convertCouriersToValues([Courier::JNE, 'tiki']);
expect($converted)->toBe(['jne', 'tiki']);
bash
php artisan vendor:publish --tag="rajaongkir-laravel-config"