NAV img-alt
logo Red de Protección Social
cURL JavaScript PHP

Introduction

Bienvenido a la API de Red de Protección Social . Puedes usar nuestra API para acceder a los distintos endpoints de CMP, donde podrás obtener los beneficios de la clase media.

El API esta organizado alrededor de REST. Todas las respuestas de la API retornan objetos JSON, incluyendo los errores.

Utilizamos características incluidas en el protocolo HTTP, como autenticación y verbos, los cuales son soportados por la gran mayoría de los clientes HTTP. Soportamos CORS, lo cual permite interactuar de manera segura con nuestra API desde una aplicación web desde el lado del cliente.

Tenemos bindings para cURL, JavaScript. Puedes ver ejemplos de código en el área a la derecha, y puedes cambiar el lenguaje de los ejemplos arriba a la derecha.

Tambien disponemos de una collection para Postman que puedes descargar desde aquí

Authentication

CMP utiliza Oauth2 sobre HTTPS para la autenticación. Para tener acceso a nuestra API, debes tener tu client_id y client_secret. Los request no autenticados retornarán una respuesta HTTP 401. Las llamadas sobre HTTP simple también fallarán.

Authorize API access to a client.

Example request:

          curl -X POST "/api/v1/oauth/token" \
            -d "grant_type"="client_credentials" \
            -d "scope"="*" \
            -d "client_id"="{client_id}" \
            -d "client_secret"="{client_secret}" \
          
        
          
            const url = new URL("/api/v1/oauth/token");

            let headers = {
              "Accept": "application/json",
              "Content-Type": "application/json",
            }
            let body = JSON.stringify({
              "grant_type": "client_credentials",
              "scope": "*",
              "client_id": "{client_id}",
              "client_secret": "{client_secret}"
            })
            fetch(url, {
              method: "POST",
              headers: headers,
              body: body
            })
            .then(response => response.json())
            .then(json => console.log(json));
          
        
          
            <?php
              require 'guzzle.phar';

              $client = new GuzzleHttp\Client();

              $body = $client->request('POST', '/api/v1/oauth/token', [
                'json' => [
                  'grant_type'    => 'client_credentials',
                  'scope'         => '*',
                  'client_id'     => '{client_id}',
                  'client_secret' => '{client_secret}'
                ],
                'headers' => [
                  "Content-Type"  => "application/json",
                ]
              ])->getBody();

              $response = json_decode($body);

              var_dump($response);
            ?>
          
        

Example response (200):

          
            {
              "token_type": "Bearer",
              "expires_in": 31535999,
              "access_token": "eyJ0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A1gO8jb0QLE"
          }
          
        

HTTP Request

POST /api/v1/oauth/token

Body Parameters

Parameter Type Status Description
grant_type string required 'client_credentials'.
scope string required '*'
client_id string required Client id entregado por CMP.
client_secret string required Client Secret entregado por CMP.

Authorize Widget access to a client.

Example request:

          
            curl -X POST "/v1/auth/widget" \
            -d "apiKey"="{apiKey}" \
            -d "secretKey"="{secretKey}" \
            -d "cu_token"="{cu_token}" \
            -d "rut"="{rut}" \
          
        
          
            const url = new URL("/v1/auth/widget");

            let headers = {
              "Content-Type": "application/json",
            }

            let body = JSON.stringify({
              "apiKey": "{apiKey}",
              "secretKey": "{secretKey}",
              "cu_token": "{cu_token}",
              "rut": "{rut}"
            })

            fetch(url, {
              method: "POST",
              headers: headers,
              body: body
            })
            .then(response => response.json())
            .then(json => console.log(json));
          
        
          
            <?php
              require 'guzzle.phar';

              $client = new GuzzleHttp\Client();

              $body = $client->request('POST', '/v1/auth/widget', [
                'json' => [
                  'apiKey'     => '{apiKey}',
                  'secretKey'  => '{secretKey}',
                  'cu_token'   => '{cu_token}',
                  'rut'        => '{rut}'
                ],
                'headers' => [
                  "Content-Type"  => "application/json",
                ]
              ])->getBody();

              $response = json_decode($body);

              var_dump($response);
            ?>
          
        

