Created
December 7, 2023 06:54
-
-
Save pipethedev/dfb0d1fc5656d3d1bd590100912dead2 to your computer and use it in GitHub Desktop.
Idempotency
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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