Digikey OAuth2 API接入问题:Windows应用零件搜索代码报错求助
问题排查与环境说明
一、代码中的核心问题
1. OAuth2授权码流程实现错误
授权码流程需要用户手动完成登录授权操作,直接通过requests.get访问authorize接口只会返回登录页面响应,不会自动携带授权码。你当前代码直接拆分auth_response.url获取code必然失败,因为该URL是登录页地址,不存在code=参数。
正确逻辑:
- 引导用户打开
authorize接口的URL,完成登录授权后,用户会被重定向到你设置的redirect_uri,此时重定向URL中才会包含code参数。 - 需要搭建本地服务监听
redirect_uri对应的端口(如8139),接收重定向请求来提取code。
2. 沙箱与生产环境混用
你获取授权码用的是沙箱环境域名sandbox-api.digikey.com,但获取Token和搜索接口用的是生产环境域名api.digikey.com。两者的凭证(client_id/secret)不通用,必须统一使用同一环境的域名和对应凭证。
3. Access Token传递方式错误
Digikey API要求将Access Token放在请求头的Authorization字段中,格式为Bearer <access_token>,而非作为URL参数传递。
4. 缺少必要请求头
调用API时需添加Accept、Content-Type等请求头,否则可能被拒绝访问。
二、修正后的示例代码
import requests from flask import Flask, request app = Flask(__name__) client_id = '<你的沙箱或生产环境client_id>' client_secret = '<你的沙箱或生产环境client_secret>' redirect_uri = 'https://localhost:8139/digikey_callback' # 统一环境:沙箱用sandbox-api.digikey.com,生产用api.digikey.com base_url = 'https://sandbox-api.digikey.com' @app.route('/digikey_callback') def callback(): # 从重定向请求中提取授权码 auth_code = request.args.get('code') if not auth_code: return "授权失败" # 获取Token token_response = requests.post(f'{base_url}/v1/oauth2/token', data={ 'client_id': client_id, 'client_secret': client_secret, 'redirect_uri': redirect_uri, 'code': auth_code, 'grant_type': 'authorization_code' }, headers={ 'Content-Type': 'application/x-www-form-urlencoded' }) if token_response.status_code != 200: return f"获取Token失败: {token_response.text}" access_token = token_response.json()['access_token'] # 搜索零件 search_response = requests.get(f'{base_url}/v1/products/search', params={'keywords': 'screw'}, headers={ 'Authorization': f'Bearer {access_token}', 'Accept': 'application/json' }) print(search_response.json()) return "搜索完成,结果已打印到控制台" if __name__ == '__main__': # 打印授权URL,引导用户访问 auth_url = f"{base_url}/v1/oauth2/authorize?client_id={client_id}&redirect_uri={redirect_uri}&response_type=code" print(f"请访问以下URL完成授权: {auth_url}") # 启动本地服务监听端口,https需要临时SSL证书 app.run(port=8139, ssl_context='adhoc')
三、沙箱与生产环境的差异
- 用途区分:沙箱是测试环境,提供模拟零件数据,所有操作无真实订单或费用,适合开发调试;生产环境使用真实Digikey数据,用于正式业务。
- 凭证独立:沙箱和生产环境的client_id、client_secret需分别申请,不可交叉使用。
- 接口域名不同:沙箱环境接口域名以
sandbox-api.digikey.com开头,生产环境以api.digikey.com开头,所有接口调用必须匹配对应环境域名。 - 数据范围:沙箱环境的零件数据为模拟数据,品类或型号覆盖不全;生产环境包含Digikey全量真实库存和产品信息。
内容的提问来源于stack exchange,提问作者PyCode
相关产品推荐
相关产品推荐

