Looking to hire Laravel developers? Try LaraJobs

laravel maintained by opportify

Description
Official Laravel package for Opportify Fraud Protection: check sign-ups and forms for fraud and bots, with Email Insights and IP Insights for security and risk checks.
Author
Last update
2026/12/04 21:01 (dev-main)
License
Downloads
0

Comments
comments powered by Disqus

Opportify for Laravel

CI

The official Laravel package for Opportify Fraud Protection. Opportify analyzes 100+ signals to check each sign-up, form and order for fraud, and gives each one a risk score from 200 (low risk) to 1000 (high risk). You decide what happens next.

In Laravel, that takes one middleware or one validation rule: the package checks the submission for fraud before it reaches your controller. Add the optional Opportify browser script (Full Signal) and behavioral signals join the same risk score.

  • You decide. By default the package only records each risk score in your log and never rejects a submission. You choose if, and from which risk level, submissions are rejected.
  • Fails open. A missing key, a timeout or an API error lets the submission through.
  • Helpful messages. When a submission is rejected, visitors see what they can fix ("Did you mean jane@gmail.com?"), never a score.
  • Laravel native. Route middleware, validation rules, a facade, a Blade component, events, Octane-safe services, and Http::fake() support in your tests.

Email Insights and IP Insights clients are included for when you only need one signal.

Contents

Products

This package gives you access to three Opportify products with one API key.

Fraud Protection gives one advisory risk score per submission, using email, IP, content, velocity and geographic signals together. Add the optional Opportify JS script (Full Signal) and behavioral signals join the same score. Email Insights and IP Insights are also available on their own when you only need one signal.

Fraud Protection Email Insights (standalone) IP Insights (standalone)
One risk score per submission ✅ Email only IP only
Email analysis: deliverability, disposable and role addresses, SPF, DKIM and DMARC, domain ✅ ✅ —
IP analysis: VPN, proxy and Tor, geolocation, WHOIS, blocklists ✅ — ✅
Content analysis, such as gibberish names ✅ — —
Velocity and geographic consistency checks ✅ — —
Behavioral signals with the optional JS script (Full Signal) ✅ — —
Batch analysis and exports — ✅ ✅

Fraud Protection returns the same email and IP analysis fields as Email Insights and IP Insights, alongside its overall score. Scores are advisory: you decide what to do with them. See Fraud Protection, Email Insights, IP Insights and pricing.

Requirements

  • PHP 8.2 or later
  • Laravel 12 or 13 (Laravel 13 needs PHP 8.3)
  • An Opportify account and API key. New accounts start with a 14-day free trial, no credit card required.

Installation

composer require opportify/laravel

The service provider and the Opportify facade are registered automatically. Add your API key to .env:

OPPORTIFY_API_KEY=your-api-key

Publish the config file if you want to change more than the environment variables below:

php artisan vendor:publish --tag=opportify-config

Configuration

Environment variable Default What it does
OPPORTIFY_API_KEY (none) Your secret API key. Without it, checking is skipped and every submission continues.
OPPORTIFY_FRAUD_MODE monitor monitor scores and logs only. block rejects submissions at or above the risk level.
OPPORTIFY_FRAUD_RISK_LEVEL highest lowest, low, medium, high or highest.
OPPORTIFY_GUIDE_EMAIL false Also show a message for fixable email problems below the risk level. See Messages shown to visitors.
OPPORTIFY_TIMEOUT 3 Seconds to wait for the API before failing open.
OPPORTIFY_REQUEST_CONTEXT true Send the visitor's browser headers as Request Context.
OPPORTIFY_BROWSER_SIGNALS false Print the Opportify browser script (Full Signal).
OPPORTIFY_PUBLIC_KEY (none) Your public key (pk_...) for the browser script.
OPPORTIFY_EMAIL_VALIDATION false In-flight email validation in the browser script.
OPPORTIFY_EMAIL_RISK_LEVEL (none) Also reject addresses at or above this Email Insights risk level in the opportify_email rule.
OPPORTIFY_CACHE_TTL 600 Seconds to cache Email Insights and IP Insights results; 0 turns the cache off.
OPPORTIFY_CACHE_STORE default store Cache store for those results.
OPPORTIFY_LOG true Log one line per checked submission.
OPPORTIFY_LOG_CHANNEL default channel Log channel for those lines.

