【问题标题】:Add a Template sample image to WhatsApp Cloud API将模板示例图像添加到 WhatsApp Cloud API
【发布时间】:2022-09-27 14:28:34
【问题描述】:

再会

我正在尝试使用此处描述的 WhatsApp 云 API 在C# 中创建一个带有媒体标头的模板:Resumable Upload API。 现在,每当我创建模板时,都会返回一个错误:不支持文件类型.

我已经在网上搜索了其他有相同经历但没有找到解决我的问题的开发人员的示例。 我遵循了这两个帖子中的建议/解决方案,但仍然很幸运:

我的步骤:

  1. 我成功创建了一个会话。
  2. 我使用返回的 sessionId 上传媒体,也没有问题。
  3. 然后我尝试使用返回的句柄创建模板(在步骤 2 中)。此步骤返回错误不支持的文件类型.

    代码:

    创建会话

    // Create the session
    var sessionId = \"\";
    using (var httpClient = new HttpClient())
    {
        using (var request = new HttpRequestMessage(new HttpMethod(\"POST\"), $\"https://graph.facebook.com/v14.0/{appId}/uploads\"))
        {
            request.Headers.TryAddWithoutValidation(\"Authorization\", \"Bearer \" + _accessToken);
            request.Headers.TryAddWithoutValidation(\"Content-Type\", \"application/json\");
    
            request.Content = new StringContent(\"{\\\"file_length\\\":\\\"16384\\\",\\\"file_type\\\":\\\"image/png\\\",\\\"file_name\\\":\\\"test.png\\\"}\");
    
            var response = await httpClient.SendAsync(request);
            var responseContent = response.Content.ReadAsStringAsync().Result;
            var result = System.Text.Json.JsonSerializer.Deserialize<SessionResponse>(responseContent);
            sessionId = result.id;
        }
    }
    

    上传媒体

    var handle = \"\";
    var dataBinary =  System.IO.File.ReadAllBytes(@\"C:\\Temp\\IMAGES\\test.png\");
    using (var httpClient = new HttpClient())
    {
        using (var request = new HttpRequestMessage(new HttpMethod(\"POST\"), $\"https://graph.facebook.com/v14.0/{sessionId}\"))
        {
            request.Headers.TryAddWithoutValidation(\"Authorization\", \"OAuth \" + _accessToken);
            request.Headers.TryAddWithoutValidation(\"file_offset\", \"0\");
            request.Headers.TryAddWithoutValidation(\"Content-Type\", \"multipart/form-data\");
    
            var multipartContent = new MultipartFormDataContent();
            multipartContent.Add(new ByteArrayContent(dataBinary));
            request.Content = multipartContent;
    
            var response = await httpClient.SendAsync(request);
            var responseContent = response.Content.ReadAsStringAsync().Result;
            var result = System.Text.Json.JsonSerializer.Deserialize<MediaUploadSessionResponse>(responseContent);
            handle = result.h;
        }
    }
    

    创建模板

    jsonData:(本例中未添加完整句柄)

    {
        \"name\":\"template_media\",
        \"components\":[
           {
              \"type\":\"HEADER\",
              \"format\":\"IMAGE\",
              \"example\":{
                 \"header_handle\":[
                    \"4:::ARaVEoRalHjf9hIFnYJb2O9I6BJeHNoonwkB....\"
                 ]
              }
           },
           {
              \"type\":\"BODY\",
              \"text\":\"Please find media attached as requested.\"
           }
        ],
        \"language\":\"en_US\",
        \"category\":\"TRANSACTIONAL\"
     }
    

    要求:

    using (var httpClient = new HttpClient())
    {
        using (var request = new HttpRequestMessage(new HttpMethod(\"POST\"), $\"https://graph.facebook.com/v14.0/{_businessAccountID}/message_templates\"))
        {
            request.Headers.TryAddWithoutValidation(\"Authorization\", \"Bearer \" + _accessToken);
    
            request.Content = new StringContent(jsonData);
            request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(\"application/json\");
    
            var response = await httpClient.SendAsync(request);
            var responseContent = response.Content.ReadAsStringAsync().Result;
        }
    }
    

    返回错误 (不支持的文件类型):

    {
        \"error\": {
            \"message\": \"Invalid parameter\",
            \"type\": \"OAuthException\",
            \"code\": 100,
            \"error_subcode\": 2388084,
            \"is_transient\": false,
            \"error_user_title\": \"File Type Not Supported\",
            \"error_user_msg\": \"The type of file is not supported.\",
            \"fbtrace_id\": \"AZalksSZjALNaBLXiiJzgZw\"
        }
    }
    

    请帮忙,谢谢。

  • 首先,在邮递员中尝试此流程,成功后您可以在代码中尝试。关注answer。这是postman collection,用于快速测试。
  • 谢谢turivishal,我也尝试过,但没有运气。
  • 你可能做错了什么或遗漏了什么。

标签: c# api facebook-graph-api cloud whatsapp


【解决方案1】:

我找到了解决方案,希望这可以帮助其他人解决同样的问题。

我没有将“Content-Type”标头添加到请求中,而是将它们添加到请求内容,例如:request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");

我还将MultipartFormDataContent 更改为ByteArrayContent,内容标题为application/x-www-form-urlencoded

有关对我有用的完整代码示例,请参见下文。

创建会话

var sessionId = "";
using (var httpClient = new HttpClient())
{
    using (var request = new HttpRequestMessage(new HttpMethod("POST"), $"https://graph.facebook.com/v14.0/{appId}/uploads"))
    {
        request.Headers.TryAddWithoutValidation("Authorization", "Bearer " + _accessToken);
        
        request.Content = new StringContent("{\"file_length\":\"16384\",\"file_type\":\"image/png\",\"file_name\":\"test.png\"}");
        request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");

        var response = await httpClient.SendAsync(request);
        if (!response.IsSuccessStatusCode)
            return null;

        var responseContent = response.Content.ReadAsStringAsync().Result;
        var result = System.Text.Json.JsonSerializer.Deserialize<SessionResponse>(responseContent);
        sessionId = result.id;
    }
}

上传媒体

var handle = "";
var dataBinary =  System.IO.File.ReadAllBytes(@"C:\Temp\IMAGES\test.png");
using (var httpClient = new HttpClient())
{
    using (var request = new HttpRequestMessage(new HttpMethod("POST"), $"https://graph.facebook.com/v14.0/{sessionId}"))
    {
        request.Headers.TryAddWithoutValidation("Authorization", "OAuth " + _accessToken);
        request.Headers.TryAddWithoutValidation("file_offset", "0");

       request.Content = new ByteArrayContent(dataBinary);
       request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded");

        var response = await httpClient.SendAsync(request);
        if (!response.IsSuccessStatusCode)
            return null;

        var responseContent = response.Content.ReadAsStringAsync().Result;
        var result = System.Text.Json.JsonSerializer.Deserialize<MediaUploadSessionResponse>(responseContent);
        handle = result.h;
    }
}

创建模板

jsonData:(本例中未添加完整句柄)

{
    "name":"template_media",
    "components":[
       {
          "type":"HEADER",
          "format":"IMAGE",
          "example":{
             "header_handle":[
                "4:::ARaVEoRalHjf9hIFnYJb2O9I6BJeHNoonwkB...."
             ]
          }
       },
       {
          "type":"BODY",
          "text":"Please find media attached as requested."
       }
    ],
    "language":"en_US",
    "category":"TRANSACTIONAL"
 }

要求

var responseContent = string.empty;

using (var httpClient = new HttpClient())
{
    using (var request = new HttpRequestMessage(new HttpMethod("POST"), $"https://graph.facebook.com/v14.0/{_businessAccountID}/message_templates"))
    {
        request.Headers.TryAddWithoutValidation("Authorization", "Bearer " + _accessToken);

        request.Content = new StringContent(jsonData);
        request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");

        var response = await httpClient.SendAsync(request);
        if (!response.IsSuccessStatusCode)
            return null;

        responseContent = response.Content.ReadAsStringAsync().Result;
    }
}

【讨论】:

    猜你喜欢
    • 2022-07-13
    • 2022-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-01
    • 1970-01-01
    • 2014-03-26
    相关资源
    最近更新 更多