Skip to content

Instantly share code, notes, and snippets.

@pipethedev
Created December 7, 2023 06:54
Show Gist options
  • Save pipethedev/dfb0d1fc5656d3d1bd590100912dead2 to your computer and use it in GitHub Desktop.
Save pipethedev/dfb0d1fc5656d3d1bd590100912dead2 to your computer and use it in GitHub Desktop.
Idempotency
<?php
namespace App\Http\Middleware;
use App\Repository\TransactionRepository;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Validation\ValidationException;
class Idempotency
{
/**
* Handle an incoming request.
*
* @param Request $request
* @param Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
* @return mixed
* @throws ValidationException
*/
public function handle(Request $request, Closure $next)
{
$idempotentKey = $request->header('X-Payment-Key');
$cacheKey = Cache::get($idempotentKey);
if(!$idempotentKey){
$this->setError('X-Payment-Key', 'The idempotent header key is missing');
}
if (base64_encode(base64_decode($idempotentKey, true)) !== $idempotentKey){
$this->setError('X-Payment-Key', 'The idempotent header key is not a valid base64 string');
}
if($cacheKey){
$this->setError('X-Payment-Key', 'This subscriptions is already processing');
}
Cache::put($idempotentKey, $idempotentKey);
return $next($request);
}
private function setError(string $field, string $error)
{
throw ValidationException::withMessages([
$field => [$error],
]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment