我正在尝试将OAuth 1.0用于FatSecret API。
我试图生成oauth_signature,但是它不起作用。
我在python上实现它。我合并了StackOverflow的许多代码,但仍然无法正常工作。
这是我使用的图书馆:
import requests
import time
from urllib import quote_plus as rawurlencode
import string
import random
import operator
这是随机数的id_generator:
def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
这是为了生成签名:
def _hmac_sha1(input_str, input_key):
from hashlib import sha1
import hmac
key = b""+input_key+b"&"
raw = b""+input_str
hashed = hmac.new(key, raw, sha1)
return hashed.digest().encode("base64").rstrip('\n')
这是代码:
key = 'xxxxx'
secret = 'xxxxxx'
oauth_signature_method = "HMAC-SHA1"
oauth_timestamp = str(int(time.time()))
oauth_nonce = id_generator(8)
oauth_version = "1.0"
url = 'http://platform.fatsecret.com/rest/server.api?method=food.get&food_id=1678'
params = {
'oauth_consumer_key': key,
'oauth_nonce': oauth_nonce,
'oauth_signature_method': oauth_signature_method,
'oauth_timestamp': oauth_timestamp,
'oauth_token': '',
'oauth_version': oauth_version
}
baseString = "POST&" + rawurlencode(url) + "&"
sorted_paramDict = sorted(params.items(), key=operator.itemgetter(0))
paramStr = ''
for kv in sorted_paramDict:
paramStr = paramStr + kv[0] + "=" + kv[1] + "&"
paramStr = paramStr[:-1]
baseString = baseString + rawurlencode(paramStr)
oauth_signature = _hmac_sha1(baseString, key)
paramsSIGN = {
'oauth_consumer_key': key,
'oauth_signature_method': oauth_signature_method,
'oauth_timestamp': oauth_timestamp,
'oauth_nonce': oauth_nonce,
'oauth_version': oauth_version,
'oauth_signature': oauth_signature
}
r = requests.post(url, params=paramsSIGN)
print r.content
结果是:
<?xml version="1.0" encoding="utf-8" ?>
<error xmlns="http://platform.fatsecret.com/api/1.0/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://platform.fatsecret.com/api/1.0/ http://platform.fatsecret.com/api/1.0/fatsecret.xsd">
<code>8</code>
<message>Invalid signature: oauth_signature 'PyhuSZB9iIIqxzuT/zhH37EGxkc='</message>
</error>
我不知道为什么它不起作用