我在使用 PayPal API 创建计费计划和处理订阅时遇到身份验证失败问题。这是我收到的错误消息:
{"name":"AUTHENTICATION_FAILURE","message":"Authentication failed due to invalid authentication credentials or a missing Authorization header.","links":[{"href":"https://developer.paypal.com/docs/api/overview/#error","rel":"information_link"}]}
尝试访问 URL 时会出现此错误
https://api.sandbox.paypal.com/v1/payments/billing-plans/P-0N9306909M1752927SPMWBYI.
下面是我的代码:
PAYPAL_CLIENT_ID = os.environ.get('PAYPAL_CLIENT_ID')
PAYPAL_CLIENT_SECRET = os.environ.get('PAYPAL_CLIENT_SECRET')
import paypalrestsdk
def create_billing_plan(name, description, type, frequency, frequency_interval, cycles, amount, credits_to_add, credits_price):
try:
paypalrestsdk.configure({
'mode': 'sandbox', # Change to 'live' for production
'client_id': PAYPAL_CLIENT_ID,
'client_secret': PAYPAL_CLIENT_SECRET
})
billing_plan_attributes = {
"name": name,
"description": description,
"type": type,
"payment_definitions": [{
"name": "Regular Payment",
"type": "REGULAR",
"frequency": frequency,
"frequency_interval": frequency_interval,
"cycles": cycles,
"amount": {
"value": amount,
"currency": "USD"
}
}],
"merchant_preferences": {
"auto_bill_amount": "yes",
"cancel_url": url_for('payment_cancel', _external=True),
"return_url": url_for('payment_success', _external=True)
}
}
billing_plan = paypalrestsdk.BillingPlan(billing_plan_attributes)
if billing_plan.create():
approval_urls = [link.href for link in billing_plan.links if link.rel == 'approval_url']
if approval_urls:
return approval_urls[0]
else:
self_urls = [link.href for link in billing_plan.links if link.rel == 'self']
if self_urls:
return self_urls[0]
else:
print('Failed to retrieve payment redirect URL.')
print('Billing Plan Links:', billing_plan.links)
return None
else:
error_message = f"Failed to create billing plan: {billing_plan.error}"
print(error_message)
print('Billing Plan Response:', billing_plan.to_dict())
return None
except paypalrestsdk.exceptions.UnauthorizedAccess as e:
print(f"Authentication failed: {e}")
flash('Failed to authenticate with PayPal.', 'danger')
return None
@app.route('/purchase', methods=['POST'])
@login_required
def purchase_subscription():
plan = request.form.get('plan')
selected_gateway = request.form.get('payment_gateway')
plan_settings = get_plan_settings()
if not plan_settings:
flash('Failed to fetch plan settings from the database.', 'danger')
return redirect(url_for('subscription'))
credits_to_add = 0
credits_price = 0
subscription_type = None
subscription_start_date = None
subscription_end_date = None
subscription_type_mapping = {
'plan1': 'monthly',
'plan2': 'monthly',
'plan3': 'monthly',
'plan4': 'yearly',
'plan5': 'yearly',
'plan6': 'yearly'
}
if plan in subscription_type_mapping:
subscription_type = subscription_type_mapping[plan]
if subscription_type == 'monthly':
frequency = "MONTH"
elif subscription_type == 'yearly':
frequency = "YEAR"
credits_to_add = plan_settings[plan + "_credits"]
credits_price = plan_settings[plan + "_price"]
else:
flash('Invalid plan selected.', 'danger')
return redirect(url_for('subscription'))
redirect_url = create_billing_plan(
name=f"{plan.capitalize()} Subscription",
description=f"{plan.capitalize()} Subscription",
type="INFINITE",
frequency=frequency,
frequency_interval="1",
cycles="0",
amount=str(credits_price),
credits_to_add=credits_to_add,
credits_price=credits_price
)
if redirect_url:
return redirect(redirect_url) # Redirect user to PayPal
else:
flash('Failed to initiate payment.', 'danger')
return redirect(url_for('subscription'))
尽管使用正确的客户端 ID 和客户端密码配置 PayPal SDK,但我仍然遇到身份验证失败的情况。
任何有关如何排查和解决此问题的见解或建议将不胜感激。
谢谢!
/v1/付款/计费计划已长期弃用,不应用于任何新的 PayPal 集成
请参阅订阅概述了解当前集成。
在撰写本文时,所有服务器端 PayPal SDK 均已弃用,不应使用任何 SDK。使用直接HTTPS API调用首先获取access_token,然后发送请求并读取JSON格式的响应。