godingtalk

package module
v0.0.0-...-2fb6554 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 26, 2024 License: MIT Imports: 7 Imported by: 0

README

godingtalk

封装钉钉开放的接口

Install下载依赖

go get -u github.com/jellycheng/godingtalk
或者
GO111MODULE=on GOPROXY=https://goproxy.cn/,direct go get -u github.com/jellycheng/godingtalk

直接获取master分支代码:
    go get -u github.com/jellycheng/godingtalk@main
    

Documentation

https://pkg.go.dev/github.com/jellycheng/godingtalk

拼接钉钉登录地址

package main

import (
	"fmt"
	"github.com/jellycheng/godingtalk"
)

func main() {
	cfg := godingtalk.DingAgentConfig{
		AppKey:"your appkey",
		AppSecret:"your appsecret",
	}
	// 授权成功后跳转地址
	redirectUri := "http://www.xxx.com/callback/dingdingtalk"
	scope := "openid corpid"
	state := ""
	// 拼接钉钉登录地址
	urlStr := godingtalk.GetLoginUrl(redirectUri, cfg.AppKey,scope,state)
	fmt.Println(urlStr)

}


企业内部应用获取access_token

package main

import (
	"fmt"
	"github.com/jellycheng/godingtalk"
)

func main() {
	cfg := godingtalk.DingAgentConfig{
		AppKey:    "钉钉应用AppKey",
		AppSecret: "钉钉应用AppSecret",
	}
	at := godingtalk.GetAccessToken(cfg)
	fmt.Println(at.AccessToken)
}

发送工作通知消息示例

发送文本消息:
    curl -X POST \
      'https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2?access_token=a3a63fc592083b2fb74bcc5f195015dd' \
      -H 'content-type: application/json' \
      -d '{"msg":{"msgtype":"text","text":{"content":"文本消息"}},"agent_id":"1605203268","userid_list":"manager4056"}
    '
    代码示例如下:
    package main
    
    import (
    	"fmt"
    	"github.com/jellycheng/godingtalk/message"
    )
    
    func main() {
    
    	req := message.SendWorkNotifyReqDto{}
    	req.AgentID = "1605203268"     //agentid
    	req.UseridList = "manager4056" // 钉钉用户ID,多个逗号分隔
    
    	req.Msg = message.WorkNotifyMsgDto{
    		Msgtype: "text",
    		Text: &message.TextMsgDto{
    			Content: "文本消息内容,如:请尽快提交本周周报",
    		}}
    	accessToken := "1cd01dc304d434e988afd680561712fb" //调用接口:企业内部应用获取access_token
    	resp := message.SendWorkMsg(req, accessToken)
    	fmt.Println(resp)
    }


发送链接消息:
第1步:企业内部应用获取access_token
第2步:
    package main
    
    import (
    	"fmt"
    	"github.com/jellycheng/godingtalk/message"
    )
    
    func main() {
    
    	req := message.SendWorkNotifyReqDto{}
    	req.AgentID = "1605203268"     //agentid
    	req.UseridList = "manager4056" // 钉钉用户ID,多个逗号分隔
    
    	req.Msg = message.WorkNotifyMsgDto{
    		Msgtype: "link",
    		Link: &message.LinkMsgDto{
    			PicURL:     "@lADOADmaWMzazQKA", // 图片资源ID
    			MessageURL: "http://www.baidu.com", //链接地址
    			Title:      "要货单审批", //链接标题名
    			Text:       "张三提交的要货单", //链接描述
    		}}
    	accessToken := "1cd01dc304d434e988afd680561712fb" //调用接口:企业内部应用获取access_token
    	resp := message.SendWorkMsg(req, accessToken)
    	fmt.Println(resp)
    }

发送markdown格式的工作工作消息

package main

import (
	"fmt"
	"github.com/jellycheng/godingtalk/message"
)

