Integration & Automation-FaaS connector
https://docs.aliwork.com/docs/yida_support/wtwabe/zevvr1/_1/md1bw3quarxyb74a
Note: the use of features in this document requires users to have a certain development basis.
1. Function introduction
- The YIDA FaaS (cloud) connector is based on Alibaba Cloud FaaS services, allowing developers to focus on writing business processing code without paying attention to the deployment, operation, and maintenance, scaling, and scaling of servers.Cloud development capabilities.
- Through code editing by developers in the Cloud IDE, YIDA connectors are more suitable for their own business,Flexible customization.
- Adhering to the original intention of YIDA connector, further promoteBreak barriers between low-code products and third-party applicationsThe process.
InstructionsOn YIDA, each organization was given 1,000 FaaS connector calls (30,000 times for attachments exceeding the capacity of 1000 yuan and 100g).
2. Create a FaaS connector
2.1 Cloud Connector creation
FaaS connector is one of the YIDA custom connector types, so it must be created throughConnector factoryPerform the operation.
Operation path:
- Connector creation portal: YIDA official website> Settings (platform management)> connector factory> connector management> create connector> FaaS custom connector> enter the connector name> OK (as shown in Figure 2.1-1)

Figure 2.1-1 Cloud Connector creation Portal
- Enter basic connector information: you can configure the connector name, icon, and introduction. (The operation is shown in Figure 2.1-2)

Figure 2.1-2 basic information of Cloud Connector
- Define connector parameter information: you can configure the name, field, description, and other information of the connector input and output parameters> save> go to the Cloud IDE for development. (The operation is shown in Figure 2.1-3)

Figure 2.1-3 define connector parameters
Description of the go to Cloud IDE development button:
- Function: click this button to verify the cloud resources. After passing, the page jumps to Alibaba Cloud development platform, where developers edit the code to achieve the purpose of customization.
- When the connector is created, the configuration of the connector is saved before it appears. When the connector already exists, the button is displayed directly.
2.2 Introduction to the Cloud IDE page
Further reading:For more information about Cloud IDE, go:What is a cloud development platform.
Cloud IDE is an online IDE of cloud development platform, and cloud development platform is an ownerZero threshold cloud-wide development, unified team business environment, consistent Serverless environment, localized IDE features and experience 」Cloud research and development platforms with extreme features,Help R & D teams to realize online work (team online, environment online, code online, collaborative online) and Serverless R & D mode, help R & D teams to efficiently share and disseminate industry Architecture experience and architecture services, improve R & D efficiency and reduce R & D costs.
2.3 FaaS code on the cloud
Note: currently connectedJavaLanguage,PythonLanguage andNodeJSThe Faas template for the language. (The new connector factory can see the new NodeJS and Python)
2.3.1 entry file path and function
2.3.1.1 Java language
File path:src/main/java/com/alibaba/work/faas/FaasEntry.java. (As shown in Figure 2.3-1)

Figure 2.3-1 path of the entry file
- Function of the entry file:It is used to customize the logic related to FaaS connectors and is more flexible.
2.3.1.2 NodeJS language
File pathRoot Directory> faasEntry.js

2.3.1.3 Python language
File pathRoot Directory> faasEntry.py