Example response (200):

          
            {
              "code": 200,
              "success": true,
              "data": {
                "CmpWidget": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjgwMDAvYXV0aC9sb2dpbiIsImlhdCI6MTU3OTE4MjExNSwiZXhwIjo3NTc5MTgyMDU1LCJuYmYiOjE1NzkxODIxMTUsImp0aSI6ImJIRVFBVadssAsds23d3c3oiLCJzdWIiOjgxLCJwcnYiOiIyM2JkNWM4OTQ5ZjYwMGFkYjM5ZTcwMWM0MDA4NzJkYjdhNTk3NmY3In0.Yc3B-vIYTZl_YD4BYhOxc0z4hSTnUoPklHrljiowz7M"
              }
            }
          
        

HTTP Request

POST /v1/auth/widget

Body Parameters

Parameter Type Status Description
apiKey string required Api key entregado por CMP.
secretKey string required Secret key entregado por CMP.
cu_token string required Token de Claveunica.
rut string required Rut de la persona a consultar por el widget (Formato rut_numero-dv) Ejemplo: 55555555-5.

API

Beneficios Potenciales

Permite obtener los beneficios potenciales a los que puede optar una persona de clase media


Requires API authentication

Example request:

          curl -X POST -G "/api/v1/beneficios-potenciales" \
            -H "Authorization: Bearer {token}" \
            -d "rut"="{rut}" \
            -d "categoria"="{salud || educacion || dependencia || trabajo || violencia || transferencias || covid || todas}"
            -d "cu_token"="{hash}" 
          
        
          
            const url = new URL("/api/v1/beneficios-potenciales");
            let headers = {
                "Authorization": "Bearer {token}",
                "Accept": "application/json",
                "Content-Type": "application/json",
            }

            let body = JSON.stringify({
                "rut": "{rut}",
                "categoria": "{salud || educacion || dependencia || trabajo || violencia || transferencias || covid || todas}",
                "cu_token": "{hash}"
            })

            fetch(url, {
                method: "POST",
                headers: headers,
                body: body
            })
                .then(response => response.json())
                .then(json => console.log(json));
          
        
          
            <?php
            require 'guzzle.phar';

            $client = new GuzzleHttp\Client();

            $body = $client->request('POST', '/api/v1/beneficios-potenciales', [
              'json' => [
                'rut'           => '{rut}',
                'categoria'     => '{salud || educacion || dependencia || trabajo || violencia || transferencias || covid || todas}'
                'cu_token'     => '{hash}' 
              ],
              'headers' => [
                "Content-Type"  => "application/json",
                "Authorization" => "Bearer {token}",
              ]
            ])->getBody();

            $response = json_decode($body);

            var_dump($response);
            ?>
          
        

Example response (200):

          
            {
              "code": 200,
              "success": true,
              "data": {
                "beneficios": [
                    {
                        "url": "",
                        "title": "",
                        "description": "",
                        "idChileAtiende": []
                    },
                    {
                        "url": "",
                        "title": "",
                        "description": "",
                        "idChileAtiende": []
                    }
                ]
              }
          }
          
        

Example response (500):

          
            {
              "code": 500,
              "success": false,
              "data": {
                  "message": "Ingrese Categoría"
              }
            }
          
        

HTTP Request

POST /api/v1/beneficios-potenciales

Body Parameters

Parameter Type Status Description
rut string required Rut de la persona Consultada (Sin puntos ni guion) Ejemplo: 555555555.
categoria string required Categoria consultada. Puedes enviar "todas" para consultar por todas las categorias.
cu_token string required Token de Claveunica.

Widgets

¿Cómo funciona?

Descarga este documento aquí

Configuración básica

Para instanciar los widgets se requiere incluir lo siguiente en el head del documento HTML:

<head>
<link rel="stylesheet" href="{'url_css'}"/>
<script src="{'url_script'}"></script>
</head>

Widget Config

Config Parameters

Parameter Type Status Description
url_css string required Url del CSS para el widget entregado por CMP.
url_script string required Url del script para el widget entregado por CMP.

