背景:
最近有潜在需求,希望SAP能自动推送异常信息给对应的钉钉用户,和负责钉钉的同事讨论后,确定自动推送工作通知消息,本次仅做研究,为后续工作做技术刺探。
有图有真相
问题描述:
研究钉钉发送工作通知API后,通过官方API Explorer和第三方工具均可以成功调用,不过最大的问题在于Token有效期仅2小时,如果通过SAP PI 调用就需要先解决动态Token的问题。(公司要求SAP对外网仅能通过SAP PI,只有这条路了)
分析钉钉请求结构(https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2?access_token=ACCESS_TOKEN),需要将Token拼接到请求中,而SAP PI 提供的认证方式,仅Oauth 支持,但是钉钉并没有采用通用的Oauth 认证方式(参数不同,无法使用),这就是最大的问题点。
方案描述:
当你头大的时候,就要想,SAP作为行业解决方案的专家,这种例外情况没考虑到?如果没有,就不能叫专家了。如果有,那就是自己还没有发现,需要求助官网和各路大神了。这不,曲线报国的方案就来了,有两个方案可以实现本需求。
1、开发两个SAP PI接口,第一个接口专门负责获取Token,第二个接口专门负责推送(通过替换拼接到URL中)
2、研究SAP PI的UDF功能,在ESR的message mapping for request 组件中请求Token,而后在
Communication channel for receiver中通过替换拼接到URL中。
关于第一个方案,已经有大神实现了,这里不用赘述,本文中详细讲解第二个方案。
方案细节:
方案中与常规SAP PI的不同点主要有两处:1、UDF功能 2、替换拼接功能。
下面就根据这两个功能点做详细分析:
1、UDF功能
* You can create source text for the class body in area 'Attributes and Methods'.
* Exceptions are import statements; you must enter these in the import table. You
* can use the inner classes, methods, and attributes defined here in the user-defined
* functions and in the methods "init, cleanUp"
* You can also use classes from imported archives that are in the same software
* component version as the function library, or in a sub software component version.
* You must specify the imported archives in table 'Archives Used'
更多知识,参考大神博文:
SAP XI/PI/PO Mapping tricks and UDF samples
SAP接口集成-PO/PI FunctionLibrary和UDF篇
本次案例中不涉及过于复杂的判断,仅需要额外获取Token值,放在Request的token字段中,然后在Channel中使用。
ESR中Message mapping for Request 如图
通过Toke_token 获取Token值并传到Message type中。
take_token逻辑具体实现如下:
实现代码:(appkey 和 appsecret 根据自己的测试用例填写)
DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
OapiGettokenRequest request = new OapiGettokenRequest();
request.setAppkey("");
request.setAppsecret("");
request.setHttpMethod("GET");
OapiGettokenResponse response = new OapiGettokenResponse();
try {
//OapiGettokenResponse response = client.execute(request);
response = client.execute(request);
} catch (ApiException e) {
e.printStackTrace();
}
return response.getAccessToken();
2、替换拼接功能
官方手册:Configuring the Receiver REST Adapter
ID中Communication Channel for Receiver
-REST URL 页签
Ps.需要替换的字符串需要用大括号,然后使用XPath方式替换
-HTTP Headers页签
最终效果如图:
另外,如果测试过程中遇到类似 Error while silently connecting 的问题(说多了都是泪),第一时间检查更新钉钉的证书情况,具体细节可以查考下面两位大神的文章:
Peer certificate rejected by ChainVerifier接口错误处理
【实测避坑】SAP PI/PO系统 配置证书调用https地址