You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask对接PayPal权限服务:提取重定向URL中验证参数的方法

回调参数获取方案与代码优化建议

首先,针对你需要获取回调URL中request_token和verification_code的需求,我们先实现对应的Flask路由来捕获这两个参数,并完成GetAccessToken API的调用:

@account.route('/access_token')
def get_access_token():
    # 从回调URL的查询参数中提取所需值
    request_token = request.args.get('request_token')
    verification_code = request.args.get('verification_code')
    
    # 先校验参数是否完整
    if not request_token or not verification_code:
        return render_template('account.html', response='授权回调缺少必要参数')
    
    # 调用PayPal的GetAccessToken接口
    url = "https://svcs.sandbox.paypal.com/Permissions/GetAccessToken"
    headers = {
        'X-PAYPAL-SECURITY-USERID': '**********',
        'X-PAYPAL-SECURITY-PASSWORD': '*********',
        'X-PAYPAL-SECURITY-SIGNATURE': '************',
        'X-PAYPAL-REQUEST-DATA-FORMAT': 'JSON',
        'X-PAYPAL-RESPONSE-DATA-FORMAT': 'JSON',
        'X-PAYPAL-APPLICATION-ID': 'APP-80W284485P519543T'
    }
    payload = {
        'token': request_token,
        'verificationCode': verification_code,
        'requestEnvelope': {
            'errorLanguage': 'en_US'
        }
    }
    
    try:
        res = requests.post(url, data=json.dumps(payload), headers=headers)
        res.raise_for_status()  # 主动触发HTTP错误异常
        res_json = res.json()
        
        if res_json['responseEnvelope']['ack'] == 'Success':
            # 拿到授权后的access_token和token_secret,可存入session或数据库
            access_token = res_json['token']
            token_secret = res_json['tokenSecret']
            return render_template('account.html', response='授权成功!已获取访问令牌')
        else:
            # 提取PayPal返回的具体错误信息
            error_msg = res_json.get('error', [{}])[0].get('message', '授权失败')
            return render_template('account.html', response=f'授权失败:{error_msg}')
    except requests.exceptions.RequestException as e:
        return render_template('account.html', response=f'请求PayPal接口出错:{str(e)}')

接下来是对你现有get_request_token函数的优化建议,结合Python新手的学习场景,从规范、安全性和健壮性三个维度调整:

  • 敏感信息抽离,避免硬编码
    把PayPal的安全凭证放到环境变量中,防止代码泄露敏感信息。可以用python-dotenv库加载本地.env文件:

    import os
    from dotenv import load_dotenv
    
    load_dotenv()  # 加载根目录的.env文件
    
    headers = {
        'X-PAYPAL-SECURITY-USERID': os.getenv('PAYPAL_USERID'),
        'X-PAYPAL-SECURITY-PASSWORD': os.getenv('PAYPAL_PASSWORD'),
        'X-PAYPAL-SECURITY-SIGNATURE': os.getenv('PAYPAL_SIGNATURE'),
        'X-PAYPAL-REQUEST-DATA-FORMAT': 'JSON',
        'X-PAYPAL-RESPONSE-DATA-FORMAT': 'JSON',
        'X-PAYPAL-APPLICATION-ID': os.getenv('PAYPAL_APP_ID')
    }
    
  • 修复Payload拼写错误
    你代码中request_Envelop是拼写错误,PayPal API要求的是requestEnvelope(驼峰命名无下划线),不修正可能导致接口返回异常。

  • 简化路由方法判断
    直接在路由装饰器中指定请求方法,不用在函数内重复判断:

    @account.route('/grant_auth', methods=['GET'])
    def get_request_token():
        # 去掉原有if request.method == 'GET'的判断
        ...
    
  • 增加异常处理,提升健壮性
    给网络请求和JSON解析添加异常捕获,避免因网络波动、API返回格式异常导致程序崩溃:

    try:
        res_details = requests.post(url, data=json.dumps(payload), headers=headers)
        res_details.raise_for_status()  # 捕获4xx/5xx的HTTP错误
        res_json_format = res_details.json()
    except requests.exceptions.RequestException as e:
        return render_template('account.html', response=f'请求PayPal失败:{str(e)}')
    except ValueError:
        return render_template('account.html', response='解析PayPal响应数据失败')
    
  • 简化分支逻辑
    不用将ack转成字符串再判断,直接比较即可,同时合并失败分支并提取具体错误信息:

    ack_status = res_json_format['responseEnvelope']['ack']
    if ack_status == 'Success':
        token = res_json_format['token']
        pal_permission_url = f'https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_grant-permission&request_token={token}'
        return redirect(pal_permission_url)
    else:
        error_msg = res_json_format.get('error', [{}])[0].get('message', '未知错误')
        return render_template('account.html', response=f'申请请求令牌失败:{error_msg}')
    

作为Python新手,额外给你两个小建议:

  • 多熟悉Flask的request对象用法,区分args(GET查询参数)和form(POST表单参数)的适用场景
  • 养成写规范docstring的习惯,方便后续自己维护代码

内容的提问来源于stack exchange,提问作者Seal_Seal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:29:37