You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

请求Azure Bot(Eco Bot)对接Dynamics 365全渠道服务的代码示例

Azure Bot 与 Dynamics 365 全渠道服务对接代码示例

一、Dynamics 365 全渠道侧前置配置

  • 在Dynamics 365全渠道管理中心创建新的Bot渠道,关联你的Azure Bot注册资源
  • 记录以下关键参数:
    • Dynamics 365组织URL(如https://your-org.crm.dynamics.com)
    • Azure Bot的Microsoft App ID
    • 租户ID(Tenant ID)

二、Azure Bot 代码改造(C# 示例,基于Bot Framework SDK v4)

1. 安装依赖NuGet包

  • Microsoft.Bot.Builder.Integration.AspNet.Core
  • Microsoft.Bot.Connector.Authentication
  • Newtonsoft.Json

2. 核心Bot逻辑代码

using Microsoft.Bot.Builder;
using Microsoft.Bot.Schema;
using Newtonsoft.Json;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

public class EcoBot : ActivityHandler
{
    private readonly string _d365OrgUrl;
    private readonly string _botAppId;
    private readonly string _tenantId;
    private readonly HttpClient _httpClient;

    public EcoBot(string d365OrgUrl, string botAppId, string tenantId)
    {
        _d365OrgUrl = d365OrgUrl;
        _botAppId = botAppId;
        _tenantId = tenantId;
        _httpClient = new HttpClient();
    }

    protected override async Task OnMessageActivityAsync(ITurnContext<IMessageActivity> turnContext, CancellationToken cancellationToken)
    {
        // 处理Eco Bot自身业务逻辑,返回响应给用户
        var botReply = $"Eco Bot收到消息:{turnContext.Activity.Text}";
        await turnContext.SendActivityAsync(MessageFactory.Text(botReply), cancellationToken);

        // 将用户消息同步至Dynamics 365全渠道
        await SyncUserMessageToD365(turnContext.Activity, cancellationToken);
    }

    private async Task SyncUserMessageToD365(IMessageActivity userActivity, CancellationToken cancellationToken)
    {
        var accessToken = await GetD365AccessToken();
        
        // 构造D365消息请求体
        var d365Payload = new
        {
            Activity = new
            {
                Type = "message",
                Text = userActivity.Text,
                From = new { Id = userActivity.From.Id, Name = userActivity.From.Name },
                Conversation = new { Id = userActivity.Conversation.Id },
                ChannelId = "webchat" // 根据实际对接渠道调整,如msteams/facebook等
            },
            BotId = _botAppId,
            TenantId = _tenantId
        };

        var requestUrl = $"{_d365OrgUrl}/api/data/v9.1/microsoftdyn365.SendBotMessage";
        var requestContent = new StringContent(JsonConvert.SerializeObject(d365Payload), System.Text.Encoding.UTF8, "application/json");
        requestContent.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);

        var response = await _httpClient.PostAsync(requestUrl, requestContent, cancellationToken);
        response.EnsureSuccessStatusCode();
    }

    private async Task<string> GetD365AccessToken()
    {
        var tokenEndpoint = $"https://login.microsoftonline.com/{_tenantId}/oauth2/v2.0/token";
        var requestBody = new FormUrlEncodedContent(new[]
        {
            new KeyValuePair<string, string>("grant_type", "client_credentials"),
            new KeyValuePair<string, string>("client_id", _botAppId),
            new KeyValuePair<string, string>("client_secret", "YOUR_BOT_APP_SECRET"), // 替换为你的Bot应用密钥
            new KeyValuePair<string, string>("scope", $"{_d365OrgUrl}/.default")
        });

        var response = await _httpClient.PostAsync(tokenEndpoint, requestBody);
        response.EnsureSuccessStatusCode();
        var tokenResult = JsonConvert.DeserializeObject<dynamic>(await response.Content.ReadAsStringAsync());
        return tokenResult.access_token;
    }
}

3. Startup.cs 配置

public class Startup
{
    private IConfiguration Configuration { get; }

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddHttpClient();

        // 注册EcoBot并传入D365配置参数
        services.AddSingleton<EcoBot>(sp =>
        {
            var d365OrgUrl = Configuration["D365:OrgUrl"];
            var botAppId = Configuration["MicrosoftAppId"];
            var tenantId = Configuration["D365:TenantId"];
            return new EcoBot(d365OrgUrl, botAppId, tenantId);
        });

        services.AddBot<EcoBot>(options =>
        {
            options.CredentialProvider = new SimpleCredentialProvider(
                Configuration["MicrosoftAppId"],
                Configuration["MicrosoftAppPassword"]);
        });
    }

    // 省略Configure方法其他代码
}

三、接收D365全渠道坐席消息

在Bot中添加处理D365回调消息的逻辑,转发给用户:

public override async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken = default)
{
    // 判断是否为D365全渠道发来的坐席消息
    if (turnContext.Activity.ChannelId == "dynamics365")
    {
        var agentReply = $"坐席回复:{turnContext.Activity.Text}";
        await turnContext.SendActivityAsync(MessageFactory.Text(agentReply), cancellationToken);
    }
    else
    {
        await base.OnTurnAsync(turnContext, cancellationToken);
    }
}

四、关键注意事项

  • 确保Azure Bot的服务主体在Dynamics 365中拥有全渠道管理员或消息发送/接收权限
  • 代码中敏感信息(如Bot应用密钥、D365组织URL)需替换为实际值
  • 测试时可先通过Bot Framework Emulator验证本地逻辑,再部署到Azure后对接D365全渠道

内容的提问来源于stack exchange,提问作者knowledge_eater

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 04:06:26