2.3.2 Code description of the entry file
Note: currently connectedJavaLanguage,PythonLanguage andNodeJSThe Faas template for the language. (The new version of the connector factory can see the new NodeJS and Python). The following code is an example of Java language code (note: The Faas template for NodeJS and The Faas template for Java are aligned with all functions, the tool class and sample code are complete. The Faas template for Python and Faas template for Java are partially aligned.
//入口文件 FaasEntry.java 初始化代码
package com.alibaba.work.faas;
import java.util.Arrays;
import java.util.Map;
import java.util.Objects;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.work.faas.common.AbstractEntry;
import com.alibaba.work.faas.common.FaasInputs;
import com.alibaba.work.faas.util.DingOpenApiUtil;
import com.alibaba.work.faas.util.YidaConnectorUtil;
import com.alibaba.work.faas.util.YidaConnectorUtil.ConnectorTypeEnum;
import com.alibaba.work.faas.util.YidaConnectorUtil.YidaResponse;
import com.aliyun.fc.runtime.Context;
/**
* @Description 宜搭Faas连接器函数入口,FC handler:com.alibaba.work.faas.FaasEntry::handleRequest
* @Version 2.0
* @Author bufan
**/
public class FaasEntry extends AbstractEntry {
@Override
public JSONObject execute(FaasInputs faasInputs, Context context) {
context.getLogger().info("faasInputs: " + JSON.toJSONString(faasInputs));
//填充宜搭工具类的上下文, 必须调用此方法!!! 请不要删除
initYidaUtil(faasInputs);
//登录态里的钉钉userId
String userId = (String) faasInputs.getYidaContext().get("userId");
//登录态里的钉钉corpId
String corpId = (String) faasInputs.getYidaContext().get("corpId");
//业务传的实际入参(如果您配置了参数映射(也就是点击了连接器工厂里的解析Body按钮并配置了各个参数描述和映射), 那么就是业务实际参数经过参数映射处理后的值)
Map<String,Object> input = faasInputs.getInputs();
/**
* 示例1, 在doYourBusiness方法里编写您的业务代码, 也可以将业务代码封装到其他Class源文件或方法里, cloudIDE和您的本地IDE基本无区别。
*/
// JSONObject result = new JSONObject();
// try {
// Object businessResult = doYourBusiness(input);
// result.put("success",true);
// result.put("result",businessResult);
// result.put("error","");
// return result;
// } catch (Exception e) {
// result.put("success",false);
// result.put("result",null);
// result.put("error",e.getMessage());
// return result;
// }
/**
*示例2, 调用宜搭连接器
*/
// JSONObject result = new JSONObject();
// try {
// Object connectorResult = invokeYidaConnector(faasInputs);
// result.put("success",true);
// result.put("result",connectorResult);
// result.put("error","");
// return result;
// } catch (Exception e) {
// result.put("success",false);
// result.put("result",null);
// result.put("error",e.getMessage());
// return result;
// }
/**
*示例3, 调用钉开放平台OpenAPI
*/
// JSONObject result = new JSONObject();
// try {
// List<String> formInstanceIdList = invokeDingOpenApi();
// result.put("success",true);
// result.put("result",formInstanceIdList);
// result.put("error","");
// return result;
// } catch (Exception e) {
// result.put("success",false);
// result.put("result",null);
// result.put("error",e.getMessage());
// return result;
// }
/**
* 返回的JSONObject并不是一定要带success、result、error, 下面的代码只是示例, 具体返回哪些key-value由您自己决定, 尽量与您在宜搭连接器工厂里配置的出参结构保持一致即可
*/
JSONObject result = new JSONObject();
result.put("success",true);
result.put("result","恭喜您, 成功调用宜搭FASS连接器!");
result.put("error","");
return result;
}
/**
* 将相关参数存到宜搭工具类里, 必须要调用此方法!!! 请不要删除!!!
*
* @param faasInputs
*/
private static final void initYidaUtil(FaasInputs faasInputs){
/**
* 用于调用钉钉开放平台OpenAPI的accessToken, 宜搭提供的, 仅申请了钉钉开放平台的部分OpenAPI的调用权限
* 如果此accessToken不满足您的需求,可在钉钉开放平台创建您自己的钉钉应用并获取appKey和APPSecret并使用com.alibaba.work.faas.util.DingOpenApiUtil获取您自己的customAccessToken
*
* @see com.alibaba.work.faas.util.DingOpenApiUtil#getCustomAccessTokenThenCache(String,String)
*/
String accessToken = (String) faasInputs.getYidaContext().get("accessToken");
// 设置钉开放平台访问token, 后续无需再设置
DingOpenApiUtil.setAccessToken(accessToken);
// try {
// //调用该方法就会自动存储customAccessToken, 之后请不要调用DingOpenApiUtil.setAccessToken(accessToken)将返回的customAccessToken覆盖宜搭传入的accessToken;
// DingOpenApiUtil.getCustomAccessTokenThenCache("您的钉钉应用appKey", "您的钉钉应用appSecret");
// } catch (Exception e) {
// System.out.println("getCustomAccessTokenThenCache error:"+e.getMessage());
// }
/**
*调用宜搭连接器依赖consumeCode
*/
String consumeCode = (String)faasInputs.getYidaContext().get("consumeCode");
//设置连接器消费码, 后续无需再设置
YidaConnectorUtil.setConsumeCode(consumeCode);
}
/**
* 可以将您的业务代码放在这里
*
* @param input
* @return
* @throws Exception
*/
private Object doYourBusiness(Map<String,Object> input) throws Exception{
//取实际的入参
String param1 = (String)input.get("参数1");
String param2 = (String)input.get("参数2");
String paramN = (String)input.get("参数N");
//业务处理
return null;
}
/**
* 示例 调用钉钉官方连接器(待办连接器, 创建待办)
*
* @param faasInputs
* @return
* @throws Exception
*/
private Object invokeYidaConnector(FaasInputs faasInputs) throws Exception {
Map<String,Object> input = faasInputs.getInputs();
String userId = (String)faasInputs.getYidaContext().get("userId");
String corpId = (String)faasInputs.getYidaContext().get("corpId");
JSONObject connectorActionInputs = new JSONObject();
//注意: http连接器的入参是body,query等, 钉钉官方连接器则不是, 请参考宜搭帮助文档 https://www.yuque.com/yida/support/stbfik
{
connectorActionInputs.put("unionId",Arrays.asList(userId));
connectorActionInputs.put("subject",(String)input.get("title"));
connectorActionInputs.put("creatorId",Arrays.asList(userId));
connectorActionInputs.put("description","Faas连接器里调用钉钉官方连接器创建待办");
connectorActionInputs.put("dueTime",System.currentTimeMillis()+600*1000);
connectorActionInputs.put("priority",10L);
}
//请确保调用前设置了consumeCode
//更多钉钉官方连接器ID和动作ID及出入参请参照 https://www.yuque.com/yida/support/stbfik#Mv0dK (如果目标段落不存在, 请访问 https://www.yuque.com/yida/support/stbfik)
YidaResponse response = YidaConnectorUtil.invokeService("G-CONN-1016B8AEBED50B01B8D00009","G-ACT-1016B8B1911A0B01B8D0000I", ConnectorTypeEnum.DING_INNER_CONNECTOR,null,connectorActionInputs);
if (Objects.nonNull(response) && response.isSuccess()){
try {
return YidaConnectorUtil.extractYidaConnectorExecutionResult(response);
} catch (Exception e) {
throw new Exception(e.getMessage());
}
}else {
throw new Exception(Objects.isNull(response)?"执行宜搭连接器失败":response.getErrorCode() +" "+response.getErrorMsg());
}
}
/**
* 示例 批量创建宜搭表单实例
*
* @return
* @throws Exception
*/
private List<String> invokeDingOpenApi() throws Exception {
BatchSaveFormDataRequest request = new BatchSaveFormDataRequest();
request.setAsynchronousExecution(true);
request.setKeepRunningAfterException(true);
request.setNoExecuteExpression(true);
request.setAppType("宜搭应用编码");
request.setUserId("钉钉userId");
request.setSystemToken("宜搭应用systemToken");
request.setFormUuid("表单编码");
JSONObject formData = new JSONObject();
formData.put("表单组件1的ID", "表单组件1的值");
formData.put("表单组件2的ID", "表单组件2的值");
//批量创建200条
request.setFormDataJsonList(Collections.nCopies(200,formData.toJSONString()));
return DingOpenApiUtil.batchSaveFormData(request);
}
}
Disassemble the preceding code:
execute()
Is an entry function that hosts the editing of FaaS connector logic. There are two input parameters, which are FaasInputs respectively.(Need to focus on)And Context.FaasInputs
The parameter has two properties:
yidaContext
: used to obtain YIDA server context content and additional content. Currently, four context variables (hereinafter referred to as variables) can be obtained. More relevant context variables will be brought out as needed):
VariableuserId
Used to obtain the DingTalk user ID of the current login person;
VariablecorpId
Used to obtain the unique identity of the enterprise where the current login is located on DingTalk;
VariableaccessTokenUsed to call DingTalk open platform OpenAPI;
Note: The Faas code template provides a tool class that can easily call DingTalk open platform OpenAPI. You can also use the tool class to write code to obtain your own accessToken to call DingTalk open platform OpenAPI.
VariableconsumeCodeIt is used to call YIDA connectors (DingTalk connectors, DingTalk three-party connectors, and custom HTTP connectors) and YIDA platform interfaces in Faas connectors;
Note: The Faas code template provides a tool class that can easily call the YIDA connector.
inputs
: enter the actual input parameter of the FC function:
Remarks:
If you configure the parameter mapping of Faas connector input parameters in the connector factory, the actual input parameter is the input parameter object that you call the Faas connector to obtain after parameter mapping.
If you do not configure the parameter mapping of the Faas connector input parameters in the connector factory, YIDA directly passes the input parameters that you call the Faas connector to the FC function.
- Business logic writing area: You do not have to write business logic in the execute() function. You can add new methods to existing classes, create new classes, and maven pom.xml introduces the dependencies you need. You only need to return the business results in execute functions.
The returned result type isJSONObject: Stores business execution results.
2.3.3 breakpoint debugging
Currently, the FaaS code templates provided by the YIDA Faas connector can be Java, NodeJS, and Python development languages, all of which support breakpoints.debug
, the specific operation is prompted in the Cloud IDE. Java language can also be added to classesmain
Function and execute the main function in the Cloud IDE and observe the output in the Cloud IDE console.
Java breakpoint debugging
The following figure shows an example of breakpoint Debug in Java environment (note: breakpoint debugging in NodeJS and Python is similar to Java. The difference is that breakpoints in NodeJS and Python are automatically generated by IDE, java does not need to automatically generate debugging configuration files)


NodeJS breakpoint debugging
- Install Node dependencies according to README.md in the root directory of the project, as shown in the following figure.

- Switch to the debugging panel to add a debugging configuration file (click the "start debugging" button in the triangle for the first time to automatically create a debugging configuration file (select NodeJS configuration). You do not need to fill in the debugging configuration yourself.
{
// 使用 IntelliSense 了解相关属性。
// 悬停以查看现有属性的描述。
// 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch Program",
"skipFiles": [
"<node_internals>/**"
],
"program": "${workspaceFolder}/test/tpl.test.js"
}
]
}

(() => {
handler(JSON.stringify({
"body": JSON.stringify({
"inputs": {
},
"yidaContext": {
"accessToken": "17f5033ce3d733fbb0c63fed5f24d9cb",
"consumeCode": "193F27DDD0AD40186D7E4707C12DB4D44CBC2B89E8D4813708ED88D0E7BDF86FF1226683194967A585E53BE531E2A3FA5110FEEFB2363906F055C25B78F3F2EE93EB5B067E0171B5E1C9A18958A43658E3F7289C5FF8A42FE48E288364F14BD661C36AC5F2B459F9DA95ADDB94AB65D6",
"corpId": "您的钉钉corpId",
"userId": "您的钉钉userId"
}
})
}), {}, (error, response) => {
console.info(error ? ("error:" + JSON.stringify(error) + " " + error.name + " " + error.message) : "", "\n\nresponse:", JSON.stringify(response));
})
})();

- To break a breakpoint, you can also add an execution statement and break a breakpoint.

- Go to the debug Panel and click the Start debug button to enter the debug status.

Python breakpoint debugging
For more information, see NodeJS breakpoint debugging.
2.3.4 save, submit and push code
- Save the modified source code (shortcut keys: Mac is command + s , Windows is ctrl + s)(manual save is not required, because when committing, CloudIDE will ask if you want to automatically save all files that have been edited and unsaved. If you select yes, the modified files will be automatically saved.)
- In the left sidebar of CloudIDE, go to the git panel (as shown in the following figure) and click the submit code button (the icon is✔⊙) and fill in the commit information in the pop-up input box, press enter, and then click the menu (the icon is three dots) to select "push", which will be pushed to the remote code warehouse.

You can also use git commands: the cloud platform has built-in Git commands like the well-known IDE. After writing its own business logic code, you can also use various git commands to save, submit, and push code.
- Save:
git add.
- Submit:
git commit
- Push:
git push
2.3.5 deployment
After the code is pushed to the remote repository, click deploy Button> SelectOnline Environment> Click deploy. (The operation is shown in Figure 2.3-2)

Figure 2.3-2 application deployment
Note:YIDA currently, only the FaaS code that calls the online environment for deployment is open (the Faas connector will be opened to test in the connector factory in YIDA, that is, the Faas pre-release environment will be called). Therefore, select an online environment for deployment.
The code is deployed successfully, indicating that the connector has been created and can be used in YIDA.
2.3.6 print and view running logs
2.3.6.1 how to print running logs
YIDA adds recommend logs to facilitate troubleshooting. There are several ways to print logs:
- You can obtain the Logger object from the second input parameter Context object of the entry function and print the log, namely:context.getLogger().info(Your log), orcontext.getLogger().warn(Your log), orcontext.getLogger().error(Your log).
- Use the programming language's own log printing method
- Java language can be used
System.out.print
OrSystem.out.printlnMethod to log. (Please add keywords to the log and separate the keywords with the strings before and after them with spaces. Otherwise, it may not match when retrieving logs) - NodeJS language can be usedconsole.infoTo print logs. (Please add keywords to the log and separate the keywords with the strings before and after them with spaces. Otherwise, it may not match when retrieving logs)
- Python can be usedlogger in logging moduleTo print logs (already provided in the Python Faas template) (please add keywords to the logs and separate the keywords with the strings before and after them with spaces, otherwise the logs may not match)
As shown in the following figure (Java example):

2.3.6.2 how to view the printed running logs:
- Go to the connector Editing mode: connector factory> find the corresponding connector> Click Go to Cloud IDE development 」. (The operation is shown in Figure 2.3-3)

Figure 2.3-3 enter the connector editing mode
- Go to the application list: Application Management> cloud native applications 」. (Operation is shown in Figure 2.3-4)

Figure 2.3-4 enter the application list
- Select the corresponding connector to go to the log management page: Select Applications> O & M monitoring> log management page. (Operation is shown in Figure 2.3-5)

Figure 2.3-5 log management
- Environment choose online environment> log query option with release words, compared with the following figure
wblogrelease-fc-2022012501607003
> enter keywords> perform Log Query (as shown in Figure 2.3-6)

Figure 2.3-6 view logs
2.4 Use of FaaS connector
2.4.1 Use in connector data sources
Expand reading:For more information about the YIDA connector data source features, go to the following steps:远程数据源调用自定义连接器
2.4.2 use in integration & automation and approval flows
Expand reading:For more information about YIDA integration and automation functions, go to the following steps:集成&自动化-连接器
2.4.3 call YIDA connector in Faas code
Call YIDA connector: (see faas code for more detailed instructions)
com.alibaba.work.faas.util.YidaConnectorUtil#invokeService(String connectorId,String actionId, ConnectorTypeEnum connectorTypeEnum, Long connection,JSONObject inputs)
Refer to this article:What functions are implementedSample Entry function code
2.4.4 call the YIDA platform interface in Faas code
YIDA platform interface reference:YIDA platform interface
Call the YIDA platform interface: (see faas code for more detailed instructions)
com.alibaba.work.faas.util.YidaConnectorUtil
getYidaApi(String path,Map,String> headers,Map,String> queries)
postYidaApi(String path,Map,String> headers,Map,String> queries,Map,String> bodies)
2.4.5 call DingTalk open platform OpenAPI in Faas code
Call DingTalk open platform OpenAPI: (see faas code for more detailed instructions)
com.alibaba.work.faas.util.DingOpenApiUtil
getOpenUrl(String userId,String appType,String systemToken,Long timeout, String url)throwsException
startProcessInstance(String appType,String systemToken,String userId,String language,String formUuid,String formDataJson,String processCode,String departmentId)throwsException
saveFormData(SaveFormDataRequest saveFormDataRequest)throwsException
Wait.
2.4.6 call HTTP service in Faas code
Provides HTTP tool classes:
com.alibaba.work.faas.util.HttpUtil
doGet(String schemaAndHost, String path, Map headers, Map queries)
doPost (StringschemaAndHostStringpathMap<String,String> headersMap<String,String> queriesMap<String,String> bodies)
doPost (StringschemaAndHostStringpathMap<String,String> headersMap<String,String> queriesStringbody)
doPost (StringschemaAndHostStringpathMap<String,String> headersMap<String,String> queries, byte[] body)
doPut (StringschemaAndHostStringpathMap<String,String> headersMap<String,String> queriesStringbody)
doPut (StringschemaAndHostStringpathStringmethodMap<String,String> headersMap<String,String> queries, byte[] body)
doDelete (StringschemaAndHostStringpathMap<String,String> headersMap<String,String> queries)
3. Use cases
3.1 travel code identification
3.1.1 case scenario
Under the background of strict epidemic prevention and control, the Verification of travel code and health code is undoubtedly the top priority of epidemic prevention work. Previously, manual verification was required for the travel code, which was time-consuming and laborious. Now, YIDA passesUse the FaaS connector in remote data sources on page YIDA, realize the travel codeAutomatic recognitionAnd backfill the read information into the YIDA form. It can greatly reduce the workload of Epidemic prevention personnel and improve the accuracy of verification.
3.1.2 video demonstration
此处为语雀视频卡片,点击链接查看:宜搭Faas连接器实操示例.mov
YIDA FaaS connector practical example
3.2 SMS notification
3.2.1 create FaaS connector
Follow the above creation process to create an SMS notification FaaS connector. The request Body and java code are as follows:
- Connector request Body configuration
{
"phoneNumbers": "15915915901",
"signNum": "sign",
"templateCode": "code",
"templateParam": "param",
"accessKeyId": "ak",
"accessKeySecret": "as"
}

- java code
- Add dependencies to pom.xml
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>dysmsapi20170525</artifactId>
<version>2.0.9</version>
</dependency>
- src/FaasEntry.java code replacement
package com.alibaba.work.faas;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.work.faas.common.AbstractEntry;
import com.alibaba.work.faas.common.FaasInputs;
import com.alibaba.work.faas.util.DingOpenApiUtil;
import com.alibaba.work.faas.util.YidaConnectorUtil;
import com.aliyun.fc.runtime.Context;
import com.aliyun.tea.*;
import com.aliyun.dysmsapi20170525.*;
import com.aliyun.dysmsapi20170525.models.*;
import com.aliyun.teaopenapi.*;
import com.aliyun.teaopenapi.models.*;
/**
* @Description 宜搭Faas连接器函数入口,FC handler:com.alibaba.work.faas.FaasEntry::handleRequest
* @Version 2.0
* @Author bufan
**/
public class FaasEntry extends AbstractEntry {
@Override
public JSONObject execute(FaasInputs faasInputs, Context context) {
context.getLogger().info("faasInputs: " + JSON.toJSONString(faasInputs));
/**
*用于调用钉钉开放平台OpenAPI的accessToken, 宜搭提供的, 仅申请了钉钉开放平台的部分OpenAPI的调用权限
*如果此accessToken不满足您的需求, 可在钉钉开放平台创建您自己的钉钉应用并获取appKey和APPSecret并使用com.alibaba.work.faas.util.DingOpenApiUtil获取您自己的accessToken
* @see com.alibaba.work.faas.util.DingOpenApiUtil#getCustomAccessTokenThenCache(String, String)
*/
String accessToken = (String)faasInputs.getYidaContext().get("accessToken");
//设置钉开放平台访问token, 后续无需再设置
DingOpenApiUtil.setAccessToken(accessToken);
/**
*调用宜搭的前端消费接口时使用
*/
String consumeCode = (String)faasInputs.getYidaContext().get("consumeCode");
//设置连接器消费码, 后续无需再设置
YidaConnectorUtil.setConsumeCode(consumeCode);
Map<String,Object> input = faasInputs.getInputs();
String ak = (String)input.get("accessKeyId");
String as = (String)input.get("accessKeySecret");
String phoneNumbers = (String)input.get("phoneNumbers");
String signNum = (String)input.get("signNum");
String templateCode = (String)input.get("templateCode");
String templateParam = (String)input.get("templateParam");
JSONObject result = new JSONObject();
result.put("success",true);
result.put("message","");
result.put("code","");
try {
com.aliyun.dysmsapi20170525.Client client = createClient(ak, as);
SendSmsRequest sendSmsRequest = new SendSmsRequest();
// 复制代码运行请自行打印 API 的返回值
sendSmsRequest.setPhoneNumbers(phoneNumbers);
sendSmsRequest.setSignName(signNum);
sendSmsRequest.setTemplateCode(templateCode);
sendSmsRequest.setTemplateParam(templateParam);
SendSmsResponse res = client.sendSms(sendSmsRequest);
String resCode = res.getBody().getCode();
if ("ok".equalsIgnoreCase(resCode)) {
return result;
}
else {
System.out.println("invoke failed:" + JSON.toJSONString(res));
result.put("success",false);
result.put("message",res.getBody().getMessage());
result.put("code",resCode);
return result;
}
}
catch(Exception ex) {
System.out.println("meet errot");
ex.printStackTrace();
result.put("success",false);
result.put("message",ex.getMessage());
return result;
}
}
private static com.aliyun.dysmsapi20170525.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
Config config = new Config()
// 您的AccessKey ID
.setAccessKeyId(accessKeyId)
// 您的AccessKey Secret
.setAccessKeySecret(accessKeySecret);
// 访问的域名
config.endpoint = "dysmsapi.aliyuncs.com";
return new com.aliyun.dysmsapi20170525.Client(config);
}
}
3.2.2 purchase Alibaba Cloud SMS
Go to Alibaba Cloud to buy 「SMS serviceAnd configure SMS Signature and template (follow Alibaba Cloud documentation).
3.2.3 configuration automation process
Use the configured SMS notification FaaS connector in automation, and then configure the parameters. You can also call SMS notifications from the connector data source in the designer to send SMS messages.

4. FAQ
Q: Applicable scenarios for FaaS connectors?
A: The original intention of FaaS connector isAutomatically connect the link and context of Alibaba Cloud function computing (FC) service, if you have not used Alibaba Cloud function computing service or are not familiar with it, you can use the FaaS connector of YIDA. If you already have Alibaba Cloud function computing service, you can use the YIDA HTTP custom connector for access (note: Currently, the YIDA connector factory only supports Alibaba Cloud API GatewayCall APIs through simple authentication (AppCode), not supported yetAbstract signature authentication method (APP Key and APP Secret) call the API,If the authentication method configured when you expose function compute through Alibaba Cloud API Gateway is Simple Authentication, you can access your function Compute Service through YIDA HTTP custom connector).
Q: What functions does the FaaS connector implement when connecting the link and context functions of Alibaba Cloud function computing service?
A: The functions we implement are as follows:
● automatically create a RAM user, establish a RAM user login state through SAML2.0, and load the Faas code template provided by us.
● automatically transfer YIDA context (including YIDA userId of the DingTalk login person, YIDA corpId of the enterprise to which the login person belongs, etc.)
● ecological capabilities, can be reused, business opportunities, etc.
● provides HTTP calling tools to facilitate you to call HTTP services.
● provides basic DingTalk accessToken and corresponding tool classes for easily calling DingTalk YIDA on the Open API Open platform and other DingTalk on the Open API Open platform (you can also use your own accessToken).
● tools are provided to easily call existing connector actions in YIDA (including DingTalk one-party connectors, DingTalk three-party connectors, and custom HTTP connectors), as well as YIDA platform interfaces.
Later, more useful tools will be built into the Faas code template.
Q: YIDA mapping between FaaS connector and Alibaba Cloud FaaS service?
A: After the FaaS connector is created and saved in the connector factory, A unique Faas Connector id is actually generated in the background of YIDA. The user clicks "go to Cloud IDE development" for the first time and YIDA the background system will call the relevant API of Alibaba Cloud to create an Alibaba cloud application space and obtain the id of the application space, YIDA records the binding relationship between the Faas Connector id and the Alibaba Cloud Application id. The Alibaba cloud application space id is a part of the url of the Cloud IDE and also a part of the domain name of the Alibaba Cloud Application. When running, the background system can use this Alibaba cloud application space id and its correspondingAPP Key and APP Secret pass signature authenticationCall the function Compute Service exposed to Alibaba Cloud API Gateway.
5. Common errors and solutions
5.1 execution exceptionFC function error:NotFound
Cause: The code is not deployed to the online environment and needs to be deployed. (Faas connectors deployed in online environments are displayed in the integration automation designer and approval flow designer, however, in the initial stage, in order to prevent users from thinking that the Faas connector retrieval system is abnormal when they forget to deploy the online environment, it will also be displayed in the connector selection list when the online environment is not deployed)
Solution:Click to view how to deploy.
5.2 enter the CloudIDE interface and find that the workspace is being initialized"
Always in the state shown in the following figure, you can enterhttps://ide.aliyun.comFreeze the workspace and refresh the CloudIDE page.

5.3 WhyFAAS connectorRun 10 seconds to report an error: Readtimed out
FAASThe execution duration of the function can be adjusted to 600s, but the YIDA duration of the process of calling the FASS cloud function on the timeout side and waiting for the execution result is 10s, which cannot be adjusted currently.