The published config/opportify.php also holds the field map, the email and form error keys and the visitor messages. Logs never contain personal data or the API key: only the outcome, risk level, score, factor codes and submission type.

Behind a load balancer or proxy, configure Laravel's trusted proxies so $request->ip() returns the visitor's address.

Checking submissions for fraud

Middleware

Add the opportify.check middleware to the routes that receive submissions:

use Illuminate\Support\Facades\Route;

Route::post('/register', [RegisteredUserController::class, 'store'])
    ->middleware('opportify.check:registration');

Route::post('/contact', ContactController::class)
    ->middleware('opportify.check:contactForm,block');

The first parameter is the submission type: registration (default), trial, contactForm, leadCapture, subscription, support or checkout. The optional second parameter, monitor or block, overrides OPPORTIFY_FRAUD_MODE for that route.

The middleware runs on POST, PUT and PATCH requests. It sends the visitor's IP address, the Request Context, the browser script's token when present, and the fields named in opportify.fraud.fields (for example email, name, first_name, company, message). Fields that are not in the map, such as passwords, are never sent.

In block mode, a rejected submission gets a normal Laravel validation error, so it works with Blade forms, Inertia and JSON requests alike. The decision is stored on the request for your controller:

use Opportify\Laravel\FraudProtection\FraudProtection;

$decision = $request->attributes->get(FraudProtection::REQUEST_ATTRIBUTE);
$decision?->outcome;           // allowed, flagged, blocked, skipped or error
$decision?->result?->score;    // 200 (lowest risk) to 1000 (highest risk)
$decision?->result?->level;    // RiskLevel enum
$decision?->result?->factors;  // for example ['email:disposable-domain']

Validation rules

Use the rules where you validate the submission, for example in a form request:

use Opportify\Laravel\Rules\OpportifyEmail;
use Opportify\Laravel\Rules\OpportifyFraud;

public function rules(): array
{
    return [
        'email' => ['required', 'email', new OpportifyFraud('registration')],
        // or: 'email' => 'required|email|opportify_fraud:registration',
    ];
}
  • OpportifyFraud (opportify_fraud:<type>,<mode>) checks the whole submission with Fraud Protection, like the middleware. When the middleware already checked the request, the rule reuses its decision and makes no second API call.
  • OpportifyEmail (opportify_email) checks only the email address with Email Insights. It rejects addresses with a suggested correction, an invalid format, and disposable, no-reply or undeliverable addresses (opportify.email.reject), each with its own message. Role addresses such as info@ and a risk level are opt-in:
new OpportifyEmail(['email_role' => true], riskLevel: 'high');

Both rules pass when the API cannot be reached (fail open).

Facade

For custom flows, use the facade:

use Opportify\Laravel\Facades\Opportify;

$fraud = Opportify::fraud();

$check = $fraud->createRequest($request, 'leadCapture'); // IP, Request Context, browser token
$check->email = $request->input('work_email');
$check->companyName = $request->input('company');

$decision = $fraud->check($check);   // never throws

if ($rejection = $fraud->rejection($decision)) {
    return back()->withErrors(['work_email' => $rejection->message]);
}

check() fails open and dispatches events. Opportify::fraud()->analyze($payload) calls the API directly and throws Opportify\Laravel\Exceptions\ApiException on errors; its result includes the full response in $result->raw.

Messages shown to visitors

When a submission is rejected, the package shows the most specific message it can, in this order, following Opportify's guide Turn Fraud Signals into Helpful Guidance:

