Web挂钩¶
警告
It is highly recommended to consult with a developer, solution architect, or another technical role when deciding to use webhooks and throughout the implementation process. If not properly configured, webhooks may disrupt the Odoo database and can take time to revert.
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.
Unlike scheduled actions, which run at predefined intervals, or manual API requests, which need to be explicitly invoked, webhooks enable real-time, event-driven communication and automation. For example, you can set up a webhook to have your Odoo inventory data updated automatically when a sales order is confirmed in an external point-of-sale system.
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.
To find a model’s technical name, with developer mode activated, hover over the model name and
then click (Internal link). The technical name can be found in
the Model field. For example, a sales order webhook uses the Sales
Order model, but the technical name sale.order
is used in the payload.
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.
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
andmodel
appear in the payload.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.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.
小技巧
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.
Webhook use cases¶
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.
Update a sales order’s currency¶
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.
Test the webhook¶
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" }
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 theS
or any zeros before the number. For example, a sales order with the numberS00007
should be entered as7
in Postman.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.
Test the webhook¶
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.