Pular para o conteúdo
Documentação do usuário

Webhooks

Webhooks, que podem ser criados no Odoo Studio, permitem que você automatize uma ação no seu banco de dados Odoo quando um evento específico ocorre em outro sistema externo.

Na prática, funciona da seguinte forma: quando o evento ocorre no sistema externo, um arquivo de dados (o "payload") é enviado para a URL do webhook do Odoo via uma solicitação de API POST, e uma ação predefinida é executada no seu banco de dados Odoo.

Ao contrário de ações agendadas, que são executadas em intervalos predefinidos, ou solicitações de API manuais, que precisam ser explicitamente invocadas, webhooks permitem comunicação e automação em tempo real orientadas por eventos. Por exemplo, você pode configurar um webhook para ter seus dados de inventário do Odoo atualizados automaticamente quando um pedido de venda é confirmado em um sistema externo de ponto de venda.

Configurar um webhook no Odoo não requer codificação ao conectar dois bancos de dados Odoo, mas testar um webhook <studio/webhooks/test-webhook> requer uma ferramenta externa. Registros ou ações de destino personalizados <studio/webhooks/webhook-example> podem exigir habilidades de programação.

Criar um webhook no Odoo

Para encontrar o nome técnico de um modelo, com o modo desenvolvedor ativado, passe o mouse sobre o nome do modelo e clique em fa-arrow-right (Link interno). O nome técnico pode ser encontrado no campo Modelo. Por exemplo, um webhook de pedido de venda usa o modelo Pedido de Venda, mas o nome técnico sale.order é usado no payload.

Para criar um webhook no Studio, proceda da seguinte forma:

  1. Open Studio <studio/access> and click Webhooks, then New.

  2. Give the webhook a clear, meaningful name that identifies its purpose.

  3. If needed, and provided developer mode is activated, select the appropriate Model from the dropdown. If developer mode is not activated, the automation rule targets the current model by default.

  4. The webhook's URL is automatically generated, but can be changed if needed by clicking Rotate Secret. This is the URL that should be used when implementing the webhook in the external system that will send updates to the database.

    A URL é confidencial e deve ser tratada com cuidado. Compartilhá-la online ou sem cautela pode fornecer acesso não intencional ao banco de dados Odoo. Se a URL for atualizada após a implementação inicial, certifique-se de atualizá-la no sistema externo.

  5. If desired, enable Log Calls to track the history of API requests made to the webhook's URL, e.g., for troubleshooting purposes.

  6. If the system sending the webhook is not Odoo, adjust the Target Record code to look for the JSON record included in the payload when the API request is made to the webhook's URL. If the system sending the webhook is an Odoo database, ensure that the id and model appear in the payload.

Se o webhook for usado para criar registros no banco de dados Odoo, use model.browse(i) ou model.search(i) em vez do formato padrão Target Record.

  1. Click Add an action in the Actions To Do tab to define the actions <studio/automated-actions/action> to be executed.

  2. Before implementing the webhook in the external system, test <studio/webhooks/test-webhook> it to ensure it works as intended.

Testar um webhook

Testar um webhook requer um payload de teste e uma ferramenta externa ou sistema, como Postman, para enviar o payload através de uma requisição de API POST. Esta seção apresenta os passos para testar um webhook no Postman.

  1. In Postman, create a new HTTP request and set its method to POST.

  2. Copy the webhook's URL from your Odoo database using the fa-link (link) icon and paste it into the URL field in Postman.

  3. Click the Body tab and select raw.

  4. Set the file type to JSON, then copy the code from the test payload and paste it into the code editor.

  5. Click Send.

No visualizador Response na parte inferior da tela no Postman, detalhes, incluindo um código de resposta HTTP, indicam se o webhook está funcionando corretamente ou não.

  • A 200 OK or status: ok message indicates that the webhook is functioning properly on Odoo's side. From here, implementation can begin with the other system to automatically send the API requests to the Odoo webhook's URL.

  • If any other response is returned, the number associated with it helps to identify the problem. For example, a 500 Internal Server Error message means that Odoo could not interpret the call properly. In this case, ensure the fields found in the JSON file are properly mapped in the webhook's configuration and in the system sending the test call.

Implementar um webhook em um sistema externo

Quando o webhook tiver sido criado com sucesso no Odoo e testado, implemente-o no sistema que envia dados ao banco de dados Odoo, certificando-se de que as requisições de API POST sejam enviadas à URL do webhook.

Casos de uso de webhooks

Abaixo estão dois exemplos de como usar webhooks no Odoo. Um payload de teste é fornecido para cada exemplo e pode ser encontrado na seção sobre testes do webhook. Postman é usado para enviar o payload de teste.

