接口调用方法
概述
BPMAX 提供了多种方式调用接口,您可以根据使用场景选择合适的调用方式:
- 表单脚本:填写表单时可用于显示三方系统信息
- 流程脚本: 流程节点审批时可用于同步数据
脚本调用
使用 $proxy() 函数
$proxy() 是 BPMAX 提供的接口代理函数,用于在脚本中调用接口。
基本语法
// 获取接口代理对象
const proxy = $proxy('平台标识', options);
// 调用接口
const result = await proxy.接口方法名(参数);参数说明
平台标识:接口平台的 platform_key
options(可选):
instance_key:指定使用的实例标识,不指定则使用默认实例caller:调用来源
调用方式
BPMAX 支持两种调用方式:
1. 直接调用方式
直接调用接口方法,参数按顺序传递。
// 示例:调用企业微信发送消息接口
const result = await $proxy('qywx').sendTextMessage(
'UserID', // 第一个参数:接收人
'这是一条测试消息' // 第二个参数:消息内容
);适用场景:
- 参数较少的接口
- 参数顺序固定的接口
- 快速调用
2. 链式调用方式
使用链式调用构建请求,更灵活地设置各种参数。
// 示例:使用链式调用
const result = await $proxy('crm_system')
.$api('get_customer_detail') // 指定接口
.$path({ id: '12345' }) // 设置路径参数
.$query({ fields: 'name,phone' }) // 设置查询参数
.$header({ 'X-Custom': 'value' }) // 设置请求头
.$call(); // 执行调用链式调用方法:
| 方法 | 说明 | 示例 |
|---|---|---|
| $api(name) | 指定要调用的接口 | .$api('get_customer') |
| $path(params) | 设置路径参数 | .$path({ id: '123' }) |
| $query(params) | 设置查询参数 | .$query({ page: 1 }) |
| $header(headers) | 设置请求头 | .$header({ 'X-Token': 'xxx' }) |
| $body(data) | 设置请求体 | .$body({ name: '张三' }) |
| $call() | 执行调用 | .$call() |
适用场景:
- 参数较多的接口
- 需要动态设置参数的场景
- 需要自定义请求头的场景
调用示例
查询客户信息:
// 使用直接调用方式
async function getCustomerInfo(customerId) {
try {
const result = await $proxy('crm_system').getCustomerDetail(customerId);
if (result.code === 200) {
return result.data;
} else {
throw new Error(result.message);
}
} catch (error) {
console.error('查询客户信息失败:', error);
throw error;
}
}
// 使用链式调用方式
async function getCustomerInfoChain(customerId) {
const result = await $proxy('crm_system')
.$api('get_customer_detail')
.$path({ id: customerId })
.$query({ fields: 'name,phone,email,address' })
.$call();
return result.data;
}
// 使用示例
const customerId = form.customerId;
const customerInfo = await getCustomerInfo(customerId);
console.log('客户名称:', customerInfo.name);
console.log('联系电话:', customerInfo.phone);示例:自定义请求头
// 添加自定义请求头
async function callApiWithCustomHeaders() {
const result = await $proxy('external_system')
.$api('some_api')
.$header({
'X-Request-ID': generateRequestId(),
'X-Client-Version': '1.0.0'
})
.$call();
return result.data;
}