我尝试使用Twitter Oauth登录我的应用程序(Web)
import requests
import random
import time
import hashlib
import hmac
import urllib
import base64
CONSUMER_KEY = "TestKey"
CONSUMER_SECRET = "TestSecret"
REQUEST_TOKEN_URL = "https://api.twitter.com/oauth/request_token"
CALLBACK_URL = "https://www.example.com/cgi-bin/twittercallback"
def urlencode(s):
return urllib.parse.quote(s, safe='')
def request_token(url, method):
params = dict()
params['oauth_callback'] = CALLBACK_URL
params['oauth_consumer_key'] = CONSUMER_KEY
params['oauth_nonce'] = str(random.getrandbits(64))
params['oauth_signature_method'] = 'HMAC-SHA1'
params['oauth_timestamp'] = str(int(time.time()))
params['oauth_version'] = '1.0'
keys = sorted(list(params.keys()))
enc_params = urlencode('&'.join(['%s=%s' % (urlencode(key), urlencode(params[key])) for key in keys]))
base_string = '%s&%s&%s' % (method.upper(), urlencode(url), enc_params)
key = CONSUMER_SECRET + '&'
params['oauth_signature'] = base64.standard_b64encode(
hmac.new(key.encode(), base_string.encode(), hashlib.sha1).digest()).decode('ascii')
keys = sorted(list(params.keys()))
authorize = 'OAuth ' + ', '.join('%s="%s"' % (key, urlencode(params[key])) for key in keys)
ret = requests.post(url, headers={'Authorization': authorize})
print(ret, ret.text)
if __name__ == '__main__':
request_token(REQUEST_TOKEN_URL, 'POST')
我尝试了很多次但也失败了,错误信息是
{"errors":[{"code":32,"message":"Could not authenticate you."}]}
我的代码有什么问题?
答案 0 :(得分:1)
我重新生成了消费者API密钥,我的应用程序可以正常工作