Perfil Ciudadano

Permite visualizar el perfil de una persona de clase media


Requires Widget authentication

Example widget call:

          
            Not Supported, only JavaScript.
          
        
          
            function callWidget(selector, apiKey, cmpToken) {
              var CmpPerfil = window.CmpWidget.widgets.cmpPerfilCiudadano()
              CmpPerfil.render({
                selector,
                apiKey,
                cmpToken,
              })
              window.location.hash = '#/'
            }

            callWidget(
              {selector},
              {apiKey},
              {cmpToken},
            )

            // HTML
           <div id='{selector}'/>
          
        
          
            Not Supported, only JavaScript.
          
        

Widget Instance

Widget Parameters

Parameter Type Status Description
selector string required Selector HTML donde se instanciará el widget. Ejemplo: #cmp-widget-div
apiKey string required Api key entregado por CMP.
cmpToken string required Token obtenido en la autenticación para el widget.

Hogar Ciudadano

Permite visualizar los datos del hogar de una persona de clase media


Requires Widget authentication

Example widget call:

          
            Not Supported, only JavaScript.
          
        
          
            function callWidget(selector, apiKey, cmpWidget) {
              var CmpHogar = window.CmpWidget.widgets.cmpHogarCiudadano()
              CmpHogar.render({
                selector,
                apiKey,
                cmpWidget,
              })
              window.location.hash = '#/'
            }

            callWidget(
              {selector},
              {apiKey},
              {cmpWidget},
            )
            
            // HTML
           <div id='{selector}'/>
          
        
          
            Not Supported, only JavaScript.
          
        

Widget Instance

Widget Parameters

Parameter Type Status Description
selector string required Selector HTML donde se instanciará el widget. Ejemplo: #cmp-widget-div
apiKey string required Api key entregado por CMP.
cmpWidget string required Token obtenido en la autenticación para el widget.

Manejo de Errores

Disponemos de una función para capturar y manejar los posibles errores de los widgets


Requires Widget authentication

Example handler error widget call:

          
            Not Supported, only JavaScript.
          
        
          
            function handleWidgetError(error) {
              // Handle Widget Error here
              console.log(error)
            }
            function callWidget(selector, apiKey, cmpToken) {
              var args = {
                selector,
                apiKey,
                cmpToken,
              }
              if (window.CmpWidget) {
                var CMPwidget = window.CmpWidget.widgets.cmpPerfilCiudadano()
                /*ó 
                var CMPwidget = window.CmpWidget.widgets.cmpHogarCiudadano();
                */
                CMPwidget.render(args)
                CMPwidget.onError(args, (error) => handleWidgetError(error))
                window.location.hash = "#/"
              }
            }

            callWidget(
              {selector},
              {apiKey},
              {cmpWidget},
            )
            
            // HTML
           <div id='{selector}'/>
          
        
          
            Not Supported, only JavaScript.
          
        

Widget Instance With Handling Errors

Widget Parameters

Parameter Type Status Description
selector string required Selector HTML donde se instanciará el widget. Ejemplo: #cmp-widget-div
apiKey string required Api key entregado por CMP.
cmpWidget string required Token obtenido en la autenticación para el widget.

Formato del objeto error

{
message: {{"Error description"}},
code: {{"HTTP error code"}}
}

Errors

Codigo Error Descripción
400

Bad Request

Hay un problema con tu request
401

Unauthorized

Tu api key es incorrecta
403

Forbidden

No tienes permiso para ver esta página
404

Not Found

El recurso especificado no fue encontrado
405

Method Not Allowed

Trataste de ingresar a un recurso con un método inválido
406

Not Acceptable

Solicistaste un formato que no es json
410

Gone

El recurso solicitado fue removido de nuestros servidores
429

Too Many Requests

Estas solicitando muchos recursos! Detente!
500

Internal Server Error

Tuvimos un problema con nuestro servidor. Inténtalo nuevamente mas tarde
503

Service Unavailable

Estamos offline por mantenimiento. Inténtalo nuevamente mas tarde