func main() {

	req := message.SendWorkNotifyReqDto{}
	req.AgentID = "1605203268"     //agentid
	req.UseridList = "manager4056" // 钉钉用户ID,多个逗号分隔
	markdownText := `
# 张三提交的要货单
[去审批](http://www.baidu.com)

`
	req.Msg = message.WorkNotifyMsgDto{
		Msgtype: "markdown",
		Markdown: &message.MarkdownMsgDto{
			Title: "张三提交的要货单", //标题
			Text:  markdownText, // markdown内容
		}}
	accessToken := "1cd01dc304d434e988afd680561712fb" //调用接口:企业内部应用获取access_token
	resp := message.SendWorkMsg(req, accessToken)
	fmt.Println(resp)
}


根据手机号获取企业账号用户的userId

package main

import (
	"fmt"
	"github.com/jellycheng/godingtalk"
)

func main() {
	req := godingtalk.GetUseridByMobileReqDto{
		Mobile:                        "手机号",
		SupportExclusiveAccountSearch: false,
	}
	accessToken := "1cd01dc304d434e988afd680561712fb" //调用接口:企业内部应用获取access_token
	res := godingtalk.GetUseridByMobile(req, accessToken)
	fmt.Println(res.Result.Userid)

}

查询钉钉用户详情

package main

import (
	"fmt"
	"github.com/jellycheng/godingtalk"
)

func main() {
	accessToken := "68e9ee0cac0035a295923b0bd7dbef76"                          //调用接口:企业内部应用获取access_token
	userid := "18024719687686"                                                 //钉钉用户ID
	userprofileRespDto := godingtalk.GetUserInfo(accessToken, userid, "zh_CN") // 查询钉钉用户信息,包括 unionid
	if userprofileRespDto.Errcode == 0 {
		fmt.Println(fmt.Sprintf("用户详情: %+v", userprofileRespDto.Result))
		fmt.Println("Unionid: ", userprofileRespDto.Result.Unionid)
	} else {
		fmt.Println("错误:", userprofileRespDto.Errmsg)
	}

}

创建钉钉待办任务

package main

import (
	"fmt"
	"github.com/jellycheng/godingtalk/todotask"
)

func main() {
	at := "cb5673b689e132bc93ff6eede12fbe2a" // 访问凭证
	unionId := "G5x1lVRm5TSw2JToFbkOmAiEiE"  // 钉钉用户unionId
	operatorId := unionId
	detailUrl := new(todotask.DetailURL)
	detailUrl.PcURL = "https://www.php.net"    // PC端详情页url跳转地址
	detailUrl.AppURL = "https://www.baidu.com" //APP端详情页url跳转地址

	reqDto := todotask.CreateTodoTaskReqDto{
		Subject:            "钉钉待办标题369",
		CreatorID:          unionId, //创建者的unionId
		Description:        "钉钉代办描述,你有xxx提交的审批单审批",
		ExecutorIds:        []string{unionId},
		IsOnlyShowExecutor: true,
		DetailURL:          detailUrl,
	}
	respDto := todotask.CreateTodoTask(reqDto, at, unionId, operatorId)
	fmt.Println(fmt.Sprintf("%+v", respDto))

}

删除钉钉待办任务

package main

import (
	"fmt"
	"github.com/jellycheng/godingtalk/todotask"
)

func main() {
	at := "5bbb653cff473e279360c7c4755d6ecf" // 访问凭证
	unionId := "G5x1lVRm5TSw2JToFbkOmAiEiE"  // 钉钉用户unionId
	operatorId := unionId
	taskId := "taska684c561500c8674e4f08a57c298f6f7" //任务ID

	respDto := todotask.DeleteTodoTask(at, unionId, operatorId, taskId)
	fmt.Println(fmt.Sprintf("%+v", respDto))

}

更新钉钉待办任务完成

package main

import (
	"fmt"
	"github.com/jellycheng/godingtalk/todotask"
)