Atualizar a moeda de um pedido de vendas

Este webhook atualiza um pedido de venda no app Sales para USD quando o sistema externo envia uma requisição de API POST à URL do webhook que inclui o número desse pedido de venda (que é identificado pelo registro id do payload).

Isso pode ser útil para filiais fora dos Estados Unidos com uma empresa-mãe localizada dentro dos Estados Unidos ou durante fusões ao consolidar dados em um banco de dados Odoo.

Criar o webhook

Para criar este webhook, proceda da seguinte forma:

  1. Open the Sales app, then open Studio <studio/access> and click Webhooks. The Sales Order model is selected by default.

  2. Click New. The Trigger is set to On webhook by default.

  3. Set the Target Record to model.env[payload.get('_model')].browse(int(payload.get('_id'))), where:

    • payload.get('_model') retrieves the value associated with the model key in the payload, i.e., sale.order, which is the technical name of the Sales Order model.

    • payload.get('_id') retrieves the value associated with the id key in the payload, i.e., the number of the target sales order in your Odoo database with the S and leading zeros removed.

    • int converts the retrieved id to an integer (i.e., a whole number) because the method browse() can only be used with an integer.

  4. Click Add an action.

  5. In the Type section, click Update Record.

  6. In the Action details section, select Update, choose the field Currency, and select USD.

  7. Click Save & Close.

Testar o webhook

Para testar este webhook, proceda da seguinte forma:

  1. With Postman open, create a new HTTP request and set its method to POST.

  2. Copy the URL of the Odoo webhook using the fa-link (link) icon and paste it into the URL field in Postman.

  3. Click the Body tab and select raw.

  4. Set the file type to JSON, then copy this code, i.e., the payload, and paste it into the code editor:

    {
        "_model": "sale.order",
        "_id": "SALES ORDER NUMBER"
    }
  5. In your Odoo database, choose a sales order to test the webhook on. In the pasted code, replace SALES ORDER NUMBER with the sales order's number without the S or any zeros before the number. For example, a sales order with the number S00007 should be entered as 7 in Postman.

  6. Click Send.

  7. Consult the Response viewer <studio/webhooks/test-webhook-response> in Postman to determine whether or not the webhook is functioning properly. If a message other than 200 OK or status: ok is returned, the number associated with the message helps to identify the problem.

Criar um novo contato

Este webhook usa código personalizado para criar um novo contato em um banco de dados Odoo quando o sistema externo envia uma requisição POST da API para a URL do webhook que inclui as informações do contato. Isso pode ser útil para criar automaticamente novos fornecedores ou clientes.

Criar o webhook

Para criar este webhook, proceda da seguinte forma:

  1. Open the Contacts app, then open Studio <studio/access> and click Webhooks. The Contact model is selected by default.

  2. Click New. The Trigger is set to On webhook by default.

  3. Set the Target Record to model.browse([2]). This is essentially a placeholder as the code in the automated action tells the webhook what needs to be retrieved from the payload and in which model the record needs to be created.

  4. Click Add an action.

  5. In the Type section, click Execute Code.

  6. Copy this code and paste it into the code editor in the Code tab of the Action details section:

    # variables to retrieve and hold data from the payload
    contact_name = payload.get('name')
    contact_email = payload.get('email')
    contact_phone = payload.get('phone')
    
    # a Python function to turn the variables into a contact in Odoo
    if contact_name and contact_email:
        new_partner = env['res.partner'].create({
            'name': contact_name,
            'email': contact_email,
            'phone': contact_phone,
            'company_type':'person',
            'customer_rank': 1,
        })
    # an error message for missing required data in the payload
    else:
        raise ValueError("Missing required fields: 'name' and 'email'")
  7. Click Save & Close.

Testar o webhook

Para testar este webhook, proceda da seguinte forma:

  1. In Postman, create a new HTTP request and set its method to POST.

  2. Copy the URL of the Odoo webhook using the fa-link (link) icon and paste it into the URL field in Postman.

  3. Click the Body tab and select raw.

  4. Set the file type to JSON, then copy this code, i.e., the payload, and paste it into the code editor:

    {
        "name": "CONTACT NAME",
        "email": "CONTACTEMAIL@EMAIL.COM",
        "phone": "CONTACT PHONE NUMBER"
    }
  5. In the pasted code, replace the CONTACT NAME, CONTACTEMAIL@EMAIL.COM, and CONTACT PHONE NUMBER with a new contact's information.

  6. Click Send.

  7. Consult the Response viewer <studio/webhooks/test-webhook-response> in Postman to determine whether or not the webhook is functioning properly. If a message other than 200 OK or status: ok is returned, the number associated with the message helps to identify the problem.