MonCash avec Laravel : comment structurer une intégration propre ?

poze 3 months ago120 gadefr

5

J'ai trouvé des exemples MonCash en PHP « tout dans un fichier ». Je voudrais une intégration propre dans Laravel : où mettre la configuration, le client HTTP, les routes ?

Anviwònman:Laravel 11PHP 8.3

Dyagnostik IA

Se IA ki fè l. Se pa yon repons — kominote a anba a konfime oswa korije l. Toujou verifye anvan ou fye l.

1 Repons

3
✓
✓ Repons yo aksepte

Une structure qui tient la route :

1. Configuration, dans config/services.php :

'moncash' => [
    'client_id' => env('MONCASH_CLIENT_ID'),
    'secret'    => env('MONCASH_CLIENT_SECRET'),
    'api'       => env('MONCASH_API', 'https://sandbox.moncashbutton.digicelgroup.com/Api'),
    'gateway'   => env('MONCASH_GATEWAY', 'https://sandbox.moncashbutton.digicelgroup.com/Moncash-middleware'),
],

2. Un service dédié, app/Services/MonCash.php :

class MonCash
{
    public function token(): string
    {
        // Le token vit environ une minute : on le met en cache un peu moins longtemps.
        return Cache::remember('moncash.token', 45, function () {
            return Http::asForm()
                ->withBasicAuth(config('services.moncash.client_id'), config('services.moncash.secret'))
                ->post(config('services.moncash.api').'/oauth/token', [
                    'scope' => 'read,write',
                    'grant_type' => 'client_credentials',
                ])->throw()->json('access_token');
        });
    }
 
    public function createPayment(string $orderId, int $amount): string
    {
        $token = Http::withToken($this->token())
            ->post(config('services.moncash.api').'/v1/CreatePayment', compact('orderId', 'amount'))
            ->throw()->json('payment_token.token');
 
        return config('services.moncash.gateway').'/Payment/Redirect?token='.urlencode($token);
    }
 
    public function transaction(string $transactionId): ?array
    {
        return Http::withToken($this->token())
            ->post(config('services.moncash.api').'/v1/RetrieveTransactionPayment', compact('transactionId'))
            ->json('payment');
    }
}

3. Contrôleur et routes : POST /checkout/{order} redirige vers createPayment(), et GET /moncash/retour appelle transaction(), vérifie message === 'successful' et le montant, puis marque la commande payée dans une transaction DB.

Injectez MonCash par le conteneur. En test, vous le remplacez par un faux avec $this->mock(MonCash::class), sans jamais appeler l'API réelle.

Konekte pou di lòt moun si li te mache.

answered 3 months ago

Sign in and verify your email to post an answer.