如何在 Python 中从 PayPal 捕获订单

问题描述

我一直试图了解 PayPal SDK 的捕获过程究竟是如何工作的。我目前正在开发带有 PayPal Checkout 选项的 Python Kivy 移动应用程序。我一直试图让这个例子在这里工作:https://github.com/paypal/Checkout-Python-SDK#capturing-an-order but 在执行时得到这个错误

422
{'Cache-Control': 'max-age=0,no-cache,no-store,must-revalidate','Content-Length': '584','Content-Type': 'application/json','Date': 'Thu,04 Mar 2021 18:32:56 GMT','Paypal-Debug-Id': 'd092a377ca029'}
{"name":"UNPROCESSABLE_ENTITY","details":[{"issue":"ORDER_NOT_APPROVED","description":"Payer has not yet approved the Order for payment. Please redirect the payer to the 'rel':'approve' url returned as part of the HATEOAS links within the Create Order call or provide a valid payment_source in the request."}],"message":"The requested action Could not be performed,semantically incorrect,or Failed business validation.","debug_id":"d092a377ca029","links":[{"href":"https://developer.paypal.com/docs/apI/Orders/v2/#error-ORDER_NOT_APPROVED","rel":"information_link","method":"GET"}]}

据我所知,这是因为我都尝试同时创建和捕获订单。我怎样才能让捕获只在客户批准后才开始,所以我很可能看不到此错误消息?任何帮助表示赞赏!

.py

def PayPal(self):
    client_id = "ID"
    client_secret = "SECRET"

    environment = SandBoxEnvironment(client_id=client_id,client_secret=client_secret)
    client = PayPalHttpClient(environment)

    request = OrdersCreateRequest()
    request.prefer("return=representation")

    request.request_body({
        "application_context": {
            "return_url": ""},"intent": "CAPTURE","purchase_units": [{
            "amount": {
                "currency_code": "CAD","value": str(App.get_running_app().cart)
            }}]})

    try:
        response = client.execute(request)
        print("Order With Complete Payload:")
        print("Status Code:",response.status_code)
        print("Status:",response.result.status)
        print("Order ID:",response.result.id)
        print("Intent:",response.result.intent)
        print("Links:")
        for link in response.result.links:
            print('\t{}: {}\tCall Type: {}'.format(link.rel,link.href,link.method))
            print("Total Amount: {} {}".format(response.result.purchase_units[0].amount.currency_code,response.result.purchase_units[0].amount.value))
            order = response.result
            print(order)
    except IOError as ioe:
        print(ioe)
        if isinstance(ioe,HttpError):
            print(ioe.status_code)
    webbrowser.open("https://www.sandBox.paypal.com/checkoutNow?token=" + response.result.id)

    # Capture order
    request = OrdersCaptureRequest(order_id= response.result.id)

    try:
        response = client.execute(request)
        order = response.result.id

    except IOError as ioe:
        if isinstance(ioe,HttpError):
            print(ioe.status_code)
            print(ioe.headers)
            print(ioe)
        else:
            print(ioe)

解决方法

只有在客户通过批准流程(在 PayPal)并返回到您的应用程序后才能进行捕获。如果您在创建订单时指定 return_url,则可以将其设置为 deeplink 返回您的应用,这应该是一个 Intent,然后调用仅执行捕获的函数。>