Search code examples
pythondjangopaypalpaypal-sandboxpaypal-rest-sdk

Integrate PayPal in Django app using Paypal Python SDK


I'm working on a project in which I'm using Python(3.6) & Django(1.10) and I need to implement Paypal payment method in this project. I have decided to use the official Python SDK from Paypal instead of other third-party packages.It's not only the csrf problem but it also how we can render a custom form for paypal checkout button.

Here's wwhat Ihave tried.
According to the docs as Here.
Here's my template:

<form class="form">
   {% csrf_token %}
    <div id="paypal-button"></div>

    <script src="https://www.paypalobjects.com/api/checkout.js"></script>

    <script>
      var CREATE_PAYMENT_URL = '{% url 'users:payment' %}';
      var EXECUTE_PAYMENT_URL = 'https://my-store.com/paypal/execute-payment';
      paypal.Button.render({
         env:    'sandbox', // Or 'production'

         commit: true, // Show a 'Pay Now' button
         payment: function () {
           return paypal.request.post(CREATE_PAYMENT_URL).then(function (data) {
               return data.paymentID;
    });
 },

         onAuthorize: function (data) {
             return paypal.request.post(EXECUTE_PAYMENT_URL, {
                    paymentID: data.paymentID,
                    payerID: data.payerID}).then(function () {                                                            
                   // The payment is complete!                                                                    

                  // You can now show a confirmation message to the customer
              });
            }
      }, '#paypal-button');
   </script>
 </form>

From urls.py:

   url('^payment/$', views.PaymentProcess.as_view(), name='payment'),

From views.py:

class PaymentProcess(LoginRequiredMixin, generic.DetailView):
    def post(self, request, *args, **kwargs):
        mydict = {
            'paymentID': 'PAYMENTID',
        }
        print('Getting payment request')
        return json.dumps(mydict)

When Paypal submits a post request to /payment it returns 403 Forbidden error due to csrf_token. How can I pass the csrf_token with this request.

Any resource or tutorial will be really appreciated.


Solution

  • It seems you can add custom headers to your post request : https://github.com/paypal/PayPal-Python-SDK/blob/master/paypalrestsdk/api.py#L270

    Given that you just have to add you csrf token to the headers : https://docs.djangoproject.com/en/2.0/ref/csrf/#setting-the-token-on-the-ajax-request

    And your server should give you access