Autenticação
O que é Autenticação? 🧐
Para que uma API possa ser acionada é preciso realizar uma autenticação para garantir que os dados transacionados estejam protegidos. Existem três métodos principais para fazer isso: autenticação básica HTTP, Chaves da API e OAuth.No RD Station utilizamos os métodos de autenticação OAuth e Chaves de API.
OAuth
Pré-requisitos
Antes de iniciar o processo de autenticação, cheque se você já possui:
✔️ Uma conta do RD Station, se ainda não tiver, crie uma aqui.
✔️ Uma url de callback para receber a primeira credencial da conta.
✔️ Credenciais client_id
e client_secret
.
O que é uma URL de callback?
Num fluxo de autenticação, o seu aplicativo solicita autorização para ter acesso a uma conta dentro da estrutura do RD Station. Por isso, precisamos de um "endereço de entrega" do seu aplicativo para podermos devolver essa autorização, caso nosso cliente autorize a conexão da sua aplicação com o RD Station. Esse endereço de entrega é a url de callback. Uma url de callback se parece com isso:https://nomedoapp.org/auth/callback
O que são Credenciais?
No fluxo OAuth de autenticação, seu aplicativo possui duas credenciais, que chamamos declient_id
e client_secret
. Essas credenciais são utilizadas para gerar tokens de acesso. Uma vez que um token de acesso tenha sido gerado, ele será utilizado nas trocas de mensagens via API. Se você ainda não possui essas credenciais, poderá gerá-las acessando a RD Station App Store. É lá que você irá fazer o processo de submissão do seu aplicativo, e após isso suas credenciais serão criadas. Caso você já possua as credenciais, poderá iniciar o processo de autenticação agora mesmo. Passo a passo resumido do fluxo de autenticação 😉
Passo 1: Criar um aplicativo na RD Station App Store Passo 2: Substituir os campos da URL abaixo pelos dados que você vai obter do aplicativo.https://api.rd.services/auth/dialog?client_id={client_id}&redirect_uri={redirect_uri}
Passo 3: Clicar no link e realizar login no RD Station Marketing. Passo 4: Após login e confirmação de acesso, enviaremos o code
para a URL de callback. Passo 5: Solicitar o access_token
e refresh_token
a partir do code
gerado, enviando uma requisição para a nossa API. Passo 6: Pronto! Agora você já pode enviar dados para a nossa API com o access_token
recebido.
Iniciando o processo de autorização
Seu aplicativo deverá direcionar o usuário para a URL de autorização indicada abaixo, substituindo os parâmetros client_id
e redirect_uri
por suas credenciais. Veja o exemplo:
Request Parameters:
client_id | Type: String | Client |
---|---|---|
redirect_uri | Type: String | Redirect Uri |
Você verá a caixa de confirmação da autorização, conforme mostrado a imagem abaixo. Clique no botão para confirmar o acesso.
Feita a confirmação, o RD Station retornará com uma URL de callback, que contém o parâmetro code
. Veja no exemplo:
https://yourapp.org/auth/callback?code={code}
Esse processo só precisa ser feito uma vez \O/ Porém pode-se repetir caso você queira gerar um novo code ou o usuário seja desconectado.
Obs: Se a url de callback possuir query string, o valor deve ser passado em formato encoded. Exemplo:
Url de callback: http://example.com/callback/index?name=auth Url de callback encoded: http%3A%2F%2Fexample.com%2Fcallback%2Findex%3Fname%3Dauthe
Obtendo tokens de acesso
Uma vez recebido o parâmetro code
, só falta obter o token de acesso. Para isso basta fazer uma requisição para obter o access_token
:
Obtendo tokens de acesso
Request Parameters
client_id | Type: String | Client |
---|---|---|
client_secret | Type: String | Client Secret |
code | Type: String | Code |
Body Example:
{
"client_id": "CLIENT_ID",
"client_secret": "CLIENT_SECRET",
"code": "CODE"
}
Response Body Parameters
access_token | Type: String | Access Token |
---|---|---|
refresh_token | Type: String | Refresh Token |
expires_in | Type: Integer | Expires In |
Response Example:
{
"access_token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6Ik5UZ3hRamM1UWpKR1FUUkNPRVE0UVRZeFJFVTBNRFEzUkRGRE9UVXdPVE5FTXpVM09UUXpRUSJ9.eyJpc3MiOiJodHRwczovL3Jkc3RhdGlvbi5hdXRoMC5jb20vIiwic3ViIjoidklUYjF2N0NoVmhmUVE2QUFTbDNLVUpYRUJTSVNCR2hAY2xpZW50cyIsImF1ZCI6Imh0dHBzOi8vYXBwLnJkc3RhdGlvbi5jb20uYnIvYXBpL3YyLyIsImV4cCI6MTUwNDI5NDQzMSwiaWF0IjoxNTA0MjA4MDMxLCJzY29wZSI6IiJ9.k7OSdhOlTgRBZmEhg_uXXaCofEq4iwDdBi6yuD8SxMF06nCA834KjIqWkmX-W-u84q8SEzGyhb_KT0zZlMvyGotoGPMry_vABXEIorC25zKCUE9BtMJpHJ_suFwQMqZQ8rK6JSnbkOKwLuuDq8_YnrutBURJiBSdSI9325MLw0DZdnw0IgXnNVCHRLdOMl4k_Ovk5Ke3yzESJvMxgJJ3UnojL0ckRExVPwxnbLCyJp1W_PsEe-FOcEl0kDEX-8JQ8MGATiB2vZOu5TJi4sbYCLzg3GInegGh9zvZQR1W4K3isDtOmlNRSYU9A5ez3dQ8HTZdCj9gT_aGWWskxWi6Cw",
"expires_in":86400,
"refresh_token":"9YORmXHgOI32k-Y22tZWm-rsf--oFPr8JDCQIQhBEUY"
}
cURL example request:
curl --request POST --url 'https://api.rd.services/auth/token' --header 'Content-Type: application/json' --data '{ "code": "dbexxxxxxxxxxxxxxx865", "client_id": "5c6xxxxxxxxxxxxxxxacc", "client_secret":"LzHxxxxxxxxxxxxxxx98V"}'
Com o access_token
gerado, este deverá ser enviado no cabeçalho de cada requisição para a API Pública.
Authorization: Bearer access_token |
Required on client request |
---|---|
Content-Type: application/json |
Required on client request |
Atualizando um token expirado
Todo access_token
é temporário, e tem como prazo de validade o valor definido pelo atributo expires_in
em segundos, que é de 86400 segundos (24 Horas). Um novo access_token
é gerado utilizando o refresh_token
, exemplo:
Atualizando um token expirado
Request Parameters
client_id | Type: String | Client |
---|---|---|
client_secret | Type: String | Client Secret |
refresh_token | Type: String | Refresh Token |
Body Example:
{
"client_id": "CLIENT_ID",
"client_secret": "CLIENT_SECRET",
"refresh_token": "REFRESH_TOKEN"
}
Response Body Parameters
access_token | Type: String | Access Token |
---|---|---|
refresh_token | Type: String | Refresh Token |
expires_in | Type: Integer | Expires In |
Response Examples:
Success - 200 Ok
{
"access_token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6Ik5UZ3hRamM1UWpKR1FUUkNPRVE0UVRZeFJFVTBNRFEzUkRGRE9UVXdPVE5FTXpVM09UUXpRUSJ9.eyJpc3MiOiJodHRwczovL3Jkc3RhdGlvbi5hdXRoMC5jb20vIiwic3ViIjoidklUYjF2N0NoVmhmUVE2QUFTbDNLVUpYRUJTSVNCR2hAY2xpZW50cyIsImF1ZCI6Imh0dHBzOi8vYXBwLnJkc3RhdGlvbi5jb20uYnIvYXBpL3YyLyIsImV4cCI6MTUwNDI5NDQzMSwiaWF0IjoxNTA0MjA4MDMxLCJzY29wZSI6IiJ9.k7OSdhOlTgRBZmEhg_uXXaCofEq4iwDdBi6yuD8SxMF06nCA834KjIqWkmX-W-u84q8SEzGyhb_KT0zZlMvyGotoGPMry_vABXEIorC25zKCUE9BtMJpHJ_suFwQMqZQ8rK6JSnbkOKwLuuDq8_YnrutBURJiBSdSI9325MLw0DZdnw0IgXnNVCHRLdOMl4k_Ovk5Ke3yzESJvMxgJJ3UnojL0ckRExVPwxnbLCyJp1W_PsEe-FOcEl0kDEX-8JQ8MGATiB2vZOu5TJi4sbYCLzg3GInegGh9zvZQR1W4K3isDtOmlNRSYU9A5ez3dQ8HTZdCj9gT_aGWWskxWi6Cw",
"expires_in":86400,
"refresh_token":"9YORmXHgOI32k-Y22tZWm-rsf--oFPr8JDCQIQhBEUY"
}
Invalid Grant - 401 Unauthorized
Response Headers
WWW-Authenticate: Bearer realm="https://api.rd.services/", error="invalid_grant", error_description="The provided refresh token is invalid or was revoked."
Response Body
{
"error_type": "INVALID_REFRESH_TOKEN",
"error_message": "The provided refresh token is invalid or was revoked."
}
cURL example request:
curl --request POST --url 'https://api.rd.services/auth/token' --header 'Content-Type: application/json' --data '{ "refresh_token": "OlzExxxxxxxxxxxxxxx-379", "client_id": "5c6xxxxxxxxxxxxxxxacc", "client_secret":"LzHxxxxxxxxxxxxxxx98V"}'
Revogando o acesso de um token
O acesso dos clientes com autenticação do tipo OAuth pode ser revogado sempre que necessário. Isso pode ser feito utilizando o access_token
ou o refresh_token
, por exemplo:
Revogando o acesso de um token
Request Headers
Content-Type | x-www-form-urlencoded |
---|---|
Authorization | Bearer ACCESS_TOKEN |
Request Parameters
Field | Type | Required | Description |
---|---|---|---|
token | String | true | Refresh Token Or Access Token |
token_type_hint | String | false | Available Options |
Body Example:
{
"token": "REFRESH_TOKEN",
"token_type_hint": "refresh_token"
}
cURL example request:
curl --request POST --url 'https://api.rd.services/auth/revoke' --header 'Content-Type: application/x-www-form-urlencoded' --header 'Authorization: Bearer ACCESS_TOKEN' --data '{ "token": "OlzExxxxxxxxxxxxxxx-379", "token_type_hint": "refresh_token"}'
API Key
A utilização da API Key possibilita o envio de eventos de conversão para o RD Station Marketing.
API key é um token que deve ser enviado via Query String pelo parâmetro api_key.
Para saber mais sobre API Keys acesse a Central de Ajuda.
Default Headers
Request Headers
Content-Type | application/json |
---|
Query String
Authentication Token
Query Param | api_key |
---|
Default Responses
Success | Code: 200
{
"event_uuid": "5408c5a3-4711-4f2e-8d0b-13407a3e30f3"
}
Bad Request | Invalid Event Type | Code: 400
{
"errors": [
{
"error_type": "INVALID_OPTION",
"error_message": "Must be one of the valid options.",
"validation_rules": {
"valid_options": [
"CONVERSION"
]
},
"path": "$.event_type"
}
]
}
Evento de Conversão
O RD Station Marketing considera o valor do atributo conversion_identifier
como identificador da conversão.
Esse evento é registrado sempre que ocorre uma conversão.
Request body parameters
Field | Type | Required | Description |
---|---|---|---|
event_type | String | true | The event type that diferentiates the event. For the conversion event it should be sent as "CONVERSION". |
event_family | String | true | The family of the event for processing purposes. It currently accepts only "CDP" as valid option. |
conversion_identifier | String | true | The name of the conversion event. |
name | String | false | Name of the contact. |
String | true | Email of the contact. | |
job_title | String | false | Job title of the contact. |
state | String | false | State of the contact. |
city | String | false | City of the contact. |
country | String | false | Country of the contact. |
personal_phone | String | false | Phone of the contact. |
mobile_phone | String | false | Mobile phone of the contact. |
String | false | Twitter handler of the contact. | |
String | false | Facebook of the contact. | |
String | false | Linkedin of the contact. | |
website | String | false | Website of the contact. |
company_name | String | false | Company name of the contact. |
company_site | String | false | Company website of the contact. |
company_address | String | false | Company address of the contact. |
client_tracking_id | String | false | Value of a '_rdtrk' cookie. (e.g: 43b00843-09af-4fae-bf9d-a0697640b808) |
traffic_source | String | false | This can either be the value of a '__trf.src' cookie (base 64 encoded or not) or an UTM source param. If passing a cookie the following fields MUST be empty: traffic_medium, traffic_campaign and traffic_value. |
traffic_medium | String | false | UTM medium param. |
traffic_campaign | String | false | UTM campaign param. |
traffic_value | String | false | UTM value param (term). |
tags | Array of Strings | false | Tags that can be added to the contact. |
available_for_mailing | Boolean | false | Enable/disable receive emails. |
legal_bases | Array of Objects | false | Legal Bases of the contact. |
cf_custom_field_name* | String | false | Custom field created in RDSM and its value related to the contact. |
* All custom fields available in RD Station Marketing account are valid on this payload. They should be sent using the prefix "cf_" plus the field name, for instance: cf_age.
Request body example
{
"event_type": "CONVERSION",
"event_family":"CDP",
"payload": {
"conversion_identifier": "Name of the conversion event",
"name": "name of the contact",
"email": "email@email.com",
"job_title": "job title value",
"state": "state of the contact",
"city": "city of the contact",
"country": "country of the contact",
"personal_phone": "phone of the contact",
"mobile_phone": "mobile_phone of the contact",
"twitter": "twitter handler of the contact",
"facebook": "facebook name of the contact",
"linkedin": "linkedin user name of the contact",
"website": "website of the contact",
"company_name": "company name",
"company_site": "company website",
"company_address": "company address",
"client_tracking_id": "lead tracking client_id",
"traffic_source": "Google",
"traffic_medium": "cpc",
"traffic_campaign": "easter-50-off",
"traffic_value": "easter eggs",
"tags": ["mql", "2019"],
"available_for_mailing": true,
"legal_bases": [
{
"category": "communications",
"type": "consent",
"status": "granted"
}
],
"cf_my_custom_field": "custom field value"
}
}