钉钉服务端开发记录demo1


1、注册企业账号。


2、普通企业版Demo地址:
https://github.com/ddtalk/HarleyCorp


下载后导入eclipse   jdk修改为1.7

4.将您的CorpID和CorpSecret配置在Env.java文件

这2个值在钉钉OA管理后台(https://oa.dingtalk.com/)微应用》微应用设置里面


5.如果测试demo代码

关键点agentid如果得来,点击微应用》应用中心》可以新建一个也可以用已有的,随便一个》点击查看agentid,都可以用来发消息。


package com.alibaba.dingtalk.openapi.demo;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.dingtalk.openapi.demo.auth.AuthHelper;
import com.alibaba.dingtalk.openapi.demo.department.DepartmentHelper;
import com.alibaba.dingtalk.openapi.demo.media.MediaHelper;
import com.alibaba.dingtalk.openapi.demo.message.ConversationMessageDelivery;
import com.alibaba.dingtalk.openapi.demo.message.LightAppMessageDelivery;
import com.alibaba.dingtalk.openapi.demo.message.MessageHelper;
import com.alibaba.dingtalk.openapi.demo.user.User;
import com.alibaba.dingtalk.openapi.demo.user.UserHelper;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dingtalk.open.client.api.model.corp.CorpUserDetail;
import com.dingtalk.open.client.api.model.corp.CorpUserDetailList;
import com.dingtalk.open.client.api.model.corp.CorpUserList;
import com.dingtalk.open.client.api.model.corp.Department;
import com.dingtalk.open.client.api.model.corp.MessageBody;
import com.dingtalk.open.client.api.model.corp.MessageBody.OABody.Body;
import com.dingtalk.open.client.api.model.corp.MessageBody.OABody.Body.Form;
import com.dingtalk.open.client.api.model.corp.MessageBody.OABody.Body.Rich;
import com.dingtalk.open.client.api.model.corp.MessageBody.OABody.Head;
import com.dingtalk.open.client.api.model.corp.MessageType;
import com.dingtalk.open.client.api.model.corp.UploadResult;

public class Demo {

	public static void main(String[] args) throws Exception {

		try {

			List<Department> departments = new ArrayList<Department>();
			departments = DepartmentHelper.listDepartments(AuthHelper.getAccessToken(), "1");
			JSONObject usersJSON = new JSONObject();
			
			System.out.println("depart num:"+departments.size());
			for(int i = 0;i<departments.size();i++){
				JSONObject userDepJSON = new JSONObject();
				System.out.println("dep:"+departments.get(i).toString());
		
	            long offset = 0;
	            int size = 5;
	            CorpUserList corpUserList = new CorpUserList();	           
	            while (true) {
	                corpUserList = UserHelper.getDepartmentUser(AuthHelper.getAccessToken(), Long.valueOf(departments.get(i).getId())
	                		, offset, size, null);
	                System.out.println(JSON.toJSONString(corpUserList));
	                if (Boolean.TRUE.equals(corpUserList.isHasMore())) {
	                    offset += size;
	                } else {
	                    break;
	                }
	            }
				if(corpUserList.getUserlist().size()==0){
					continue;
				}
				for(int j = 0;j<corpUserList.getUserlist().size();j++){
					String user = JSON.toJSONString(corpUserList.getUserlist().get(j));
					userDepJSON.put(j+"", JSONObject.parseObject(user, CorpUserDetail.class));

				}

				
				usersJSON.put(departments.get(i).getName(), userDepJSON);
				System.out.println("user:"+usersJSON.toString());
			}
			
			System.out.println("depart:"+usersJSON.toJSONString());


			// 获取access token
			String accessToken = AuthHelper.getAccessToken();
			log("成功获取access token: ", accessToken);

			// 获取jsapi ticket
			String ticket = AuthHelper.getJsapiTicket(accessToken);
			log("成功获取jsapi ticket: ", ticket);

			// 获取签名
			String nonceStr = "nonceStr";
			long timeStamp = System.currentTimeMillis();
			String url = "http://www.dingtalk.com";
			String signature = AuthHelper.sign(ticket, nonceStr, timeStamp, url);
			log("成功签名: ", signature);

			// 创建部门
			String name = "TestDept.34";
			String parentId = "1";
			String order = "1";
			boolean createDeptGroup = true;
			long departmentId = Long.parseLong(DepartmentHelper.createDepartment(accessToken, name, parentId, order, createDeptGroup));
			log("成功创建部门", name, " 部门id=", departmentId);

			// 获取部门列表
			List<Department> list = DepartmentHelper.listDepartments(accessToken, parentId);
			log("成功获取部门列表", list);

			// 更新部门
			name = "hahahaha";
			boolean autoAddUser = true;
			String deptManagerUseridList = null;
			boolean deptHiding = false;
			String deptPerimits = "aa|qq";			
			DepartmentHelper.updateDepartment(accessToken, departmentId, name, parentId, order, createDeptGroup, 
					autoAddUser, deptManagerUseridList, deptHiding, deptPerimits, null, 
					null, null, null, null);

			
			log("成功更新部门", " 部门id=", departmentId);
			
			CorpUserDetail userDetail = new CorpUserDetail();
			userDetail.setUserid("id_yuhuan");
			userDetail.setName("name_yuhuan");
			userDetail.setEmail("yuhuan@abc.com");
			userDetail.setMobile("18612124567");
			userDetail.setDepartment(new ArrayList());
			userDetail.getDepartment().add(departmentId);

			
			UserHelper.createUser(accessToken, userDetail);
			log("成功创建成员", "成员信息=", userDetail);

			// 上传图片
			File file = new File("/Users/ian/Downloads/lALOAVYgbc0DIM0Bwg_450_800.png");
			UploadResult uploadResult = MediaHelper.upload(accessToken, MediaHelper.TYPE_IMAGE, file);
			log("成功上传图片", uploadResult);

			// 下载图片
			String fileDir = "/Users/ian/Desktop/";
			MediaHelper.download(accessToken, uploadResult.getMedia_id(), fileDir);
			log("成功下载图片");

			
			MessageBody.TextBody textBody = new MessageBody.TextBody();
			textBody.setContent("TextMessage");
			
			MessageBody.ImageBody imageBody = new MessageBody.ImageBody();
			imageBody.setMedia_id(uploadResult.getMedia_id());
			
			MessageBody.LinkBody linkBody = new MessageBody.LinkBody();
			linkBody.setMessageUrl("http://www.baidu.com");
			linkBody.setPicUrl("@lALOACZwe2Rk");
			linkBody.setTitle("Link Message");
			linkBody.setText("This is a link message");

			// 创建oa消息
            MessageBody.OABody oaBody = new MessageBody.OABody();
            oaBody.setMessage_url("message_url");
            Head head = new Head();
            head.setText("head.text");
            head.setBgcolor("FFBBBBBB");
            oaBody.setHead(head);

            Body body = new Body();
            body.setAuthor("author");
            body.setContent("content");
            body.setFile_count("file_count");
            body.setImage("@image");
            body.setTitle("body.title");
            Rich rich = new Rich();
            rich.setNum("num");
            rich.setUnit("unit");
            body.setRich(rich);
            List<Form> formList = new ArrayList<Form>();
            Form form = new Form();
            form.setKey("key");
            form.setValue("value");
            formList.add(form);
            body.setForm(formList);
            oaBody.setBody(body);

			// 发送微应用消息
			String toUsers = Vars.TO_USER;
			String toParties = Vars.TO_PARTY;
			String agentId = Vars.AGENT_ID;
			LightAppMessageDelivery lightAppMessageDelivery = new LightAppMessageDelivery(toUsers, toParties, agentId);

			lightAppMessageDelivery.withMessage(MessageType.TEXT, textBody);
			MessageHelper.send(accessToken, lightAppMessageDelivery);
			log("成功发送 微应用文本消息");
			lightAppMessageDelivery.withMessage(MessageType.IMAGE, imageBody);
			MessageHelper.send(accessToken, lightAppMessageDelivery);
			log("成功发送 微应用图片消息");
			lightAppMessageDelivery.withMessage(MessageType.LINK, linkBody);
			MessageHelper.send(accessToken, lightAppMessageDelivery);
			log("成功发送 微应用link消息");
			lightAppMessageDelivery.withMessage(MessageType.OA, oaBody);
			MessageHelper.send(accessToken, lightAppMessageDelivery);
			log("成功发送 微应用oa消息");

			// 发送会话消息
//			String sender = Vars.SENDER;
//			String cid = Vars.CID;//cid需要通过jsapi获取,具体详情请查看开放平台文档--->客户端文档--->会话

//			ConversationMessageDelivery conversationMessageDelivery = new ConversationMessageDelivery(sender, cid,
//					agentId);
//
//			conversationMessageDelivery.withMessage(MessageType.TEXT, textBody);
//			MessageHelper.send(accessToken, conversationMessageDelivery);
//			log("成功发送 会话文本消息");
//			conversationMessageDelivery.withMessage(MessageType.IMAGE, imageBody);
//			MessageHelper.send(accessToken, conversationMessageDelivery);
//			log("成功发送 会话图片消息");
//			conversationMessageDelivery.withMessage(MessageType.LINK, linkBody);
//			MessageHelper.send(accessToken, conversationMessageDelivery);
//			log("成功发送 会话link消息");

			// 更新成员
			userDetail.setMobile("11177776666");
			UserHelper.updateUser(accessToken, userDetail);
			log("成功更新成员", "成员信息=", userDetail);

			// 获取成员
			CorpUserDetail  userDetail11 = UserHelper.getUser(accessToken, userDetail.getUserid());
			log("成功获取成员", "成员userid=", userDetail11.getUserid());

			// 获取部门成员
			CorpUserList userList = UserHelper.getDepartmentUser(accessToken, departmentId, null, null, null);
			log("成功获取部门成员", "部门成员user=", userList.getUserlist());

			// 获取部门成员(详情)
			CorpUserDetailList userList2 = UserHelper.getUserDetails(accessToken, departmentId, null, null, null);
			log("成功获取部门成员详情", "部门成员详情user=", userList2.getUserlist());

			// 批量删除成员
//			User user2 = new User("id_yuhuan2", "name_yuhuan2");
//			user2.email = "yuhua2n@abc.com";
//			user2.mobile = "18611111111";
//			user2.department = new ArrayList();
//			user2.department.add(departmentId);
//			UserHelper.createUser(accessToken, user2);
			
			CorpUserDetail userDetail2 = new CorpUserDetail();
			userDetail2.setUserid("id_yuhuan2");
			userDetail2.setName("name_yuhuan2");
			userDetail2.setEmail("yuhua2n@abc.com");
			userDetail2.setMobile("18612124926");
			userDetail2.setDepartment(new ArrayList());
			userDetail2.getDepartment().add(departmentId);
			UserHelper.createUser(accessToken, userDetail2);

			
			

			List<String> useridlist = new ArrayList();
			useridlist.add(userDetail.getUserid());
			useridlist.add(userDetail2.getUserid());
			UserHelper.batchDeleteUser(accessToken, useridlist);
			log("成功批量删除成员", "成员列表useridlist=", useridlist);

			// 删除成员
//			User user3 = new User("id_yuhuan3", "name_yuhuan3");
//			user3.email = "yuhua2n@abc.com";
//			user3.mobile = "18611111111";
//			user3.department = new ArrayList();
//			user3.department.add(departmentId);
			CorpUserDetail userDetail3 = new CorpUserDetail();
			userDetail3.setUserid("id_yuhuan3");
			userDetail3.setName("name_yuhuan3");
			userDetail3.setMobile("13146654734");
			userDetail3.setDepartment(new ArrayList());
			userDetail3.getDepartment().add(departmentId);

			
			
			UserHelper.createUser(accessToken, userDetail3);
			UserHelper.deleteUser(accessToken, userDetail3.getUserid());
			log("成功删除成员", "成员userid=", userDetail3.getUserid());

			// 删除部门
			DepartmentHelper.deleteDepartment(accessToken, departmentId);
			log("成功删除部门", " 部门id=", departmentId);

		} catch (OApiException e) {
			e.printStackTrace();
		}
	}

	private static void log(Object... msgs) {
		StringBuilder sb = new StringBuilder();
		for (Object o : msgs) {
			if (o != null) {
				sb.append(o.toString());
			}
		}
		System.out.println(sb.toString());
	}
}





  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
钉钉的CalDAV服务器是一个标准的CalDAV服务器,因此你可以使用任何支持CalDAV协议的第三方库来访问它。下面是一个使用Android系统自带的SyncAdapter框架实现的CalDAV同步Demo。 1. 添加依赖 在build.gradle文件中添加以下依赖: ``` dependencies { implementation "com.github.aflx:sardine-android:5.7.0" } ``` 这里使用了Sardine-Android库,它是一个支持WebDAV和CalDAV协议的Android库,可以方便地与钉钉的CalDAV服务器进行交互。 2. 创建SyncAdapter 创建一个继承自AbstractThreadedSyncAdapter的SyncAdapter类,并实现其中的onPerformSync()方法,用于执行CalDAV同步任务。 ```java public class CalDAVSyncAdapter extends AbstractThreadedSyncAdapter { private static final String TAG = "CalDAVSyncAdapter"; private final Sardine mSardine; public CalDAVSyncAdapter(Context context, boolean autoInitialize) { super(context, autoInitialize); mSardine = new OkHttpSardine(); } @Override public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) { try { // TODO: 执行CalDAV同步任务 } catch (Exception e) { Log.e(TAG, "CalDAV sync failed", e); syncResult.stats.numIoExceptions++; } } } ``` 3. 注册SyncAdapter 在AndroidManifest.xml文件中注册SyncAdapter,并指定对应的账户类型和CalDAV服务器地址。 ```xml <application> <provider android:name="android.content.ContentProvider" android:authorities="com.android.calendar" android:exported="false" android:syncable="true" /> <service android:name=".CalDAVSyncAdapterService" android:exported="true"> <intent-filter> <action android:name="android.content.SyncAdapter" /> </intent-filter> <meta-data android:name="android.content.SyncAdapter" android:resource="@xml/caldav_sync_adapter" /> <meta-data android:name="android.provider.CONTACTS_STRUCTURE" android:resource="@xml/contacts" /> </service> </application> <uses-permission android:name="android.permission.READ_CALENDAR" /> <uses-permission android:name="android.permission.WRITE_CALENDAR" /> <uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS" /> <account-authenticator xmlns:android="http://schemas.android.com/apk/res/android" android:accountType="com.android.exchange" android:icon="@drawable/icon_exchange" android:smallIcon="@drawable/icon_exchange" android:label="@string/app_name" /> <sync-adapter xmlns:android="http://schemas.android.com/apk/res/android" android:contentAuthority="com.android.calendar" android:accountType="com.android.exchange" android:userVisible="false" android:supportsUploading="true" android:allowParallelSyncs="false" android:isAlwaysSyncable="true" /> ``` 在res/xml目录下创建caldav_sync_adapter.xml文件,指定SyncAdapter的参数。 ```xml <sync-adapter xmlns:android="http://schemas.android.com/apk/res/android" android:contentAuthority="com.android.calendar" android:accountType="com.android.exchange" android:userVisible="false" android:supportsUploading="true" android:allowParallelSyncs="false" android:isAlwaysSyncable="true" /> ``` 4. 执行CalDAV同步任务 在SyncAdapter的onPerformSync()方法中,使用Sardine库实现CalDAV同步任务。以下是一个简单的例子,可以获取钉钉CalDAV服务器上的所有日历事件。 ```java @Override public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) { try { // 创建Sardine对象 mSardine.setCredentials("username", "password"); // 获取所有日历事件 List<DavResource> resources = mSardine.getResources("https://calendar.dingtalk.com/caldav/username/events/"); // 解析日历事件 for (DavResource resource : resources) { CalendarBuilder builder = new CalendarBuilder(); Calendar calendar = builder.build(resource.getInputStream()); Log.d(TAG, "Event: " + calendar.toString()); } } catch (Exception e) { Log.e(TAG, "CalDAV sync failed", e); syncResult.stats.numIoExceptions++; } } ``` 注意:在使用Sardine库访问CalDAV服务器时,需要使用完整的CalDAV资源地址,例如"https://calendar.dingtalk.com/caldav/username/events/",其中username为钉钉账号的用户名。另外,钉钉的CalDAV服务器使用的是HTTPS协议,需要添加相应的证书验证。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

最土老杨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值