# 部门信息变化

当应用订阅该事件后，如果部门信息发生变化，则会触发该事件。部门信息发生变化的范围包括：

- 企业管理员在管理后台修改部门信息。
- 企业开发者调用
[修改部门部分信息](https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/reference/contact-v3/department/patch)、[更新部门所有信息](https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/reference/contact-v3/department/update)、[更新部门ID](https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/reference/contact-v3/department/update_department_id) API 修改部门信息。

## 前提条件

- 你需要在应用中配置事件订阅，这样才可以在事件触发时接收到事件数据。了解事件订阅可参见[事件订阅概述](https://open.feishu.cn/document/ukTMukTMukTM/uUTNz4SN1MjL1UzM)。
- 该事件有部分字段权限要求，你可以参考相应的参数描述获取参数所需的权限。只有当应用开通了相应的字段权限后，才可以成功接收到完整的事件体数据。申请权限的具体操作，参见[申请 API 权限](https://open.feishu.cn/document/ukTMukTMukTM/uQjN3QjL0YzN04CN2cDN)。

## 事件

基本 | &nbsp;
---|---
事件类型 | contact.department.updated_v3
支持的应用类型 | Custom App、Store App
权限要求<br>**订阅该事件所需的权限，开启其中任意一项权限即可订阅**<br>开启任一权限即可 | 获取通讯录基本信息(contact:contact.base:readonly)<br>以应用身份读取通讯录(contact:contact:readonly_as_app)<br>以应用身份访问通讯录(contact:contact:access_as_app)
字段权限要求 | **注意事项**：该接口返回体中存在下列敏感字段，仅当开启对应的权限后才会返回；如果无需获取这些字段，则不建议申请<br>获取通讯录部门组织架构信息(contact:department.organize:readonly)<br>以应用身份读取通讯录(contact:contact:readonly_as_app)<br>获取部门基础信息(contact:department.base:readonly)<br>查询部门 HRBP 信息(contact:department.hrbp:readonly)<br>以应用身份访问通讯录(contact:contact:access_as_app)<br>读取通讯录(contact:contact:readonly)
推送方式 | [Webhook](https://open.feishu.cn/document/ukTMukTMukTM/uUTNz4SN1MjL1UzM)

### 事件体

名称 | 类型 | 描述
---|---|---
schema | string | 事件模式
header | event_header | 事件头
event_id | string | 事件 ID
event_type | string | 事件类型
create_time | string | 事件创建时间戳（单位：毫秒）
token | string | 事件 Token
app_id | string | 应用 ID
tenant_key | string | 租户 Key
event | \- | \-
object | department_event | 部门更新后的信息。
name | string | 部门名称。<br>**数据校验规则**：<br>- 最小长度：`1` 字符<br>**字段权限要求（满足任一）**：<br>以应用身份读取通讯录(contact:contact:readonly_as_app)<br>获取部门基础信息(contact:department.base:readonly)<br>以应用身份访问通讯录(contact:contact:access_as_app)<br>读取通讯录(contact:contact:readonly)
parent_department_id | string | 父部门的部门 open_department_id。了解部门 ID 可参见[部门资源介绍](https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/reference/contact-v3/department/field-overview)。<br>**字段权限要求（满足任一）**：<br>以应用身份读取通讯录(contact:contact:readonly_as_app)<br>获取通讯录部门组织架构信息(contact:department.organize:readonly)<br>以应用身份访问通讯录(contact:contact:access_as_app)<br>读取通讯录(contact:contact:readonly)
department_id | string | 当前部门的 department_id。了解部门 ID 可参见[部门资源介绍](https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/reference/contact-v3/department/field-overview)。<br>**字段权限要求（满足任一）**：<br>以应用身份读取通讯录(contact:contact:readonly_as_app)<br>获取部门基础信息(contact:department.base:readonly)<br>以应用身份访问通讯录(contact:contact:access_as_app)<br>读取通讯录(contact:contact:readonly)
open_department_id | string | 当前部门的 open_department_id。了解部门 ID 可参见[部门资源介绍](https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/reference/contact-v3/department/field-overview)。
leader_user_id | string | 部门主管的用户 open_id 。了解用户 ID 可参见[用户相关的 ID 概念](https://open.feishu.cn/document/home/user-identity-introduction/introduction)。<br>**字段权限要求（满足任一）**：<br>以应用身份读取通讯录(contact:contact:readonly_as_app)<br>获取部门基础信息(contact:department.base:readonly)<br>以应用身份访问通讯录(contact:contact:access_as_app)<br>读取通讯录(contact:contact:readonly)
chat_id | string | 部门群 ID。你可以调用[获取群信息](https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/reference/im-v1/chat/get)接口，通过群 ID 获取群详细信息。<br>**字段权限要求（满足任一）**：<br>以应用身份读取通讯录(contact:contact:readonly_as_app)<br>获取通讯录部门组织架构信息(contact:department.organize:readonly)<br>以应用身份访问通讯录(contact:contact:access_as_app)<br>读取通讯录(contact:contact:readonly)
order | int | 当前部门在同级部门的排序。取值越小排序越靠前。<br>**字段权限要求（满足任一）**：<br>以应用身份读取通讯录(contact:contact:readonly_as_app)<br>获取通讯录部门组织架构信息(contact:department.organize:readonly)<br>以应用身份访问通讯录(contact:contact:access_as_app)<br>读取通讯录(contact:contact:readonly)
status | department_status | 部门状态。<br>**字段权限要求（满足任一）**：<br>以应用身份读取通讯录(contact:contact:readonly_as_app)<br>获取部门基础信息(contact:department.base:readonly)<br>以应用身份访问通讯录(contact:contact:access_as_app)<br>读取通讯录(contact:contact:readonly)
is_deleted | boolean | 是否被删除。<br>**可能值：**<br>- true：是<br>- false：否
leaders | departmentLeader\[\] | 部门负责人信息。
leaderType | int | 负责人类型。<br>**可选值有**：<br>- 1：主负责人。<br>- 2：副负责人。
leaderID | string | 负责人的用户 open_id。了解用户 ID 可参见[用户相关的 ID 概念](https://open.feishu.cn/document/home/user-identity-introduction/introduction)。<br>**字段权限要求（满足任一）**：<br>以应用身份读取通讯录(contact:contact:readonly_as_app)<br>获取通讯录部门组织架构信息(contact:department.organize:readonly)<br>以应用身份访问通讯录(contact:contact:access_as_app)<br>读取通讯录(contact:contact:readonly)
department_hrbps | user_id\[\] | 部门 HRBP 的用户 ID 列表。了解用户 ID 可参见[用户相关的 ID 概念](https://open.feishu.cn/document/home/user-identity-introduction/introduction)。<br>**字段权限要求**：<br>查询部门 HRBP 信息(contact:department.hrbp:readonly)
union_id | string | 用户的 union_id。
user_id | string | 用户的 user_id。
open_id | string | 用户的 open_id。
old_object | department_event | 部门更新前的信息。
name | string | 部门名称。<br>**数据校验规则**：<br>- 最小长度：`1` 字符<br>**字段权限要求（满足任一）**：<br>以应用身份读取通讯录(contact:contact:readonly_as_app)<br>获取部门基础信息(contact:department.base:readonly)<br>以应用身份访问通讯录(contact:contact:access_as_app)<br>读取通讯录(contact:contact:readonly)
parent_department_id | string | 父部门的部门 open_department_id。了解部门 ID 可参见[部门资源介绍](https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/reference/contact-v3/department/field-overview)。<br>**字段权限要求（满足任一）**：<br>以应用身份读取通讯录(contact:contact:readonly_as_app)<br>获取通讯录部门组织架构信息(contact:department.organize:readonly)<br>以应用身份访问通讯录(contact:contact:access_as_app)<br>读取通讯录(contact:contact:readonly)
department_id | string | 当前部门的 department_id。了解部门 ID 可参见[部门资源介绍](https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/reference/contact-v3/department/field-overview)。<br>**字段权限要求（满足任一）**：<br>以应用身份读取通讯录(contact:contact:readonly_as_app)<br>获取部门基础信息(contact:department.base:readonly)<br>以应用身份访问通讯录(contact:contact:access_as_app)<br>读取通讯录(contact:contact:readonly)
open_department_id | string | 当前部门的 open_department_id。了解部门 ID 可参见[部门资源介绍](https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/reference/contact-v3/department/field-overview)。
leader_user_id | string | 部门主管的用户 open_id 。了解用户 ID 可参见[用户相关的 ID 概念](https://open.feishu.cn/document/home/user-identity-introduction/introduction)。<br>**字段权限要求（满足任一）**：<br>以应用身份读取通讯录(contact:contact:readonly_as_app)<br>获取部门基础信息(contact:department.base:readonly)<br>以应用身份访问通讯录(contact:contact:access_as_app)<br>读取通讯录(contact:contact:readonly)
chat_id | string | 部门群 ID。你可以调用[获取群信息](https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/reference/im-v1/chat/get)接口，通过群 ID 获取群详细信息。<br>**字段权限要求（满足任一）**：<br>以应用身份读取通讯录(contact:contact:readonly_as_app)<br>获取通讯录部门组织架构信息(contact:department.organize:readonly)<br>以应用身份访问通讯录(contact:contact:access_as_app)<br>读取通讯录(contact:contact:readonly)
order | int | 当前部门在同级部门的排序。取值越小排序越靠前。<br>**字段权限要求（满足任一）**：<br>以应用身份读取通讯录(contact:contact:readonly_as_app)<br>获取通讯录部门组织架构信息(contact:department.organize:readonly)<br>以应用身份访问通讯录(contact:contact:access_as_app)<br>读取通讯录(contact:contact:readonly)
status | department_status | 部门状态。<br>**字段权限要求（满足任一）**：<br>以应用身份读取通讯录(contact:contact:readonly_as_app)<br>获取部门基础信息(contact:department.base:readonly)<br>以应用身份访问通讯录(contact:contact:access_as_app)<br>读取通讯录(contact:contact:readonly)
is_deleted | boolean | 是否被删除。<br>**可能值：**<br>- true：是<br>- false：否
leaders | departmentLeader\[\] | 部门负责人信息。
leaderType | int | 负责人类型。<br>**可选值有**：<br>- 1：主负责人。<br>- 2：副负责人。
leaderID | string | 负责人的用户 open_id。了解用户 ID 可参见[用户相关的 ID 概念](https://open.feishu.cn/document/home/user-identity-introduction/introduction)。<br>**字段权限要求（满足任一）**：<br>以应用身份读取通讯录(contact:contact:readonly_as_app)<br>获取通讯录部门组织架构信息(contact:department.organize:readonly)<br>以应用身份访问通讯录(contact:contact:access_as_app)<br>读取通讯录(contact:contact:readonly)
department_hrbps | user_id\[\] | 部门 HRBP 的用户 ID 列表。了解用户 ID 可参见[用户相关的 ID 概念](https://open.feishu.cn/document/home/user-identity-introduction/introduction)。<br>**字段权限要求**：<br>查询部门 HRBP 信息(contact:department.hrbp:readonly)
union_id | string | 用户的 union_id。
user_id | string | 用户的 user_id。
open_id | string | 用户的 open_id。

### 事件体示例
```json
{
    "schema": "2.0",
    "header": {
        "event_id": "5e3702a84e847582be8db7fb73283c02",
        "event_type": "contact.department.updated_v3",
        "create_time": "1608725989000",
        "token": "rvaYgkND1GOiu5MM0E1rncYC6PLtF7JV",
        "app_id": "cli_9f5343c580712544",
        "tenant_key": "2ca1d211f64f6438"
    },
    "event": {
        "object": {
            "name": "测试部门",
            "parent_department_id": "od_j10jjkfsd89782",
            "department_id": "jyd7sa8yf2",
            "open_department_id": "od_j10j52hjksd9g0isdfg43",
            "leader_user_id": "ou_3j1kh45jk18fgh23hf",
            "chat_id": "oc_uiy325uy23bnv48gdf",
            "order": 100,
            "status": {
                "is_deleted": false
            },
            "leaders": [
                {
                    "leaderType": 1,
                    "leaderID": "ou_7dab8a3d3cdcc9da365777c7ad535d62"
                }
            ],
            "department_hrbps": [
                {
                    "union_id": "on_cad4860e7af114fb4ff6c5d496d1dd76",
                    "user_id": "98bc325a",
                    "open_id": "ou_c99c5f35d542efc7ee492afe11af19ef"
                }
            ]
        },
        "old_object": {
            "name": "测试部门",
            "parent_department_id": "od_j10jjkfsd89782",
            "department_id": "jyd7sa8yf2",
            "open_department_id": "od_j10j52hjksd9g0isdfg43",
            "leader_user_id": "ou_3j1kh45jk18fgh23hf",
            "chat_id": "oc_uiy325uy23bnv48gdf",
            "order": 100,
            "status": {
                "is_deleted": false
            },
            "leaders": [
                {
                    "leaderType": 1,
                    "leaderID": "ou_7dab8a3d3cdcc9da365777c7ad535d62"
                }
            ],
            "department_hrbps": [
                {
                    "union_id": "on_cad4860e7af114fb4ff6c5d496d1dd76",
                    "user_id": "98bc325a",
                    "open_id": "ou_c99c5f35d542efc7ee492afe11af19ef"
                }
            ]
        }
    }
}
```

### 事件订阅示例代码

事件订阅流程可参考：[事件订阅概述](https://open.feishu.cn/document/ukTMukTMukTM/uUTNz4SN1MjL1UzM)，新手入门可参考：[教程](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/contact/v3"
	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("", "").
		OnP2DepartmentUpdatedV3(func(ctx context.Context, event *larkcontact.P2DepartmentUpdatedV3) error {
			fmt.Printf("[ OnP2DepartmentUpdatedV3 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_contact_department_updated_v3(data: lark.contact.v3.P2ContactDepartmentUpdatedV3) -> None:
    print(f'[ do_p2_contact_department_updated_v3 access ], data: {lark.JSON.marshal(data, indent=4)}')

# 注册事件 Register event
event_handler = lark.EventDispatcherHandler.builder("", "") \
    .register_p2_contact_department_updated_v3(do_p2_contact_department_updated_v3) \
    .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.contact.ContactService;
import com.lark.oapi.service.contact.v3.model.P2DepartmentUpdatedV3;
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("", "")
            .onP2DepartmentUpdatedV3(new ContactService.P2DepartmentUpdatedV3Handler() {
                @Override
                public void handle(P2DepartmentUpdatedV3 event) throws Exception {
                    System.out.printf("[ onP2DepartmentUpdatedV3 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({
        'contact.department.updated_v3': 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/contact/v3"
)

// 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("", "").
		OnP2DepartmentUpdatedV3(func(ctx context.Context, event *larkcontact.P2DepartmentUpdatedV3) error {
			fmt.Printf("[ OnP2DepartmentUpdatedV3 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_contact_department_updated_v3(data: lark.contact.v3.P2ContactDepartmentUpdatedV3) -> None:
    print(f'[ do_p2_contact_department_updated_v3 access ], data: {lark.JSON.marshal(data, indent=4)}')

# 注册事件 Register event
event_handler = lark.EventDispatcherHandler.builder("", "") \
    .register_p2_contact_department_updated_v3(do_p2_contact_department_updated_v3) \
    .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.contact.ContactService;
import com.lark.oapi.service.contact.v3.model.P2DepartmentUpdatedV3;
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")
            .onP2DepartmentUpdatedV3(new ContactService.P2DepartmentUpdatedV3Handler() {
                @Override
                public void handle(P2DepartmentUpdatedV3 event) throws Exception {
                    System.out.printf("[ onP2DepartmentUpdatedV3 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({
    'contact.department.updated_v3': 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);