Situation Shown on Default text
A correction is available email field Did you mean {suggestion}? Please confirm your email address.
Invalid format email field The email address provided does not look valid. Please review it.
Disposable address email field Temporary or disposable email addresses are not accepted. Please use a permanent email address.
No-reply address email field This address cannot receive replies. Please use an email address you can check.
Undeliverable email field We could not confirm this email address with the provider. Could you double-check it?
Role address (shared inbox) email field This looks like a shared inbox. For your account, please use a personal email address.
Tor or open proxy (level high or highest) form The connection you are using was flagged as high risk. Please switch to your regular internet connection to continue.
Blocklisted IP (level high or highest) form Your connection was flagged for suspicious activity. Please try a different network or contact support.
Cloud provider or VPN (level high or highest) form We could not verify your connection. Please try again from a standard home or office network.
Anything else form We couldn't verify some of the details you entered. Please check them and try again.

Visitors never see the score, the level or factor codes.

  • Where messages go. Email messages go on opportify.fraud.email_field (email). Form-level messages go on opportify.fraud.form_error_key, which defaults to the email field because Laravel's starter kits only display field errors. To show them separately, set it to a key of your own and display it: @error('form') {{ $message }} @enderror.
  • Changing the texts. Publish the translations with php artisan vendor:publish --tag=opportify-lang and edit or translate lang/vendor/opportify/en/opportify.php, or override one message in config/opportify.php under messages. {suggestion} and :suggestion are replaced with the suggested address.
  • Helping visitors fix email problems. With OPPORTIFY_GUIDE_EMAIL=true, a submission with a fixable email problem (correction, invalid format, disposable, no-reply or undeliverable) gets its message even when it scored below your risk level, and even in monitor mode, so a real visitor can correct a typo. Role addresses join that list when opportify.fraud.guide_role_address is true. Guidance applies only to a visitor's own form submission, not to console commands or imports.

Full Signal: the browser script

Full Signal is the Fraud Protection API and the Opportify browser script used together, so one risk score uses both enrichment and behavioral signals. The script is off by default. To turn it on:

  1. Add your public key and enable it in .env:

    OPPORTIFY_BROWSER_SIGNALS=true
    OPPORTIFY_PUBLIC_KEY=pk_your_public_key
    
  2. Add the component to the <head> of the layout your forms use:

    <head>
        ...
        <x-opportify::browser-signals />
    </head>
    

    @opportifyBrowserSignals does the same.

The script adds hidden opportifyToken and opportifyFormUUID inputs to your forms. The middleware and the opportify_fraud rule send both, together with the page's hostname as origin (from the browser's Origin header, else APP_URL, else the request host), and only when all three are present. The script runs with data-opty-intercept="disabled", so it never submits a form itself: your Laravel route still receives the submission.

The package loads the latest script version from https://cdn.opportify.ai/f/latest.json, cached for two hours. It accepts only https://cdn.opportify.ai URLs, and falls back to OPPORTIFY_SCRIPT_VERSION (1.6.0) when the manifest or the cache cannot be read, so a CDN or cache outage does not break your pages.

For forms that post JSON (Inertia, fetch, Axios), include the two hidden inputs in the request body. Livewire support is planned for a later release.

Content Security Policy

If your application sends a Content Security Policy, allow:

script-src  https://cdn.opportify.ai
connect-src https://api.opportify.ai https://form.opportify.ai
frame-src   https://cdn.opportify.ai

The component adds a nonce attribute when you pass one (<x-opportify::browser-signals :nonce="$nonce" />) or when your app set one with Vite::useCspNonce(). See Content Security Policy.

In-flight email validation

With OPPORTIFY_EMAIL_VALIDATION=true (and Browser Signals on), the script checks email fields as the visitor types and suggests fixes, such as a typo correction, before the form is submitted. It does nothing while Browser Signals is off. Each check uses Email Insights credits, and the typed address is sent to Opportify before the form is submitted. See in-flight email validation.

Privacy notice

The browser script collects signals about the visitor's browser and how the form is filled in, and in-flight email validation sends the typed email address to Opportify before submit. Update your privacy notice before you turn either on.

Recipes

