Plataformas
PHP y Laravel
PHP sin más o Laravel, con cURL o el cliente HTTP de Laravel.
Los ejemplos de código, los puntos finales y los códigos de error son los mismos en todos los idiomas.
PHP básico (cURL)
php
<?php
function tryOn(string $personPath, string $garmentUrl): string {
$ch = curl_init("https://www.tryoncloud.com/api/v1/generate");
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 120,
CURLOPT_HTTPHEADER => ["X-API-KEY: " . getenv("TRYONCLOUD_API_KEY")],
CURLOPT_POSTFIELDS => [
"person_image" => new CURLFile($personPath),
"garment_url" => $garmentUrl,
],
]);
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($status !== 200) {
$err = json_decode($body, true);
throw new RuntimeException($err["code"] . ": " . $err["error"]);
}
return $body; // the PNG
}Laravel
.env:
bash
TRYONCLOUD_API_KEY=tk_dev_v1_your_key_hereControlador:
php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
class TryOnController extends Controller
{
public function store(Request $request)
{
$request->validate([
'person' => 'required|image|max:15360',
'garment_url' => 'required|url',
]);
$res = Http::withHeaders(['X-API-KEY' => env('TRYONCLOUD_API_KEY')])
->timeout(120)
->attach('person_image', file_get_contents($request->file('person')->path()), 'person.jpg')
->post('https://www.tryoncloud.com/api/v1/generate', [
'garment_url' => $request->input('garment_url'),
]);
if ($res->failed()) {
return response()->json($res->json(), $res->status());
}
return response($res->body(), 200)->header('Content-Type', 'image/png');
}
}Consejo: En el entorno de producción, lee la clave con
config('services.tryoncloud.key') en lugar de env(), para que siga funcionando con la caché de configuración de Laravel.