# Laravel

> A Laravel service using the HTTP client, a controller, routes with throttling, and configuration.

`.env`:

```bash
OTP_PS_API_KEY=otp_test_…
OTP_PS_BASE_URL=https://otp.ps
```

```php title="examples/laravel/config/services.php"
<?php
// Add this entry to the array in config/services.php, and to .env:
//   OTP_PS_API_KEY=otp_test_…
//   OTP_PS_BASE_URL=https://otp.ps
return [
    'otp_ps' => [
        'key' => env('OTP_PS_API_KEY'),
        'url' => env('OTP_PS_BASE_URL', 'https://otp.ps'),
    ],
];
```

```php title="examples/laravel/app/Services/OtpPs.php"
<?php

namespace App\Services;

use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\Http;

class OtpPs
{
    private function client()
    {
        return Http::baseUrl(rtrim(config('services.otp_ps.url'), '/') . '/api/v1')
            ->withToken(config('services.otp_ps.key'))
            ->acceptJson()
            ->timeout(15);
    }

    /** Returns the verification; throws RequestException on an error answer ($e->response->json('error')). */
    public function send(string $phone, string $purpose = 'verify', string $locale = 'ar', ?string $idempotencyKey = null): array
    {
        $request = $this->client();
        if ($idempotencyKey) {
            $request = $request->withHeaders(['Idempotency-Key' => $idempotencyKey]);
        }
        return $request->post('/verify/send', compact('phone', 'purpose', 'locale'))->throw()->json();
    }

    /** Trust only $result['valid'] === true. */
    public function check(string $id, string $code): array
    {
        return $this->client()->post('/verify/check', compact('id', 'code'))->throw()->json();
    }

    public static function errorCode(RequestException $e): string
    {
        return (string) ($e->response->json('error') ?? 'unknown');
    }
}
```

```php title="examples/laravel/app/Http/Controllers/PhoneVerificationController.php"
<?php

namespace App\Http\Controllers;

use App\Services\OtpPs;
use Illuminate\Http\Client\RequestException;
use Illuminate\Http\Request;

class PhoneVerificationController extends Controller
{
    public function send(Request $request, OtpPs $otp)
    {
        $data = $request->validate(['phone' => 'required|string|max:30', 'locale' => 'in:ar,en']);
        try {
            $v = $otp->send($data['phone'], 'verify', $data['locale'] ?? 'ar');
        } catch (RequestException $e) {
            $code = OtpPs::errorCode($e);
            return response()->json(['error' => $code, 'retryAfter' => $e->response->json('retry_after')], $code === 'rate_limited' ? 429 : 422);
        }
        // Keep the id and the number in the session; the browser only learns that a code was sent.
        $request->session()->put('otp_pending', ['id' => $v['id'], 'phone' => $data['phone']]);
        return response()->json(['sent' => true, 'to' => $v['to'], 'expiresAt' => $v['expires_at']]);
    }

    public function check(Request $request, OtpPs $otp)
    {
        $data = $request->validate(['code' => 'required|string|max:10']);
        $pending = $request->session()->get('otp_pending');
        if (!$pending) {
            return response()->json(['error' => 'no_code'], 422);
        }
        try {
            $r = $otp->check($pending['id'], $data['code']);
        } catch (RequestException $e) {
            return response()->json(['error' => OtpPs::errorCode($e)], 422);
        }
        if ($r['valid'] === true) {
            $request->session()->forget('otp_pending');
            // The number is verified: save it on the user / order here, e.g.
            // $request->user()?->forceFill(['phone' => $pending['phone'], 'phone_verified_at' => now()])->save();
            $request->session()->put('verified_phone', $pending['phone']);
            return response()->json(['verified' => true]);
        }
        if ($r['status'] !== 'pending') {
            $request->session()->forget('otp_pending');
        }
        return response()->json(['verified' => false, 'status' => $r['status'], 'attemptsLeft' => $r['attempts_left']], 422);
    }
}
```

```php title="examples/laravel/routes/web.php"
<?php
// In routes/web.php (session and CSRF protection included). The throttle is your own limit per visitor.
use App\Http\Controllers\PhoneVerificationController;
use Illuminate\Support\Facades\Route;

Route::post('/otp/send', [PhoneVerificationController::class, 'send'])->middleware('throttle:5,15');
Route::post('/otp/check', [PhoneVerificationController::class, 'check'])->middleware('throttle:20,15');
```

The routes are in `web.php`, so Laravel's session and CSRF protection apply: send the CSRF token with your `fetch` calls (`X-CSRF-TOKEN` from the `csrf-token` meta tag). These files are syntax-checked on every change; the Laravel framework itself isn't run in OTP.ps's tests.
