Twitter Direct Message返回401未经授权

时间:2018-10-05 09:36:40

标签: c# rest twitter twitter-oauth

我已遵循以下Twitter文档,以通过API在Twitter中发送直接消息。 https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-event

以下是代码正在使用

        string oauthconsumerkey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        string oauthconsumersecret = "YYYYYYYYYYYYYYYYYYYYYYYYYY";
        string oauthtokensecret = string.Empty;
        string oauthtoken = string.Empty;
        string oauthsignaturemethod = "HMAC-SHA1";
        string oauthversion = "1.0";
        string oauthnonce = Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
        TimeSpan timeSpan = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
        string oauthtimestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();
        string url = "https://api.twitter.com/1.1/direct_messages/events/new.json";
        SortedDictionary<string, string> basestringParameters = new SortedDictionary<string, string>();
        basestringParameters.Add("oauth_version", oauthversion);
        basestringParameters.Add("oauth_consumer_key", oauthconsumerkey);
        basestringParameters.Add("oauth_nonce", oauthnonce);
        basestringParameters.Add("oauth_signature_method", oauthsignaturemethod);
        basestringParameters.Add("oauth_timestamp", oauthtimestamp);
        basestringParameters.Add("oauth_token", [AccessToken........]);

        string baseString = String.Empty;
        baseString += "POST" + "&";
        baseString += Uri.EscapeDataString(url.Split('?')[0]) + "&";
        foreach (KeyValuePair<string, string> entry in basestringParameters)
        {
            baseString += Uri.EscapeDataString(entry.Key + "=" + entry.Value + "&");
        }

        //Remove the trailing ambersand char last 3 chars - %26
        baseString = baseString.Substring(0, baseString.Length - 3);

        //Build the signing key
        string signingKey = Uri.EscapeDataString(oauthconsumersecret) +
          "&" + Uri.EscapeDataString(oauthtokensecret);

        //Sign the request
        HMACSHA1 hasher = new HMACSHA1(new ASCIIEncoding().GetBytes(signingKey));
        string oauthsignature = Convert.ToBase64String(
          hasher.ComputeHash(new ASCIIEncoding().GetBytes(baseString)));

        //Tell Twitter we don't do the 100 continue thing
        ServicePointManager.Expect100Continue = false;
        HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(@url);

        StringBuilder authorizationHeaderParams = new StringBuilder();
        authorizationHeaderParams.Append("OAuth ");
        authorizationHeaderParams.Append("oauth_consumer_key=" + "\"" + Uri.EscapeDataString(oauthconsumerkey) + "\",");
        authorizationHeaderParams.Append("oauth_nonce=" + "\"" + Uri.EscapeDataString(oauthnonce) + "\",");
        authorizationHeaderParams.Append("oauth_signature=" + "\"" + Uri.EscapeDataString(oauthsignature) + "\",");
        authorizationHeaderParams.Append("oauth_signature_method=" + "\"" + Uri.EscapeDataString(oauthsignaturemethod) + "\",");
        authorizationHeaderParams.Append("oauth_timestamp=" + "\"" + Uri.EscapeDataString(oauthtimestamp) + "\",");
        authorizationHeaderParams.Append("oauth_token=" + "\"" + Uri.EscapeDataString([AccessToken........]) + "\",");
        authorizationHeaderParams.Append("oauth_version=" + "\"" + Uri.EscapeDataString(oauthversion) + "\"");
        webRequest.Headers.Add("Authorization", authorizationHeaderParams.ToString());

        webRequest.Method = "POST";
        webRequest.ContentType = "application/json";
        //Allow us a reasonable timeout in case Twitter's busy
        webRequest.Timeout = 3 * 60 * 1000;

        try
        {

            string PostData = "{ \"event\": { \"type\": \"message_create\", \"message_create\": { \"target\": { \"recipient_id\": \"193301701\"}, \"message_data\": { \"text\": \"Hello World!\"} } } }";
            //"{\"event\": {\"type\": \"message_create\", \"message_create\": {\"target\": {\"recipient_id\": "+recipient_id+"},\"message_data\": {\"text\": " + Message+"}}}}";
            if (!string.IsNullOrEmpty(PostData))
            {
                System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
                byte[] data = encoding.GetBytes(PostData);
                webRequest.ContentLength = data.Length;
                using (System.IO.Stream stream = webRequest.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }
            HttpWebResponse webResponse = webRequest.GetResponse() as HttpWebResponse;
            System.IO.Stream dataStream = webResponse.GetResponseStream();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream);
            // Read the content.
            string responseFromServer = reader.ReadToEnd();
        }
        catch (Exception ex)
        {
            throw ex;
        }

但是总是出现401 Unauthorized错误,响应如下:

{
    "errors": [
        {
            "code": 32,
            "message": "Could not authenticate you."
        }
    ]
}

我已经从开发者帐户检查了应用程序权限

  

直接消息权限适用于生成的使用者密钥

0 个答案:

没有答案