func main() {
	at := "5bbb653cff473e279360c7c4755d6ecf" // 访问凭证
	unionId := "G5x1lVRm5TSw2JToFbkOmAiEiE"  // 钉钉用户unionId
	operatorId := unionId
	taskId := "taska731540ae5c7cba052df63a374336912" //任务ID
	status := true // 更新任务完成
	respDto := todotask.UpdateTodoTaskStatus(at, unionId,operatorId,taskId, status)
	fmt.Println(fmt.Sprintf("%+v", respDto))

}

钉钉文档

钉钉开放平台: https://open.dingtalk.com
创建h5微应用: https://open.dingtalk.com/document/orgapp/create-an-h5-micro-application


Documentation

Index

Constants

View Source
const (
	ScopeOpenid                 = "openid"
	ScopeOpenIdCropid           = "openid corpid"
	LoginUrl                    = "%s/oauth2/auth?redirect_uri=%s&response_type=code&client_id=%s&scope=%s&state=%s&prompt=consent"
	UserAccessTokenUrl          = "%s/v1.0/oauth2/userAccessToken"
	UserInfo4UserAccessTokenUrl = "%s/v1.0/contact/users/me"
	// 企业内部应用获取access_token
	GetAccessTokenUrl = "%s/gettoken?appkey=%s&appsecret=%s"
	// 部门列表
	DepartmentUrl = "%s/topapi/v2/department/listsub?access_token=%s"
	// 获取指定部门的userid列表
	DepartmentUseridListUrl = "%s/topapi/user/listid?access_token=%s"
	// 获取指定用户的详细信息
	UserInfoUrl = "%s/topapi/v2/user/get?access_token=%s"

	// 发送工作通知
	WorkNotifyMsgUrl = "%s/topapi/message/corpconversation/asyncsend_v2?access_token=%s"
	// 撤回工作消息
	RecallWorkNotifyMsgUrl = "%s/topapi/message/corpconversation/recall?access_token=%s"

	// 根据手机号获取企业账号用户的userId
	GetUseridByMobileUrl = "%s/topapi/v2/user/getbymobile?access_token=%s"

	// 创建钉钉待办任务 ?operatorId=
	CreateTodoTaskUrl = "%s/v1.0/todo/users/%s/tasks%s"
	// 删除钉钉待办任务 ?operatorId=
	DeleteTodoTaskUrl = "%s/v1.0/todo/users/%s/tasks/%s%s"
	// 查询企业下用户待办列表
	GetTodoTaskUrl = "%s/v1.0/todo/users/%s/org/tasks/query"
	// 更新待办任务状态 /v1.0/todo/users/{unionId}/tasks/{taskId}/executorStatus?operatorId=
	UpdateTodoTaskStatusUrl = "%s/v1.0/todo/users/%s/tasks/%s/executorStatus%s"
	// 更新待办任务信息 /v1.0/todo/users/{unionId}/tasks/{taskId}?operatorId=
	UpdateTodoTaskInfoUrl = "%s/v1.0/todo/users/%s/tasks/%s%s"
)
View Source
const (
	// 新版api域名
	DingApiDomain = "https://api.dingtalk.com"
	// 旧版api域名
	DingOapiDomain  = "https://oapi.dingtalk.com"
	DingLoginDomain = "https://login.dingtalk.com"
)

Variables

This section is empty.

Functions

func BoolPtr

func BoolPtr(b bool) *bool

func Debug

func Debug(msg interface{})

func DeleteUrlContent

func DeleteUrlContent(urlStr string, strJson string, headers map[string]string) (string, error)

func GetDepartmentListTree

func GetDepartmentListTree(accessToken string, deptId int, language string) ([]DepartmentSimpleTree, DingTalkApiErr3Dto)

func GetLoginUrl

func GetLoginUrl(redirectUri, clientId, scope, state string) string

GetLoginUrl 第1步: 拼接钉钉登录地址: https://open.dingtalk.com/document/isvapp-server/obtain-identity-credentials

func GetUrlContent

func GetUrlContent(urlStr string, headers map[string]string) (string, error)

func JsonUnmarshal

func JsonUnmarshal(str string, obj interface{}) error

func PostUrlContnet4json

func PostUrlContnet4json(urlStr string, strJson string, headers map[string]string) (string, error)

func PutUrlContent

func PutUrlContent(urlStr string, strJson string, headers map[string]string) (string, error)

func StringPtr

func StringPtr(s string) *string

func ToJson

func ToJson(v interface{}) string

转成json字符串

Types

type AccessTokenRespDto

type AccessTokenRespDto struct {
	DingTalkApiErr2Dto
	AccessToken string `json:"access_token"`
	ExpiresIn   int    `json:"expires_in"`
}

func GetAccessToken

func GetAccessToken(cfg DingAgentConfig) AccessTokenRespDto

企业内部应用获取access_token

type DepartmentListRespDto

type DepartmentListRespDto struct {
	Errcode   int                    `json:"errcode"`
	Errmsg    string                 `json:"errmsg"`
	RequestID string                 `json:"request_id"`
	Result    []DepartmentSimpleInfo `json:"result"`
}

func GetDepartmentList

func GetDepartmentList(accessToken string, deptId int, language string) DepartmentListRespDto

获取部门列表:只支持获取当前部门的下一级部门基础信息,不支持获取当前部门下所有层级子部门

type DepartmentReqDto

type DepartmentReqDto struct {
	Language string `json:"language,omitempty"`
	DeptID   int    `json:"dept_id,omitempty"`
}

type DepartmentSimpleInfo

type DepartmentSimpleInfo struct {
	AutoAddUser     bool   `json:"auto_add_user"`     // 新人是否自动加入该群,true是,false否
	CreateDeptGroup bool   `json:"create_dept_group"` //是否同步创建一个关联此部门的企业群,true是,false否
	DeptID          int    `json:"dept_id"`           //部门ID
	Name            string `json:"name"`              //部门名称
	ParentID        int    `json:"parent_id"`         //上级部门
}

type DepartmentSimpleTree

type DepartmentSimpleTree struct {
	AutoAddUser     bool                   `json:"auto_add_user"`     // 新人是否自动加入该群,true是,false否
	CreateDeptGroup bool                   `json:"create_dept_group"` //是否同步创建一个关联此部门的企业群,true是,false否
	DeptID          int                    `json:"dept_id"`           //部门ID
	Name            string                 `json:"name"`              //部门名称
	ParentID        int                    `json:"parent_id"`         //上级部门
	SubDeptList     []DepartmentSimpleTree `json:"sub_dept_list"`     // 子部门
}

部门树

type DeptUseridDto

type DeptUseridDto struct {
	UseridList []string `json:"userid_list"`
}

type DeptUseridListRespDto

type DeptUseridListRespDto struct {
	Errcode   int           `json:"errcode"`
	Errmsg    string        `json:"errmsg"`
	RequestID string        `json:"request_id"`
	Result    DeptUseridDto `json:"result"`
}

func GetDepartmentUseridList

func GetDepartmentUseridList(accessToken string, deptId int) DeptUseridListRespDto

获取指定部门的userid列表

type DingAgentConfig

type DingAgentConfig struct {
	AgentId   string
	AppKey    string
	AppSecret string
	AesKey    string
	Token     string
}

应用配置

type DingCorpConfig

type DingCorpConfig struct {
	CorpId   string
	APIToken string
}

企业配置

type DingTalkApiErr2Dto

type DingTalkApiErr2Dto struct {
	Errcode int    `json:"errcode"`
	Errmsg  string `json:"errmsg"`
}

type DingTalkApiErr3Dto

type DingTalkApiErr3Dto struct {
	Errcode   int    `json:"errcode"`
	Errmsg    string `json:"errmsg"`
	RequestId string `json:"request_id"`
}

type DingTalkApiErrDto

type DingTalkApiErrDto struct {
	Requestid string `json:"requestid"`
	Code      string `json:"code"`
	Message   string `json:"message"`
}

type GetUseridByMobileReqDto

type GetUseridByMobileReqDto struct {
	Mobile                        string `json:"mobile"`                           //手机号
	SupportExclusiveAccountSearch bool   `json:"support_exclusive_account_search"` //false、true
}

