企业微信客服发送消息代码C#
时间: 2023-08-31 14:04:50 浏览: 117
以下是使用 C# 发送消息到企业微信客服的示例代码:
```csharp
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using Newtonsoft.Json;
public class WeChatService
{
private readonly string _accessToken;
private readonly string _baseUrl;
public WeChatService(string accessToken, string baseUrl = "https://qyapi.weixin.qq.com/cgi-bin/")
{
_accessToken = accessToken;
_baseUrl = baseUrl;
}
public async Task SendMessageAsync(string toUser, string content)
{
var message = new
{
touser = toUser,
msgtype = "text",
text = new
{
content
}
};
var json = JsonConvert.SerializeObject(message);
var url = $"{_baseUrl}message/send?access_token={_accessToken}";
var client = new HttpClient();
var requestContent = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PostAsync(url, requestContent);
response.EnsureSuccessStatusCode();
}
}
```
使用示例:
```csharp
var weChatService = new WeChatService("your_access_token");
await weChatService.SendMessageAsync("user_id", "Hello, World!");
```
其中,`your_access_token` 需要替换成你的企业微信应用的访问令牌,`user_id` 是需要发送消息的用户的企业微信用户ID,`Hello, World!` 是消息内容。