PayPal Server, Process Order Python/Django 29
Now with our token, which in other words is the PayPal access token, according to what was implemented before, it is something like the JSON WEB TOKEN of Django Rest Framework or similar, instead of passing the user password, we pass this to it and it is happy. Now with this token we could capture or approve the order as you want to call it, so for this we are going to create another method here that will be called capture order or whatever name you want and here we pass the self and the order ID:
mystore\elements\views.py
class PayPalPayment:
***
def capture_order(self, order_id):
access_token = self.get_access_token()
if not access_token:
return {"error": "Could not get access token"}
url = f"{self.base_url}/v2/checkout/orders/{order_id}/capture"
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {access_token}",
}
data = {
"application_context": {
"return_url": "<URL-RETURN>",
"cancel_url": "<URL-CANCEL>",
}
}
response = requests.post(url, json=data, headers=headers)
return response.json()
From the view, we consume the previous method, creating an instance of the class and in a view, we display the relevant data that we extract from the Paypal response:
mystore\elements\views.py
def capture_payment(request, order_id):
paypal = PayPalPayment()
res = paypal.capture_order(order_id)
if res:
return render(request,'elements/capture_payment.html', {'res': res,
'id': res['id'],
'status': res['status'],
'price': res['purchase_units'][0]['payments']['captures'][0]['amount']['value']})
return render(request,'elements/error.html')