type GetUseridByMobileRespDto

type GetUseridByMobileRespDto struct {
	DingTalkApiErr2Dto
	Result    UseridByMobileResultDto `json:"result"`
	RequestID string                  `json:"request_id"`
}

type RequestIdDto

type RequestIdDto struct {
	RequestId string `json:"request_id"`
}

type UserAccessTokenReqDto

type UserAccessTokenReqDto struct {
	ClientID     string `json:"clientId"`
	ClientSecret string `json:"clientSecret"`
	Code         string `json:"code,omitempty"`
	GrantType    string `json:"grantType,omitempty"` // authorization_code 、refresh_token
	RefreshToken string `json:"refreshToken,omitempty"`
}

type UserAccessTokenRespDto

type UserAccessTokenRespDto struct {
	DingTalkApiErrDto
	ExpireIn     int    `json:"expireIn"`
	AccessToken  string `json:"accessToken"`
	RefreshToken string `json:"refreshToken"`
	CorpId       string `json:"corpId"` //所选企业corpId
}

func GetUserAccessToken4authCode

func GetUserAccessToken4authCode(authCode string, dingCfg DingAgentConfig) UserAccessTokenRespDto

第2步: 通过用户授权成功后的authCode获取访问令牌

func RefreshToken

func RefreshToken(refreshToken string, dingCfg DingAgentConfig) UserAccessTokenRespDto

刷新访问令牌

type UserInfoRespDto

type UserInfoRespDto struct {
	DingTalkApiErrDto
	Nick      string `json:"nick"` // 昵称
	UnionID   string `json:"unionId"`
	OpenID    string `json:"openId"`
	Email     string `json:"email"`
	AvatarUrl string `json:"avatarUrl"` // 头像地址
	Mobile    string `json:"mobile"`    // 手机号
	StateCode string `json:"stateCode"` // 手机号对应的国家号
}

func GetUserInfo4UserAccessToken

func GetUserInfo4UserAccessToken(userAccessToken string) UserInfoRespDto

第3步: 获取用户信息:https://open.dingtalk.com/document/isvapp-server/dingtalk-retrieve-user-information

type UserProfileDto

type UserProfileDto struct {
	Active        bool   `json:"active"`
	Admin         bool   `json:"admin"`
	Avatar        string `json:"avatar"`
	Boss          bool   `json:"boss"`
	DeptIDList    []int  `json:"dept_id_list"`
	DeptOrderList []struct {
		DeptID int   `json:"dept_id"`
		Order  int64 `json:"order"`
	} `json:"dept_order_list"`
	ExclusiveAccount bool `json:"exclusive_account"`
	HideMobile       bool `json:"hide_mobile"`
	LeaderInDept     []struct {
		DeptID int  `json:"dept_id"`
		Leader bool `json:"leader"`
	} `json:"leader_in_dept"`
	Mobile     string `json:"mobile"`
	Name       string `json:"name"`
	RealAuthed bool   `json:"real_authed"`
	RoleList   []struct {
		GroupName string `json:"group_name"`
		ID        int    `json:"id"`
		Name      string `json:"name"`
	} `json:"role_list"`
	Senior    bool   `json:"senior"`
	StateCode string `json:"state_code"`
	Unionid   string `json:"unionid"`
	Userid    string `json:"userid"`
}

type UserProfileRespDto

type UserProfileRespDto struct {
	Errcode   int            `json:"errcode"`
	Errmsg    string         `json:"errmsg"`
	RequestID string         `json:"request_id"`
	Result    UserProfileDto `json:"result"`
}

func GetUserInfo

func GetUserInfo(accessToken string, userid string, lang string) UserProfileRespDto

获取指定用户的详细信息

type UseridByMobileResultDto

type UseridByMobileResultDto struct {
	ExclusiveAccountUseridList []interface{} `json:"exclusive_account_userid_list"`
	Userid                     string        `json:"userid"`
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL