能否从Salesforce调用.NET WebApi?触发场景下如何推送数据至API
Salesforce调用.NET WebApi 实战指南
当然可以!Salesforce完全支持调用外部的.NET WebApi,下面我来一步步帮你解决这两个核心问题:
1. 能否从Salesforce中调用.NET WebApi?
绝对没问题!Salesforce提供了多种灵活的方式来对接外部API,最常用的几种方案包括:
- Apex HTTP类:通过编写Apex代码发起HTTP请求,灵活性拉满,适合复杂业务逻辑场景
- Salesforce Flow/Process Builder:无代码配置,快速实现简单的API调用需求
- External Services:可以将外部API导入为Salesforce中的自定义服务,更规范地管理和调用外部接口
2. 基于Salesforce触发事件调用API并推送数据
以你提到的「新增账户时调用API获取产品价格」为例,我会用Apex触发器+HTTP调用的方案来实现(这也是生产环境中最常用的方式):
第一步:先明确你的.NET WebApi细节
你给出的WebApi是一个GET接口,地址格式为http://your-api-domain/api/product/getPriceForCustomer?id={id},需要传入产品ID参数,返回对应价格。先把你的API代码整理如下:
public class ProductController : ApiController { // GET api/product/getPriceForCustomer?id={id} public decimal GetPriceForCustomer(string id) { try { ConnectionStringSettings connectionString = ConfigurationManager.ConnectionStrings["ERP"]; using (SqlConnection cn = new SqlConnection(connectionString.ConnectionString)) { using (SqlCommand command = new SqlCommand("salesforce_getProductPrice", cn)) { command.CommandType = CommandType.StoredProcedure; command.Parameters.Add("@productId", SqlDbType.VarChar).Value = (object)id ?? DBNull.Value; SqlParameter priceParameter = command.Parameters.Add("@price", SqlDbType.Money); priceParameter.Direction = ParameterDirection.Output; cn.Open(); command.ExecuteNonQuery(); return (decimal)command.Parameters["@price"].Value; } } } catch (Exception e) { Trace.WriteLine(e.Message); return 0; } } }
第二步:在Salesforce中编写调用逻辑
1. 创建HTTP调用工具类(封装API调用逻辑)
public class ExternalApiCaller { public static Decimal getProductPrice(String productId) { // 替换成你的API实际域名 String apiUrl = 'http://your-api-domain/api/product/getPriceForCustomer?id=' + EncodingUtil.urlEncode(productId, 'UTF-8'); Http http = new Http(); HttpRequest request = new HttpRequest(); request.setEndpoint(apiUrl); request.setMethod('GET'); // 如果你的API需要认证(比如API Key、Basic Auth),在这里添加请求头 // request.setHeader('Authorization', 'Bearer ' + yourToken); // request.setHeader('Api-Key', 'your-api-key'); try { HttpResponse response = http.send(request); if (response.getStatusCode() == 200) { // 解析返回的价格(API返回decimal,直接转换即可) return Decimal.valueOf(response.getBody()); } else { System.debug('API调用失败,状态码:' + response.getStatusCode() + ',响应内容:' + response.getBody()); return 0; } } catch (Exception e) { System.debug('调用API时发生异常:' + e.getMessage()); return 0; } } }
2. 创建Account触发器(新增账户时触发API调用)
假设你的Account对象上有一个Product_Id__c自定义字段用来存储产品ID,触发器逻辑如下:
trigger AccountTrigger on Account (after insert) { List<Account> accountsToUpdate = new List<Account>(); for (Account acc : Trigger.new) { // 检查产品ID是否存在 if (acc.Product_Id__c != null && acc.Product_Id__c != '') { Decimal productPrice = ExternalApiCaller.getProductPrice(acc.Product_Id__c); // 将获取到的价格保存到Account的自定义字段(比如Product_Price__c) acc.Product_Price__c = productPrice; accountsToUpdate.add(acc); // 触发通知示例:给账户所有者发送邮件 // Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); // mail.setToAddresses(new List<String>{acc.Owner.Email}); // mail.setSubject('产品价格已更新'); // mail.setPlainTextBody('账户【' + acc.Name + '】对应的产品价格为:' + productPrice); // Messaging.sendEmail(new List<Messaging.SingleEmailMessage>{mail}); } } // 批量更新账户数据 if (!accountsToUpdate.isEmpty()) { update accountsToUpdate; } }
第三步:配置Salesforce远程站点设置
Salesforce默认禁止调用外部域名,你需要把API域名添加到远程站点白名单:
- 进入Salesforce Setup → 搜索「远程站点设置」
- 点击「新建远程站点」
- 填写站点名称、API域名(比如
http://your-api-domain),勾选「启用远程站点」 - 保存即可
额外注意事项
- API认证:如果你的.NET WebApi需要身份验证,一定要在Apex的HttpRequest中添加对应的认证头(比如Bearer Token或Basic Auth)
- 批量处理:如果同时新增多个账户,触发器要注意批量逻辑,避免API调用次数超限
- 异步调用:如果API响应较慢,建议用
@future方法或Queueable Apex实现异步调用,避免阻塞Salesforce事务 - 错误重试:可以根据需求添加重试机制,提升API调用的稳定性
内容的提问来源于stack exchange,提问作者Kshitij Rodrigues
相关产品推荐
相关产品推荐

