Line Notify - 取得Access Token

透過使用者綁定取得code後,要再拿code去取access token。

直接看程式

//在使用者綁定拿到的code
string code = "";
//註冊Notify服務時填的Callback URL
string redirectUri = "";
//註冊Notify服務後拿到的Client ID
string clientId = "";
//註冊Notify服務後拿到的Client Secret
string clientSecret = "";

using (HttpClient httpClient = _httpClientFactory.CreateClient())
{
    var content = new FormUrlEncodedContent(new[]
    {
                new KeyValuePair<string, string>("grant_type", "authorization_code"),
                new KeyValuePair<string, string>("code", code),
                new KeyValuePair<string, string>("redirect_uri", redirectUri),
                new KeyValuePair<string, string>("client_id", clientId),
                new KeyValuePair<string, string>("client_secret", clientSecret)
            });

    var respond = await httpClient.PostAsync(new Uri("https://notify-bot.line.me/oauth/token"), content);

    if (respond.IsSuccessStatusCode)
    {
        var result = JsonConvert.DeserializeObject<JObject>(await respond.Content.ReadAsStringAsync());

        if (result["status"].Value<string>() == "200")
        {
            var token = result["access_token"].Value<string>();
        }
        else
        {
            throw new Exception($"取得token時發生錯誤:{result["message"].Value<string>()}");
        }
    }
    else
    {
        throw new Exception($"取得token時發生錯誤,Http code:{respond.StatusCode} {respond.Content.ReadAsStringAsync().Result}");
    }
}

拿到Access Token後,就能用這組token來傳送通知了。

參考資料: