Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Ali Green Laravel Package

james.xue/laravel-ali-green

A Laravel wrapper for Alibaba Cloud Green (Ali Green) adding automated content moderation. Scan text, images, and media for risky or prohibited content through a clean API with facade support, so compliance checks on user-generated content are simple without touching the raw SDK.

View on GitHub
Deep Wiki
Context7

Getting Started

composer require james.xue/laravel-ali-green

The package is auto-discovered. Publish its config then fill in your Alibaba Cloud credentials:

php artisan vendor:publish --tag=ali-green

.env (names may vary slightly — confirm against config/ali-green.php):

ALI_GREEN_ACCESS_KEY_ID=your_key_id
ALI_GREEN_ACCESS_KEY_SECRET=your_key_secret
ALI_GREEN_REGION=cn-shanghai

Where to look first

  1. config/ali-green.php — the only file you are expected to touch. Endpoint, region, scene, and credentials live here.
  2. src/ — the README is thin, so read the facade and service classes to confirm exact method names before wiring them in. Treat the snippets below as the shape of the API, not verbatim signatures.
  3. The underlying Alibaba Green SDK's response schema — everything you return to callers is derived from it.

First use case: gate a text field

The lowest-friction integration is moderating user-submitted text at the boundary (a controller or form request) before it is persisted:

use Xiaoxuan6\LaravelAliGreen\Facades\AliGreen;

$result = AliGreen::text($request->input('body'));

if (! $result->pass()) {
    abort(422, 'Content rejected by moderation');
}

$post = Post::create($request->validated());

Get this path working end-to-end (credentials, region, a passing call, a deliberately failing call) before adding image or video moderation — those introduce async semantics and public-URL requirements that will otherwise mask a simple config error.

Implementation Patterns

Wrap the facade in a thin domain service. The facade returns raw Alibaba structures with nested body / data / results arrays. Normalize once, at the edge, and let the rest of your app consume a stable shape:

final class ModerationResult
{
    public function __construct(
        public readonly bool $passed,
        public readonly array $reasons = [],
        public readonly ?string $taskId = null,
    ) {}
}

class Moderator
{
    public function text(string $content): ModerationResult
    {
        $raw = AliGreen::text($content);
        // Map Alibaba's nested response into your DTO here.
        return new ModerationResult(/* ... */);
    }
}

Every subsequent feature (admin re-scan, audit log, webhook) now depends on your DTO, not on SDK internals.

Validation-rule pattern for text. For forms, a custom rule keeps controllers clean and gives you per-field error messages:

Validator::extend('moderated', function ($attribute, $value) {
    return app(Moderator::class)->text($value)->passed;
});

Queue media moderation. Image and video calls are network-bound and can take seconds (or, for video, require async polling). Dispatch a job from the created/updated observer, set the record to a pending moderation state, and let a queue worker resolve it:

class ModerateImage implements ShouldQueue
{
    public int $tries = 3;

    public function __construct(public Post $post) {}

    public function handle(Moderator $moderator): void
    {
        $result = $moderator->image($this->post->image_url);
        $this->post->update(['moderation_state' => $result->passed ? 'approved' : 'rejected']);
    }
}

Video needs a task lifecycle. Video moderation is asynchronous: the API returns a task/job identifier, and you either poll or receive a callback. Model it explicitly:

$taskId = AliGreen::video($videoUrl);
ModerationTask::create(['id' => $taskId, 'model' => $video->getMorphClass(), 'model_id' => $video->id]);

Then either (a) a scheduled command polls taskId results until terminal, or (b) expose a public, unauthenticated-but-signed callback route that the service hits. The callback route needs CSRF exclusion.

Cache and dedupe. Identical text (headlines, comments) gets moderated repeatedly. Hash the payload (sha1($normalized)) and cache the verdict for a short TTL — cheap, and it flattens spikes from bots or accidental resubmits.

Throttle outbound calls. Wrap in RateLimiter::attempt() or a Redis token bucket keyed by tenant. Alibaba Green enforces QPS quotas per account; when you exceed them you get errors that look like moderation failures if you don't distinguish them.

Test with the facade fake. Laravel facades are mockable, which is the practical way to test without burning API calls:

AliGreen::shouldReceive('text')->once()->andReturn($fakeResponse);

Keep a couple of recorded real responses as fixtures; the response schema is the one thing that will break your DTO silently.

Gotchas and Tips

Media must be publicly reachable by Alibaba's servers. Local paths, paths inside storage/, and signed URLs that expire in seconds will fail. Upload to OSS (or any public HTTPS endpoint) first, then pass the URL. This is the single most common "why does image moderation always fail" cause.

Region and endpoint must match. A cn-shanghai key pointed at a cn-hangzhou endpoint produces auth/403-style errors rather than a clear "wrong endpoint." Keep region and endpoint in one env-driven block.

Use a RAM user, not your root AccessKey. Grant only the Green/content-safety permissions. If you're running across environments, per-env RAM users make it obvious which key leaked.

Text has a length limit (typically ~10k characters per call). Chunk long documents and take the worst verdict, or the API will truncate/error and you'll ship unmoderated content.

Distinguish transport failure from a rejection. A network error, quota error, or auth failure must not silently become "approved." Default to fail-closed for high-risk surfaces (comments, uploads) and fail-open for low-risk ones (profile bios) — but make the choice explicit in code, not implicit in a catch.

Response nesting is inconsistent between text, image, and video calls. Don't write one flattener that assumes a uniform shape; log the raw response once per endpoint during development and map each individually.

Async video has no sandbox and slow turnaround. Build your callback/polling plumbing against a stubbed task first; don't block a request cycle waiting for a verdict.

Pin the dependency. Last release was mid-2023 and the package is small (~63 stars). Use an exact or tight constraint ("james.xue/laravel-ali-green": "^1.0"), and skim src/ before upgrading Laravel or PHP — the SDK it wraps may lag behind framework majors.

Extension points. The config file is the intended customization surface. If you need behavior the package doesn't expose (e.g., different scenes, custom bizType, region failover), bind your own client implementation in a service provider rather than editing vendor files — or call the official Alibaba Cloud SDK directly and drop the wrapper.

Log the decision, not the content. Store verdict, labels, score, and a payload hash in your audit table — not the raw user text and not the raw credentials. Regulatory audits will ask you why something was blocked; they don't need a copy of every comment.

Local development without credentials. There's no local emulator. Provide a Moderator interface with a permissive NoopModerator bound in local/testing so day-to-day development doesn't require live keys — and a strict one everywhere else.

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
skyraptor/chatter
edlugz/sasapay
abbasudo/artisan-route
mirvan/ippanel
ignibyte/aic-framework
glavweb/data-schema-bundle
glavweb/datagrid-bundle
tacticmedia/scim-server
uni-method/frame
neika-ai/sdk
adachsoft/php-code-style
pharaonic/laravel-notification-dependencies
beautinow/translug
dev-brainiac/bot-cloaked
octoberrain/html
octoberrain/extension
octoberrain/exception
octoberrain/contracts
adachsoft/api-version-bundle
cgv/localized-resource