【问题标题】:Looking for example Python code for Netsuite API using OAuth?正在寻找使用 OAuth 的 Netsuite API 的 Python 代码示例?
【发布时间】:2016-01-15 10:11:25
【问题描述】:

Netsuite 的文档未提供。有没有人写过可以帮助我生成有效签名的代码。

【问题讨论】:

标签: python oauth netsuite


【解决方案1】:

NetSuite 套件解答网站中有一些示例代码,但您必须登录才能访问它。

https://netsuite.custhelp.com/app/answers/detail/a_id/42165/kw/42165

这是我能够工作的答案中的代码。唯一的区别是他们的代码通过尝试将时间戳编码为 int 来破坏。我将它类型转换为 str 并且编码工作正常。密钥/令牌/领域来自他们的演示代码。插入你自己的,你应该很高兴。

import oauth2 as oauth
import requests
import time

url = "https://rest.netsuite.com/app/site/hosting/restlet.nl?script=992&deploy=1"
token = oauth.Token(key="080eefeb395df81902e18305540a97b5b3524b251772adf769f06e6f0d9dfde5", secret="451f28d17127a3dd427898c6b75546d30b5bd8c8d7e73e23028c497221196ae2")
consumer = oauth.Consumer(key="504ee7703e1871f22180441563ad9f01f3f18d67ecda580b0fae764ed7c4fd38", secret="b36d202caf62f889fbd8c306e633a5a1105c3767ba8fc15f2c8246c5f11e500c")

http_method = "GET"  
realm="ACCT123456"

params = {
    'oauth_version': "1.0",
    'oauth_nonce': oauth.generate_nonce(),
    'oauth_timestamp': str(int(time.time())),
    'oauth_token': token.key,
    'oauth_consumer_key': consumer.key
}

req = oauth.Request(method=http_method, url=url, parameters=params)
signature_method = oauth.SignatureMethod_HMAC_SHA1()
req.sign_request(signature_method, consumer, token)
header = req.to_header(realm)
headery = header['Authorization'].encode('ascii', 'ignore')
headerx = {"Authorization": headery, "Content-Type":"application/json"}
print(headerx)
conn = requests.get("https://rest.netsuite.com/app/site/hosting/restlet.nl?script=992&deploy=1",headers=headerx)
print(conn.text)

【讨论】:

  • 这种使用 OAuth 的方法不再有效。 Netsuite 需要 SHA256 签名。 SHA1 已弃用。
  • 嗨@PeterAndreoli,考虑到库 oauth 不允许 OAuth2.0,为 NetSuite 连接实现 OAuth2.0 的更好选择是什么?
  • 不幸的是,我现在没有答案。我将很快更新我们的集成,所以希望我能带着解决方案回到这里。
  • @PeterAndreoli 你有什么更新吗?
  • @LimyandiVicoTrico 你现在提出这个很有趣。我的修复只是被推到了prod!你可以在这里找到我的解决方案github.com/pietro-andreoli/python-oauth2-additions。本质上,我扩展了SignatureMethod_HMAC_SHA1 类的基类,以便为SHA256 制作我自己的实现。不能保证是一个完美的解决方案,但我已经为此工作了一段时间。如果有任何变化会更新。
【解决方案2】:

仅供参考,我最近在 Python3 中使用 requests_oauthlib 进行了此操作,它与库的标准使用一起使用:

from requests_oauthlib import OAuth1Session
import json

url = 'https://xxx.restlets.api.netsuite.com/app/site/hosting/restlet.nl?script=xxx&deploy=xxx'

oauth = OAuth1Session(
    client_key='xxx',
    client_secret='xxx',
    resource_owner_key='xxx',
    resource_owner_secret='xxx',
    realm='xxx')

payload = dict(...)
resp = oauth.post(
    url,
    headers={'Content-Type': 'application/json'},
    data=json.dumps(payload),
)

print(resp)

【讨论】:

  • 我认为大多数新集成的人都需要将signature_method='HMAC-SHA256', 添加到 OAuth1Session 选项中。除此之外,你是完全正确的!非常感谢,我几乎放弃了图书馆,我只花了一点时间就弄清楚了 256 的事情。
【解决方案3】:

在 NetSuite 的原始示例代码的基础上,我能够使用 SHA256 获得以下内容,我认为您可以为 SHA512 做类似的事情。

import binascii
import hmac
import time
from hashlib import sha256

import oauth2 as oauth
import requests

url = "https://<account>.restlets.api.netsuite.com/app/site/hosting/restlet.nl?script=<scriptId>&deploy=1"
token = oauth.Token(key="080eefeb395df81902e18305540a97b5b3524b251772adf769f06e6f0d9dfde5",
                    secret="451f28d17127a3dd427898c6b75546d30b5bd8c8d7e73e23028c497221196ae2")
consumer = oauth.Consumer(key="504ee7703e1871f22180441563ad9f01f3f18d67ecda580b0fae764ed7c4fd38",
                          secret="b36d202caf62f889fbd8c306e633a5a1105c3767ba8fc15f2c8246c5f11e500c")

http_method = "POST"
realm = "CCT123456"

params = {
    'oauth_version': "1.0",
    'oauth_nonce': oauth.generate_nonce(),
    'oauth_timestamp': str(int(time.time())),
    'oauth_token': token.key,
    'oauth_consumer_key': consumer.key
}


class SignatureMethod_HMAC_SHA256(oauth.SignatureMethod):
    name = 'HMAC-SHA256'

    def signing_base(self, request, consumer, token):
        if (not hasattr(request, 'normalized_url') or request.normalized_url is None):
            raise ValueError("Base URL for request is not set.")

        sig = (
            oauth.escape(request.method),
            oauth.escape(request.normalized_url),
            oauth.escape(request.get_normalized_parameters()),
        )

        key = '%s&' % oauth.escape(consumer.secret)
        if token:
            key += oauth.escape(token.secret)
        raw = '&'.join(sig)
        return key.encode('ascii'), raw.encode('ascii')

    def sign(self, request, consumer, token):
        """Builds the base signature string."""
        key, raw = self.signing_base(request, consumer, token)

        hashed = hmac.new(key, raw, sha256)

        # Calculate the digest base 64.
        return binascii.b2a_base64(hashed.digest())[:-1]


req = oauth.Request(method=http_method, url=url, parameters=params)
oauth.SignatureMethod_HMAC_SHA256 = SignatureMethod_HMAC_SHA256
signature_method = oauth.SignatureMethod_HMAC_SHA256()
req.sign_request(signature_method, consumer, token)
header = req.to_header(realm)
header_y = header['Authorization'].encode('ascii', 'ignore')
header_x = {"Authorization": header_y, "Content-Type": "application/json"}
print(header_x)
response = requests.request("POST", url, data={}, headers=header_x)
# conn = requests.post(url, headers=headerx)
print(response.text)

【讨论】:

    猜你喜欢
    • 2010-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 2011-06-22
    • 1970-01-01
    • 1970-01-01
    • 2018-06-30
    相关资源
    最近更新 更多