웹훅¶
경고
개발자, 솔루션 설계자 또는 기타 기술 담당자와 웹훅 사용 시기 및 구현 프로세스 전반에 대한 내용을 상의하는 것을 강력히 권장합니다. 웹훅이 제대로 구성되지 않으면 Odoo 데이터베이스가 중단될 수 있으며 복구까지 장시간이 소요될 수 있습니다.
Webhooks, which can be created in Odoo Studio, allow you to automate an action in your Odoo database when a specific event occurs in another, external system.
In practice, this works as follows: when the event occurs in the external system, a data file (the
“payload”) is sent to the Odoo webhook’s URL via a POST
API request, and a predefined action is
performed in your Odoo database.
사전에 지정된 간격으로 실행되는 예약 작업 혹은 명시적으로 호출되는 수동 API 요청과는 달리, 웹훅은 실시간의 이벤트 기반 통신 및 자동화를 지원합니다. 예를 들어, 웹훅 설정을 통해 외부 POS 시스템에서 판매 주문이 확인될 경우 Odoo 재고 데이터가 자동으로 업데이트되게 하는 것도 가능합니다.
Setting up a webhook in Odoo requires no coding when connecting two Odoo databases, but testing a webhook requires an external tool. Custom target records or actions may require programming skills.
참고
This article covers creating a webhook that receives data from an external source. However, it is also possible to create an automated action that sends data to an external webhook when a change occurs in your Odoo database.
Create a webhook in Odoo¶
중요
Before implementing a webhook in a live database, configure and test it using a duplicate database to ensure the webhook performs as intended.
팁
Activating developer mode before creating up a webhook gives greater flexibility in selecting the model the automation rule targets. It also allows you to find the technical name of the model and fields, which may be needed to configure the payload.
개발자 모드가 활성화된 상태에서 모델의 기술명을 확인하려면 모델 이름 위에 마우스를 가져간 다음 (내부 링크) 를 클릭하세요. 기술명은 모델 필드에서 확인할 수 있습니다. 예를 들어, 판매주문서 웹훅은 판매주문서 모델을 사용하지만, 페이로드에는 기술명으로 sale.order
가 사용됩니다.
To create a webhook in Studio, proceed as follows:
Open Studio and click Webhooks, then New.
Give the webhook a clear, meaningful name that identifies its purpose.
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.
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.
경고
The URL is confidential and should be treated with care. Sharing it online or without caution can provide unintended access to the Odoo database. If the URL is updated after the initial implementation, make sure to update it in the external system.
If desired, enable Log Calls to track the history of API requests made to the webhook’s URL, e.g., for troubleshooting purposes.
웹훅을 전송하는 시스템이 Odoo가 아닌 경우, 대상 레코드 코드를 조정하여 웹훅 URL로 API 호출 시 페이로드에 포함된 JSON 레코드를 검색하도록 해야 합니다. 웹훅을 전송하는 시스템이 Odoo 데이터베이스인 경우, 페이로드에 `id`와 `model`이 나타나는지 확인하세요.
If the webhook is used to create records in the Odoo database, use
model.browse(i)
ormodel.search(i)
instead of the default Target Record format.Click Add an action in the Actions To Do tab to define the actions to be executed.
Before implementing the webhook in the external system, test it to ensure it works as intended.
팁
Webhooks can also be created via the Automations menu in Studio by selecting the trigger On webhook.
To access the history of API requests if Log Calls has been enabled, click the Logs smart button at the top of the Automation rules form.
If the purpose of the webhook is anything other than to update an existing record, e.g., to create a new record, the Execute Code action must be chosen.
Test a webhook¶
Testing a webhook requires a test payload and an external tool or system, like
Postman, to send the payload via a POST
API request. This section
presents the steps to test a webhook in Postman.
팁
See the webhook use cases section for step-by-step explanations of how to test webhooks using test payloads.
To get specific help with testing a webhook with Postman, contact their support team.
In Postman, create a new HTTP request and set its method to POST.
Copy the webhook’s URL from your Odoo database using the (link) icon and paste it into the URL field in Postman.
Click the Body tab and select raw.
Set the file type to JSON, then copy the code from the test payload and paste it into the code editor.
Click Send.
In the Response viewer at the bottom of the screen in Postman, details, including a HTTP response code, indicate whether or not the webhook is functioning correctly.
A
200 OK
orstatus: 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.다른 응답이 반환되는 경우에는, 해당 응답 번호를 통해 문제를 파악해 낼 수 있습니다. 예를 들어,
500 내부 서버 오류
메시지가 나타난다면 Odoo에서 호출이 제대로 해석되지 못했다는 것을 의미합니다. 이러한 경우 JSON 파일의 필드가 웹훅의 환경설정 메뉴 및 테스트 호출을 전송하는 시스템에 올바르게 매핑되었는지 확인하세요.
팁
Turning on call logging in the webhook’s configuration in Odoo provides error logs if the webhook is not functioning as intended.
Implement a webhook in an external system¶
When the webhook has been successfully created in Odoo and tested, implement it in the system that
sends data to the Odoo database, making sure the POST
API requests are sent to the webhook’s URL.
웹훅 사용 사례¶
Below are two examples of how to use webhooks in Odoo. A test payload is provided for each example, and can be found in the section on testing the webhook. Postman is used to send the test payload.
판매주문서 통화 업데이트하기¶
This webhook updates a sales order in the Sales app to USD
when the external system sends a
POST
API request to the webhook’s URL that includes that sales order number (which is identified
by the payload’s id
record).
This could be useful for subsidiaries outside the United States with a mother company located inside the United States or during mergers when consolidating data into one Odoo database.
Create the webhook¶
To create this webhook, proceed as follows:
Open the Sales app, then open Studio and click Webhooks. The Sales Order model is selected by default.
Click New. The Trigger is set to On webhook by default.
Set the Target Record to
model.env[payload.get('model')].browse(int(payload.get('id')))
, where:payload.get('model')
retrieves the value associated with themodel
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 theid
key in the payload, i.e., the number of the target sales order in your Odoo database with theS
and leading zeros removed.int
converts the retrieved id to an integer (i.e., a whole number) because the methodbrowse()
can only be used with an integer.
Click Add an action.
In the Type section, click Update Record.
In the Action details section, select Update, choose the field Currency, and select USD.
Click Save & Close.
웹훅 테스트¶
To test this webhook, proceed as follows:
With Postman open, create a new HTTP request and set its method to POST.
Copy the URL of the Odoo webhook using the (link) icon and paste it into the URL field in Postman.
Click the Body tab and select raw.
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" }
Odoo 데이터베이스에서 웹훅을 테스트할 판매주문서를 선택합니다. 붙여넣은 코드를
판매주문서 번호
를 해당 판매주문서 번호로 바꾸되, 숫자 앞에 있는S
나 0은 삭제합니다. 예를 들어, 판매주문서 번호가S00007`인 경우 Postman에는 `7
로 입력해야 합니다.Click Send.
Consult the Response viewer in Postman to determine whether or not the webhook is functioning properly. If a message other than
200 OK
orstatus: ok
is returned, the number associated with the message helps to identify the problem.
새 계약서 만들기¶
This webhook uses custom code to create a new contact in an Odoo database when the external system
sends a POST
API request to the webhook’s URL that includes the contact’s information. This could
be helpful for automatically creating new vendors or customers.
Create the webhook¶
To create this webhook, proceed as follows:
Open the Contacts app, then open Studio and click Webhooks. The Contact model is selected by default.
Click New. The Trigger is set to On webhook by default.
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.Click Add an action.
In the Type section, click Execute Code.
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'")
Click Save & Close.
웹훅 테스트¶
To test this webhook, proceed as follows:
In Postman, create a new HTTP request and set its method to POST.
Copy the URL of the Odoo webhook using the (link) icon and paste it into the URL field in Postman.
Click the Body tab and select raw.
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" }
In the pasted code, replace the
CONTACT NAME
,CONTACTEMAIL@EMAIL.COM
, andCONTACT PHONE NUMBER
with a new contact’s information.Click Send.
Consult the Response viewer in Postman to determine whether or not the webhook is functioning properly. If a message other than
200 OK
orstatus: ok
is returned, the number associated with the message helps to identify the problem.