Google上的操作-C#中的推送通知

时间:2018-09-28 21:24:34

标签: push-notification actions-on-google

我正在尝试将基本的推送通知发送到我的操作。

我正在获取访问令牌

    private static async Task<string> GetAccessTokenFromJsonKeyAsync(string jsonKeyFilePath, params string[] scopes)
    {
        using (var stream = new FileStream(jsonKeyFilePath, FileMode.Open, FileAccess.Read))
        {
            return await GoogleCredential
                .FromStream(stream) // Loads key file  
                .CreateScoped(scopes) // Gathers scopes requested  
                .UnderlyingCredential // Gets the credentials  
                .GetAccessTokenForRequestAsync(); // Gets the Access Token  
        }
    }

返回我的访问令牌。

然后我将发送以下通知消息

{
    "customPushMessage": {
        "userNotification":{
            "title":"Notification Title"
        },
        "target":{
             "userId":"ID_FROM_UPDATES_USER_ID",
             "intent":"Notification Intent",
             "locale":"en-US"
        }
    }
}

使用以下代码

        try
        {
            var accessToken = await GetAccessTokenFromJsonKeyAsync("key.json", "https://www.googleapis.com/auth/actions.fulfillment.conversation");

            var serialized = JsonConvert.SerializeObject(proactiveMessage);
            var payload = "{\"customPushMessage\": " + serialized + "}";

            // Wrap our JSON inside a StringContent which then can be used by the HttpClient class
            var httpContent = new StringContent(payload, Encoding.UTF8, "application/json");

            _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", accessToken);

            var httpResponseMessage = await _httpClient.PostAsync("https://actions.googleapis.com/v2/conversations:send", httpContent);

            Debug.WriteLine(httpResponseMessage.IsSuccessStatusCode ? "Successfully sent notification message." : $"Failed to send notification message with {httpResponseMessage.StatusCode}.");

            return httpResponseMessage;
        }
        catch (Exception ex)
        {
            Debug.WriteLine($"Alexa API Service: Failed to send notification message with exception: {ex.Message}");
            return new HttpResponseMessage(HttpStatusCode.BadRequest);
        }

我得到的响应代码是403 Forbidden。

我不确定访问令牌代码是否错误,通知结构是否错误或是否缺少其他内容。

2 个答案:

答案 0 :(得分:2)

令牌类型必须为国会大厦B的“承载者”。因此该行应为

_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

答案 1 :(得分:0)

我没有适当地请求许可。This为我提供了难题的一部分。

需要

        "updatePermission": {
            "intent": "notification.simple.text"
        }