Laravel Fortify. Fortify validates new users in app/Actions/Fortify/CreateNewUser.php. Add the rule to the email field there:

'email' => ['required', 'string', 'email', 'max:255', Rule::unique(User::class), new OpportifyFraud('registration')],

Starter kits. If your app registers users in its own route file (for example Route::post('register', ...) in routes/auth.php), add the middleware to that route: ->middleware('opportify.check:registration'). If it uses Fortify, use the recipe above.

Custom forms. Add the middleware to the route with the matching submission type, and map your field names in opportify.fraud.fields:

'fields' => [
    'email' => ['work_email', 'email'],
    'companyName' => ['company'],
    // ...
],

Store the result. Listen for SubmissionChecked (see Events) or read the decision from the request in your controller.

Events

Event When
Opportify\Laravel\Events\CheckingSubmission Before a submission is sent. Change $event->request (for example remove a field) or call $event->skip().
Opportify\Laravel\Events\SubmissionChecked Every scored submission, whatever the outcome.
Opportify\Laravel\Events\SubmissionFlagged At or above the risk level in monitor mode. The submission continues.
Opportify\Laravel\Events\SubmissionBlocked At or above the risk level in block mode. The submission is rejected.
Opportify\Laravel\Events\CheckFailed The API could not be reached or returned an error. The submission continues; $event->exception says why.

The events after checking carry $event->request, $event->decision and $event->source (middleware, rule or your own value). For example, to hold flagged accounts for review:

use Illuminate\Support\Facades\Event;
use Opportify\Laravel\Events\SubmissionFlagged;

Event::listen(function (SubmissionFlagged $event) {
    // $event->decision->result->score, ->level, ->factors, ->describeFactors()
});

Request Context

Without the browser script, the API still gets some device context. The package sends these request headers as reserved formData keys, as described in Send Request Context from Your Backend: user_agent, accept_language, referer (scheme, host and path only: the query string and fragment are removed), sec_ch_ua, sec_ch_ua_platform and sec_ch_ua_mobile. Values are trimmed, stripped of control characters and limited to 512 characters. Turn it off with OPPORTIFY_REQUEST_CONTEXT=false, or remove keys in a CheckingSubmission listener.

Email Insights and IP Insights

use Opportify\Laravel\Facades\Opportify;

$email = Opportify::email()->analyze('jane@example.com');
$email['isDeliverable'];         // "yes", "no" or "unknown"
$email['riskReport']['level'];

$ip = Opportify::ip()->analyze('203.0.113.10');
$ip['connectionType'];

Results are cached for OPPORTIFY_CACHE_TTL seconds under hashed keys (no email or IP address is stored in a key). Errors throw Opportify\Laravel\Exceptions\ApiException. For batch analysis and exports, Opportify::email()->sdk() and Opportify::ip()->sdk() return the Opportify PHP SDK clients, configured with your key.

Octane and queues

The package's services keep no request data and read the configuration when they are called. They are bound as scoped services, so Laravel Octane and queue workers get fresh instances for every request and job. The middleware and the rules work on the request they are given.

Testing your application

Fraud Protection calls go through Laravel's HTTP client, so you can fake them, and Telescope records them:

use Illuminate\Support\Facades\Http;

Http::fake([
    'api.opportify.ai/intel/v1/fraud/analyze' => Http::response([
        'score' => 950,
        'level' => 'highest',
        'factors' => ['email:disposable-domain'],
        'sources' => ['email' => ['emailType' => 'disposable']],
    ]),
]);

To skip checking in a test, set config(['opportify.api_key' => null]): every submission continues.

Email Insights and IP Insights calls go through the PHP SDK, which Http::fake() does not see. Mock the client instead:

use Opportify\Laravel\Insights\EmailInsights;

$this->mock(EmailInsights::class)
    ->shouldReceive('analyze')
    ->andReturn(['isDeliverable' => 'yes', 'emailType' => 'free']);

Support

Security

Please report vulnerabilities privately, as described in our security policy. Do not open public issues for security problems.

License

MIT. See LICENSE.