Implementaciones listas para usar en tu lenguaje favorito
Ejemplo básico de cómo verificar un certificado académico usando cURL en PHP.
No requiere instalación - PHP nativo con cURL
// Configuración del API
$apiKey = 'tu_api_key_aqui';
$codigoCertificado = 'MF-92FXSP';
// Inicializar cURL
$ch = curl_init('https://api.certuap.com/v1/verify');
// Configurar headers y opciones
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $apiKey,
'Content-Type: application/json'
]);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
'code' => $codigoCertificado
]));
// Ejecutar petición
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
// Procesar respuesta
if ($httpCode === 200) {
$data = json_decode($response, true);
if ($data['valid']) {
echo "✓ Certificado VÁLIDO\n";
echo "Estudiante: " . $data['certificate']['student_name'] . "\n";
echo "Programa: " . $data['certificate']['program'] . "\n";
echo "Institución: " . $data['certificate']['institution'] . "\n";
} else {
echo "✗ Certificado NO ENCONTRADO\n";
}
} else {
echo "Error HTTP: " . $httpCode . "\n";
}
Verifica varios certificados en una sola petición para procesos de admisión masivos.
$apiKey = 'tu_api_key_aqui';
$codigos = ['MF-92FXSP', 'AT-45KL23', 'CD-89WX56'];
$ch = curl_init('https://api.certuap.com/v1/verify/batch');
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . $apiKey,
'Content-Type: application/json'
],
CURLOPT_POSTFIELDS => json_encode(['codes' => $codigos])
]);
$response = json_decode(curl_exec($ch), true);
curl_close($ch);
// Procesar resultados
echo "Total: " . $response['summary']['total'] . "\n";
echo "Válidos: " . $response['summary']['valid'] . "\n";
echo "Inválidos: " . $response['summary']['invalid'] . "\n\n";
foreach ($response['results'] as $result) {
echo $result['code'] . ": ";
echo $result['valid'] ? "✓ VÁLIDO" : "✗ INVÁLIDO";
echo "\n";
}
Servicio reutilizable para Laravel con manejo de excepciones y caché.
namespace App\Services;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Cache;
class CertUAPService
{
private $apiKey;
private $baseUrl = 'https://api.certuap.com/v1';
public function __construct()
{
$this->apiKey = config('services.certuap.api_key');
}
public function verify(string $code)
{
// Caché por 1 hora
return Cache::remember("cert_{$code}", 3600, function() use ($code) {
$response = Http::withHeaders([
'Authorization' => 'Bearer ' . $this->apiKey,
])->post("{$this->baseUrl}/verify", [
'code' => $code
]);
if ($response->successful()) {
return $response->json();
}
throw new \Exception('Error al verificar certificado');
});
}
}
// Uso en un Controller:
public function verificar(Request $request, CertUAPService $certService)
{
$resultado = $certService->verify($request->code);
return view('certificado.resultado', compact('resultado'));
}
Ejemplo usando la librería requests de Python para verificar certificados.
pip install requests
import requests
import json
# Configuración
API_KEY = 'tu_api_key_aqui'
BASE_URL = 'https://api.certuap.com/v1'
def verificar_certificado(codigo):
"""Verifica un certificado académico"""
headers = {
'Authorization': f'Bearer {API_KEY}',
'Content-Type': 'application/json'
}
payload = {'code': codigo}
try:
response = requests.post(
f'{BASE_URL}/verify',
headers=headers,
json=payload,
timeout=10
)
response.raise_for_status()
data = response.json()
if data['valid']:
cert = data['certificate']
print(f"✓ Certificado VÁLIDO")
print(f"Estudiante: {cert['student_name']}")
print(f"Programa: {cert['program']}")
print(f"Institución: {cert['institution']}")
return True
else:
print("✗ Certificado NO ENCONTRADO")
return False
except requests.exceptions.RequestException as e:
print(f"Error: {e}")
return False
# Uso
if __name__ == "__main__":
verificar_certificado('MF-92FXSP')
import requests
from typing import Dict, List, Optional
class CertUAPClient:
"""Cliente oficial de CertUAP API"""
def __init__(self, api_key: str):
self.api_key = api_key
self.base_url = 'https://api.certuap.com/v1'
self.session = requests.Session()
self.session.headers.update({
'Authorization': f'Bearer {api_key}',
'Content-Type': 'application/json'
})
def verify(self, code: str) -> Optional[Dict]:
"""Verifica un certificado individual"""
response = self.session.post(
f'{self.base_url}/verify',
json={'code': code}
)
response.raise_for_status()
return response.json()
def verify_batch(self, codes: List[str]) -> Dict:
"""Verifica múltiples certificados"""
response = self.session.post(
f'{self.base_url}/verify/batch',
json={'codes': codes}
)
response.raise_for_status()
return response.json()
def is_valid(self, code: str) -> bool:
"""Retorna True si el certificado es válido"""
try:
result = self.verify(code)
return result.get('valid', False)
except:
return False
# Uso:
client = CertUAPClient('tu_api_key')
if client.is_valid('MF-92FXSP'):
cert = client.verify('MF-92FXSP')
print(cert['certificate']['student_name'])
Ejemplo para aplicaciones web usando Fetch API nativa del navegador.
const API_KEY = 'USAR_PROXY_BACKEND'; // ⚠️ No usar directamente
const BASE_URL = 'https://api.certuap.com/v1';
async function verificarCertificado(codigo) {
try {
const response = await fetch(`${BASE_URL}/verify`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ code: codigo })
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
if (data.valid) {
console.log('✓ Certificado VÁLIDO');
console.log('Estudiante:', data.certificate.student_name);
console.log('Programa:', data.certificate.program);
return data.certificate;
} else {
console.log('✗ Certificado NO ENCONTRADO');
return null;
}
} catch (error) {
console.error('Error:', error);
throw error;
}
}
// Uso en formulario
document.getElementById('verificarBtn').addEventListener('click', async () => {
const codigo = document.getElementById('codigoInput').value;
const resultado = await verificarCertificado(codigo);
if (resultado) {
// Mostrar resultado al usuario
document.getElementById('resultado').innerHTML = `
<div class="alert alert-success">
<h4>✓ Certificado Válido</h4>
<p>${resultado.student_name}</p>
<p>${resultado.program}</p>
</div>
`;
}
});
Crear un proxy backend seguro con Node.js y Express para proteger tu API Key.
npm install express axios dotenv
const express = require('express');
const axios = require('axios');
require('dotenv').config();
const app = express();
app.use(express.json());
const CERTUAP_API_KEY = process.env.CERTUAP_API_KEY;
const CERTUAP_BASE_URL = 'https://api.certuap.com/v1';
// Endpoint para verificar certificado
app.post('/api/verificar', async (req, res) => {
try {
const { code } = req.body;
if (!code) {
return res.status(400).json({
error: 'Código de certificado requerido'
});
}
const response = await axios.post(
`${CERTUAP_BASE_URL}/verify`,
{ code },
{
headers: {
'Authorization': `Bearer ${CERTUAP_API_KEY}`,
'Content-Type': 'application/json'
}
}
);
res.json(response.data);
} catch (error) {
console.error('Error:', error.message);
res.status(500).json({
error: 'Error al verificar certificado'
});
}
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Servidor corriendo en puerto ${PORT}`);
});
CERTUAP_API_KEY=tu_api_key_aqui PORT=3000
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
public class CertUAPClient
{
private readonly HttpClient _httpClient;
private readonly string _apiKey;
private readonly string _baseUrl = "https://api.certuap.com/v1";
public CertUAPClient(string apiKey)
{
_apiKey = apiKey;
_httpClient = new HttpClient();
_httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", _apiKey);
}
public async Task<VerificationResult> VerifyAsync(string code)
{
var payload = new { code };
var content = new StringContent(
JsonConvert.SerializeObject(payload),
Encoding.UTF8,
"application/json"
);
var response = await _httpClient.PostAsync(
$"{_baseUrl}/verify",
content
);
response.EnsureSuccessStatusCode();
var json = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<VerificationResult>(json);
}
}
// Uso:
var client = new CertUAPClient("tu_api_key");
var result = await client.VerifyAsync("MF-92FXSP");
if (result.Valid)
{
Console.WriteLine($"Estudiante: {result.Certificate.StudentName}");
}
implementation 'com.squareup.okhttp3:okhttp:4.11.0'
import okhttp3.*;
import org.json.JSONObject;
import java.io.IOException;
public class CertUAPClient {
private final OkHttpClient client;
private final String apiKey;
private final String baseUrl = "https://api.certuap.com/v1";
public CertUAPClient(String apiKey) {
this.apiKey = apiKey;
this.client = new OkHttpClient();
}
public JSONObject verify(String code) throws IOException {
JSONObject json = new JSONObject();
json.put("code", code);
RequestBody body = RequestBody.create(
json.toString(),
MediaType.parse("application/json")
);
Request request = new Request.Builder()
.url(baseUrl + "/verify")
.header("Authorization", "Bearer " + apiKey)
.post(body)
.build();
try (Response response = client.newCall(request).execute()) {
String responseBody = response.body().string();
return new JSONObject(responseBody);
}
}
// Uso:
public static void main(String[] args) {
CertUAPClient client = new CertUAPClient("tu_api_key");
JSONObject result = client.verify("MF-92FXSP");
if (result.getBoolean("valid")) {
System.out.println("✓ Certificado válido");
}
}
}