DEV Community

Cover image for PayPal Implementation in Django Rest Framework.

PayPal Implementation in Django Rest Framework.

paulsaul621 on October 31, 2022

Introduction. If you're a Django developer, then you know that Django Rest Framework is a great tool for building RESTful APIs. But what...
Collapse
 
tmcmanamey profile image
Tim • Edited

Okay, I got a little further. I'm trying to get links back from paypal for my payment. I've got my token from paypal and requesting the links. I don't know how to get more info other than a 400 error. I can't find on the paypal site the format for the message. I am running this from localhost. I also noticed in the json "landing_page": "BILLING" is this important or just a name?

This is the error
order_id = response.json()['id'] …
Local vars
Variable Value
headers
{'Authorization': 'Bearer '
'this is the auth token',
'Content-Type': 'application/json'}
json_data

{'application_context': {'brand_name': 'Nebraska Youth Camp',
'cancel_url': '/registration/cancel_url',
'landing_page': 'BILLING',
'notify_url': '/registration/notify_url',
'return_url': '/registration/return_url',
'shipping_preference': 'NO_SHIPPING',
'user_action': 'CONTINUE'},
'intent': 'CAPTURE',
'purchase_units': [{'amount': {'currency_code': 'USD', 'value': '200'},
'custom_id': 'Camp Session',
'description': 'Summer Camp',
'reference_id': '294375635',
'soft_descriptor': 'Camp Session'}]}
request

response


self


token

'my token was here'

def PaypalToken(client_ID, client_Secret):

    url = "https://api-m.sandbox.paypal.com/v1/oauth2/token"
    data = {
                "client_id":client_ID,
                "client_secret":client_Secret,
                "grant_type":"client_credentials"
            }
    headers = {
                "Content-Type": "application/x-www-form-urlencoded",
                "Authorization": "Basic {0}".format(base64.b64encode((client_ID + ":" + client_Secret).encode()).decode())
            }

    token = requests.post(url, data, headers=headers)
    return token.json()['access_token']

class CreateOrderViewRemote(APIView):
    def get(self, request):
        token = PaypalToken(clientID, clientSecret)
        headers = {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer '+token,
        }
        json_data = {
             "intent":"CAPTURE",
             "application_context": {
                 "notify_url": reverse('paypal-notify'),
                 "return_url": reverse('paypal-return'),#change to your doma$
                 "cancel_url": reverse('paypal-cancel'), #change to your domain
                 "brand_name": "Nebraska Youth Camp",
                 "landing_page": "BILLING",
                 "shipping_preference": "NO_SHIPPING",
                 "user_action": "CONTINUE"
             },
             "purchase_units": [
                 {
                     "reference_id": "294375635",
                     "description": "Summer Camp",

                     "custom_id": "Camp Session",
                     "soft_descriptor": "Camp Session",
                     "amount": {
                         "currency_code": "USD",
                         "value": "200" #amount,
                     },
                 }
             ]
         }
        response = requests.post('https://api-m.sandbox.paypal.com/v2/checkout/orders', headers=headers, json=json_data)
        order_id = response.json()['id'] # error here because return error 400, no id
        linkForPayment = response.json()['links'][1]['href']
        return linkForPayment
Enter fullscreen mode Exit fullscreen mode

Thanks for your help.

Collapse
 
paulwababu profile image
paulsaul621

Please print("response.text") so that I cam see the actual error. Landing page is where the user lands after being redirected to paypal for payments. In our case is billing. You can check PayPal documentation for the other landing pages.

Collapse
 
tmcmanamey profile image
Tim

I was able to get it to work. I used json.dump() but someone else said that if I name the variable json or at lease put json=json_data in the args that it should retain the json format. After trying this I see he's correct. I know you have that in your code but I had combined with other code I saw. I also ran through a json validator and found some commas that were not strict json. Thanks again.

Thread Thread
 
paulwababu profile image
paulsaul621

Great!

Collapse
 
tmcmanamey profile image
Tim

what does "requests.post" refer to?

Collapse
 
paulwababu profile image
paulsaul621

requests.post is a function in the Python requests library that sends an HTTP POST request to the specified URL

Collapse
 
tmcmanamey profile image
Tim

What is the APIView you refer to? Is that something we need to create?

Collapse
 
tmcmanamey profile image
Tim

Okay, so I found this. It's part of the djangorestframework

Collapse
 
tmcmanamey profile image
Tim

How do we use the Capture Order function? Do we need to make a request of Paypal then have it return to the capture order? When I have it redirect after payment the only thing in the url is the token and the payerId. Does the request.data.get('token') just get the token from the url? I get a "missing schema" on the request.data.get('url').

Collapse
 
tmcmanamey profile image
Tim

I have another question. I'm not really familiar with the rest-framework api. I get a page with the link to pay, see below, but how do I get that on my own html? Will it work if I just return to a page that I've created?

Image description

Collapse
 
tmcmanamey profile image
Tim

Is the viewset class from the djangorestframework? Do I need to start a new file with this?