在Django中使用Python Paypal REST SDK动态获取付款和付款人ID

3 投票
2 回答
3123 浏览
提问于 2025-04-17 21:36

我刚开始学习django和python。现在我正在开发一个网站,使用Paypal来处理交易。我已经成功地把python的Paypal REST SDK集成到我的项目中。下面是我的views.py文件,里面有这个集成的代码。

def subscribe_plan(request):

    exact_plan = Plan.objects.get(id = request.POST['subscribe'])
    exact_validity = exact_plan.validity_period
    exp_date = datetime.datetime.now()+datetime.timedelta(exact_validity)
    plan = Plan.objects.get(id = request.POST['subscribe'])
    subs_plan = SubscribePlan(plan = plan,user = request.user,expiriary_date = exp_date)
    subs_plan.save()




    logging.basicConfig(level=logging.INFO)

    paypalrestsdk.configure({
      "mode": "sandbox", # sandbox or live
      "client_id": "AQkquBDf1zctJOWGKWUEtKXm6qVhueUEMvXO_-MCI4DQQ4-LWvkDLIN2fGsd",
      "client_secret": "EL1tVxAjhT7cJimnz5-Nsx9k2reTKSVfErNQF-CmrwJgxRtylkGTKlU4RvrX" })

    payment = Payment({
        "intent":  "sale",
        # ###Payer
        # A resource representing a Payer that funds a payment
        # Payment Method as 'paypal'
        "payer":  {                                              
        "payment_method":  "paypal" },
        # ###Redirect URLs
        "redirect_urls": {
        "return_url": "www.mydomain.com/execute",
        "cancel_url": "www.mydomain.com/cancel" },
        # ###Transaction
        # A transaction defines the contract of a
        # payment - what is the payment for and who
        # is fulfilling it.
        "transactions":  [ {
        # ### ItemList
        "item_list": {
            "items": [{
                "name": exact_plan.plan,
                "sku": "item",
                "price": "5.00",
                "currency": "USD",
                "quantity": 1 }]},
        "amount":  {
              "total":  "5.00",
              "currency":  "USD" },
        "description":  "This is the payment transaction description." } ] }   )




selected_plan = request.POST['subscribe']
context = RequestContext(request)

if payment.create():

    print("Payment %s created successfully"%payment.id)

    for link in payment.links:#Payer that funds a payment
        if link.method=="REDIRECT":
            redirect_url=link.href
            ctx_dict = {'selected_plan':selected_plan,"payment":payment}
            print("Redirect for approval: %s"%redirect_url)
            return redirect(redirect_url,context)
else:                             
    print("Error %s"%payment.error)
    ctx_dict = {'selected_plan':selected_plan,"payment":payment}
    return render_to_response('photo/fail.html',ctx_dict,context)

在这个支付字典里,www.mydomain.com/execute被设置为返回的地址,而www.mydomain.com/cancel则是取消的地址。为了处理这两个地址,我需要再写一个视图,下面是这个视图的代码。

def payment_execute(request):
logging.basicConfig(level=logging.INFO)

# ID of the payment. This ID is provided when creating payment.
payment = paypalrestsdk.Payment.find("PAY-57363176S1057143SKE2HO3A")
ctx = {'payment':payment}
context = RequestContext(request)

# PayerID is required to approve the payment.
if payment.execute({"payer_id": "DUFRQ8GWYMJXC" }):  # return True or False
  print("Payment[%s] execute successfully"%(payment.id))
  return render_to_response('photo/execute.html',ctx,context)


else:
  print(payment.error)
  return render_to_response('photo/dismiss.html',ctx,context)

在这个payment_execute视图里,我使用了固定的支付ID和固定的付款人ID。通过这个固定的支付ID和付款人ID,我成功完成了一次Paypal的支付。但是,这个支付ID付款人ID应该是动态的。我该如何在payment_execute视图中动态设置支付ID付款人ID呢?我已经在用户会话中保存了支付ID(在我的subscribe_plan视图里),而我知道付款人ID是在返回地址中提供的,但由于我知识有限,不知道该如何获取它们。我该怎么做呢?

2 个回答

0

根据Avi Das的回答,我成功地用POST请求获取了这些信息,而不是用GET请求:

class PaypalExecutePayment:

    def __call__(self, request):
        payer_id = request.POST.get("payerID")
        payment_id = request.POST.get("paymentID")

        payment = paypalrestsdk.Payment.find(payment_id)

        if payment.execute({"payer_id": payer_id}):
            print("Payment execute successfully")
        else:
            print(payment.error)  # Error Hash

将这个类连接到我的API:

from django.views.decorators.csrf import csrf_exempt

urlpatterns = [
    ...
    url('^api/execute-payment/', csrf_exempt(views.PaypalExecutePayment())),
    ... 
]
2
  1. 支付 ID:在订阅视图中,保存支付 ID。

    你可以这样做:将支付的 ID 存到会话中:

    request.session["payment_id"] = payment.id

    然后在支付执行视图中,获取这个支付 ID:

    payment_id = request.session["payment_id"]

    接着,你可以用这个 ID 找到支付信息:

    payment = paypalrestsdk.Payment.find(payment_id)

  2. 付款人 ID:

    看起来你已经知道付款人 ID 是在返回的 URL 中提供的一个参数。在你的支付执行视图中,你可以这样获取付款人 ID:

    request.GET.get("PayerID")

以下链接可以帮助你更深入地了解和尝试:

https://devtools-paypal.com/guide/pay_paypal/python?interactive=ON&env=sandbox

https://developer.paypal.com/webapps/developer/docs/integration/web/accept-paypal-payment/

撰写回答