# [Event] Update custom organization

This event is triggered when a custom organization is updated in Feishu personnel.{Usage Examples}(url=/api/tools/api_explore/api_explore_config?project=corehr&version=v2&resource=custom_org&event=updated)

**Notice**：[[Query custom organization information in batches
]](https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/corehr-v2/custom_org/query) There is a certain delay(within 2 seconds) in the interface data query, and it is not recommended to query the above interface immediately after receiving the event.
**Notice**：- **This API will only push change events for the currently active object**.
- The future version data will be pushed in the early morning of the effective date. For example: today is January 1st, if you modify the object name and fill in January 10th to take effect, the object change event will be sent in the early morning of January 10th.
- The following field changes will receive events: names(custom organization name)、active(active)、description(description)、code(code)、manager_ids(custom organization manager)、parent_id(superior custom organization)、effective_time(effective time) and custom fields
- The following field changes will not receive events: wk_id(ID)、wk_tid(timeline record ID)、wk_updated_by(record updater)、wk_updated_at(record update time)、expiration_time、wk_created_at(record created time)、wk_created_by(record creator)、wk_deleted_at(record deleted time)、wk_status(timeline status)

## Event

Facts | &nbsp;
---|---
Event type | corehr.custom_org.updated_v2
Supported app types | Custom App、Store App
Required scopes<br>**To subscribe to this event, enable any of the listed scopes.**<br>Enable any scope from the list | 获取自定义组织信息(corehr:custom_org:read)<br>读写自定义组织信息(corehr:custom_org:write)
Push Mode | [Webhook](https://open.feishu.cn/document/ukTMukTMukTM/uUTNz4SN1MjL1UzM)

### Event body

Parameter | Type | Description
---|---|---
schema | string | Event schema
header | event_header | Event header
event_id | string | Event ID
event_type | string | Event type
create_time | string | Event creation timestamp(in ms)
token | string | Event token
app_id | string | App ID
tenant_key | string | Tenant key
event | \- | \-
org_id | string | Custom Organization Id<br>- Detailed information can be obtained through the[[Query custom organization information in batches<br>]](https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/corehr-v2/custom_org/query)
field_changes | string\[\] | Fields that have changed<br>**Data validation rules**:<br>- Length range: `0` ～ `200`
object_api_name | string | Organization type code, which can be viewed under the corresponding custom organization directory in "Feishu Personnel-Settings-Organization Settings"

### Event body example
```json
{
    "schema": "2.0",
    "header": {
        "event_id": "5e3702a84e847582be8db7fb73283c02",
        "event_type": "corehr.custom_org.updated_v2",
        "create_time": "1608725989000",
        "token": "rvaYgkND1GOiu5MM0E1rncYC6PLtF7JV",
        "app_id": "cli_9f5343c580712544",
        "tenant_key": "2ca1d211f64f6438"
    },
    "event": {
        "org_id": "7436668377630295596",
        "field_changes": [
            "name"
        ],
        "object_api_name": "custom_org_01"
    }
}
```

### Sample code for event subscriptions

For event subscription process, refer to:[Event Subscription overview](https://open.feishu.cn/document/ukTMukTMukTM/uUTNz4SN1MjL1UzM)，Guide for beginners:[Tutorial](https://open.feishu.cn/document/uAjLw4CM/uMzNwEjLzcDMx4yM3ATM/develop-an-echo-bot/introduction)

**

package main

import (
	"context"
	"fmt"

larkcore "github.com/larksuite/oapi-sdk-go/v3/core"
	larkevent "github.com/larksuite/oapi-sdk-go/v3/event"
	"github.com/larksuite/oapi-sdk-go/v3/event/dispatcher"
	"github.com/larksuite/oapi-sdk-go/v3/service/corehr/v2"
	larkws "github.com/larksuite/oapi-sdk-go/v3/ws"
)

// SDK 使用说明 SDK user guide：https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/server-side-sdk/golang-sdk-guide/preparations
func main() {
	// 注册事件 Register event
	eventHandler := dispatcher.NewEventDispatcher("", "").
		OnP2CustomOrgUpdatedV2(func(ctx context.Context, event *larkcorehr.P2CustomOrgUpdatedV2) error {
			fmt.Printf("[ OnP2CustomOrgUpdatedV2 access ], data: %s\n", larkcore.Prettify(event))
			return nil
		})

// 构建 client Build client
	cli := larkws.NewClient("YOUR_APP_ID", "YOUR_APP_SECRET",
		larkws.WithEventHandler(eventHandler),
		larkws.WithLogLevel(larkcore.LogLevelDebug),
	)

// 建立长连接 Establish persistent connection
	err := cli.Start(context.Background())

if err != nil {
		panic(err)
	}
}

# SDK 使用说明 SDK user guide：https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/server-side-sdk/python--sdk/preparations-before-development
import lark_oapi as lark

def do_p2_corehr_custom_org_updated_v2(data: lark.corehr.v2.P2CorehrCustomOrgUpdatedV2) -> None:
    print(f'[ do_p2_corehr_custom_org_updated_v2 access ], data: {lark.JSON.marshal(data, indent=4)}')

# 注册事件 Register event
event_handler = lark.EventDispatcherHandler.builder("", "") \
    .register_p2_corehr_custom_org_updated_v2(do_p2_corehr_custom_org_updated_v2) \
    .build()

def main():
    # 构建 client Build client
    cli = lark.ws.Client("APP_ID", "APP_SECRET",
                        event_handler=event_handler, log_level=lark.LogLevel.DEBUG)
    # 建立长连接 Establish persistent connection
    cli.start()

if __name__ == "__main__":
    main()

package com.example.sample;

import com.lark.oapi.core.utils.Jsons;
import com.lark.oapi.service.corehr.CorehrService;
import com.lark.oapi.service.corehr.v2.model.P2CustomOrgUpdatedV2;
import com.lark.oapi.event.EventDispatcher;
import com.lark.oapi.ws.Client;

// SDK 使用说明 SDK user guide：https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/server-side-sdk/java-sdk-guide/preparations
public class Sample {
    // 注册事件 Register event
    private static final EventDispatcher EVENT_HANDLER = EventDispatcher.newBuilder("", "")
            .onP2CustomOrgUpdatedV2(new CorehrService.P2CustomOrgUpdatedV2Handler() {
                @Override
                public void handle(P2CustomOrgUpdatedV2 event) throws Exception {
                    System.out.printf("[ onP2CustomOrgUpdatedV2 access ], data: %s\n", Jsons.DEFAULT.toJson(event.getEvent()));
                }
            })
            .build();

public static void main(String[] args) {
        // 构建 client Build client
        Client client = new Client.Builder("APP_ID", "APP_SECRET")
                .eventHandler(EVENT_HANDLER)
                .build();
        // 建立长连接 Establish persistent connection
        client.start();
    }
}

// SDK 使用说明 SDK user guide：https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/server-side-sdk/nodejs-sdk/preparation-before-development
import * as Lark from '@larksuiteoapi/node-sdk';
const baseConfig = {
    appId: 'APP_ID',
    appSecret: 'APP_SECRET'
}
// 构建 client Build client
const wsClient = new Lark.WSClient(baseConfig);
// 建立长连接 Establish persistent connection
wsClient.start({
    // 注册事件 Register event
    eventDispatcher: new Lark.EventDispatcher({}).register({
        'corehr.custom_org.updated_v2': async (data) => {
            console.log(data);
        }
    })
});

package main

import (
	"context"
	"fmt"
	"net/http"

larkcore "github.com/larksuite/oapi-sdk-go/v3/core"
	"github.com/larksuite/oapi-sdk-go/v3/core/httpserverext"
	larkevent "github.com/larksuite/oapi-sdk-go/v3/event"
	"github.com/larksuite/oapi-sdk-go/v3/event/dispatcher"
	"github.com/larksuite/oapi-sdk-go/v3/service/corehr/v2"
)

// SDK 使用说明 SDK user guide：https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/server-side-sdk/golang-sdk-guide/preparations
func main() {
	// 注册事件 Register event
	eventHandler := dispatcher.NewEventDispatcher("", "").
		OnP2CustomOrgUpdatedV2(func(ctx context.Context, event *larkcorehr.P2CustomOrgUpdatedV2) error {
			fmt.Printf("[ OnP2CustomOrgUpdatedV2 access ], data: %s\n", larkcore.Prettify(event))
			return nil
		})

// 创建路由处理器 Create route handler
	http.HandleFunc("/webhook/event", httpserverext.NewEventHandlerFunc(handler, larkevent.WithLogLevel(larkcore.LogLevelDebug)))

err := http.ListenAndServe(":7777", nil)

if err != nil {
		panic(err)
	}
}

# SDK 使用说明 SDK user guide：https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/server-side-sdk/python--sdk/preparations-before-development
from flask import Flask
from lark_oapi.adapter.flask import *
import lark_oapi as lark

app = Flask(__name__)

def do_p2_corehr_custom_org_updated_v2(data: lark.corehr.v2.P2CorehrCustomOrgUpdatedV2) -> None:
    print(f'[ do_p2_corehr_custom_org_updated_v2 access ], data: {lark.JSON.marshal(data, indent=4)}')

# 注册事件 Register event
event_handler = lark.EventDispatcherHandler.builder("", "") \
    .register_p2_corehr_custom_org_updated_v2(do_p2_corehr_custom_org_updated_v2) \
    .build()

# 创建路由处理器 Create route handler
@app.route("/webhook/event", methods=["POST"])
def event():
    resp = event_handler.do(parse_req())
    return parse_resp(resp)

if __name__ == "__main__":
    app.run(port=7777)

package com.lark.oapi.sample.event;

import com.lark.oapi.core.utils.Jsons;
import com.lark.oapi.service.corehr.CorehrService;
import com.lark.oapi.service.corehr.v2.model.P2CustomOrgUpdatedV2;
import com.lark.oapi.sdk.servlet.ext.ServletAdapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// SDK 使用说明 SDK user guide：https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/server-side-sdk/java-sdk-guide/preparations
@RestController
public class EventController {

// 注册事件 Register event
    private static final EventDispatcher EVENT_HANDLER = EventDispatcher.newBuilder("verificationToken", "encryptKey")
            .onP2CustomOrgUpdatedV2(new CorehrService.P2CustomOrgUpdatedV2Handler() {
                @Override
                public void handle(P2CustomOrgUpdatedV2 event) throws Exception {
                    System.out.printf("[ onP2CustomOrgUpdatedV2 access ], data: %s\n", Jsons.DEFAULT.toJson(event.getEvent()));
                }
            })
            .build();

// 注入 ServletAdapter 实例 Inject ServletAdapter instance
    @Autowired
    private ServletAdapter servletAdapter;

// 创建路由处理器 Create route handler
    @RequestMapping("/webhook/event")
    public void event(HttpServletRequest request, HttpServletResponse response)
            throws Throwable {
        // 回调扩展包提供的事件回调处理器 Callback handler provided by the extension package
        servletAdapter.handleEvent(request, response, EVENT_DISPATCHER);
    }
}

// SDK 使用说明 SDK user guide：https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/server-side-sdk/nodejs-sdk/preparation-before-development
import http from 'http';
import * as lark from '@larksuiteoapi/node-sdk';

// 注册事件 Register event
const eventDispatcher = new lark.EventDispatcher({
    encryptKey: '',
    verificationToken: '',
}).register({
    'corehr.custom_org.updated_v2': async (data) => {
        console.log(data);
        return 'success';
    },
});

const server = http.createServer();
// 创建路由处理器 Create route handler
server.on('request', lark.adaptDefault('/webhook/event', eventDispatcher));
server.listen(3000);

