$username = "uno";
$password = "dos";
$headers = array(
'Content-Type: application/json',
'Authorization: Basic '. base64_encode("$username:$password")
);
$parametros = '{
"nombre": "111",
"apellidos": "222",
"telefono": "333",
"email": "444",
"direccion": "555",
"ciudad": "666",
"departamento": "777"
}';
$url = "https://www.midominio.com/slim/public/api/clientes/agregar";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt( $ch, CURLOPT_POSTFIELDS, $parametros);
$result = curl_exec($ch);
curl_close($ch);
echo $result;
En midominio.com en clientes.php:
$app->post('/api/clientes/agregar', function(Request $request, Response $response){
$_SERVER["HTTP_AUTHORIZATION"] = str_replace("Basic ", "", $_SERVER["HTTP_AUTHORIZATION"]);
if ($_SERVER["HTTP_AUTHORIZATION"] == base64_encode("uno:dos")) {
$nombre = $request->getParam('nombre');
$apellidos = $request->getParam('apellidos');
$telefono = $request->getParam('telefono');
$email = $request->getParam('email');
$direccion = $request->getParam('direccion');
$ciudad = $request->getParam('ciudad');
$departamento = $request->getParam('departamento');
$consulta = "INSERT INTO clientes (nombre, apellidos, telefono, email, direccion, ciudad, departamento) VALUES
(:nombre, :apellidos, :telefono, :email, :direccion, :ciudad, :departamento)";
try{
// Instanciar la base de datos
$db = new db();
// Conexión
$db = $db->conectar();
$stmt = $db->prepare($consulta);
$stmt->bindParam(':nombre', $nombre);
$stmt->bindParam(':apellidos', $apellidos);
$stmt->bindParam(':telefono', $telefono);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':direccion', $direccion);
$stmt->bindParam(':ciudad', $ciudad);
$stmt->bindParam(':departamento', $departamento);
$stmt->execute();
echo '{"notice": {"text": "Cliente agregado"}';
} catch(PDOException $e){
echo '{"error": {"text": '.$e->getMessage().'}';
}
}
else {
echo "No tienes permiso<hr>";
exit;
}
});
Si quieres no es necesario codificar el user y el password sino simplemente mandar un token:
$token = "12345";
$headers = array(
'Content-Type: application/json',
'Authorization:tokenLSG='.$token
);
Y en clientes.php:
$_SERVER["HTTP_AUTHORIZATION"] = str_replace("tokenLSG=", "", $_SERVER["HTTP_AUTHORIZATION"]);
if ($_SERVER["HTTP_AUTHORIZATION"] == "12345") {
...
}
No hay comentarios:
Publicar un comentario