Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PayPal Smart Payment Buttons error paypal.Buttons is not a function

Tags:

php

paypal

I am integrating Smart Payment Buttons in my website, before it works properly, but earlier today, I am getting these errors

enter image description here

I loaded paypal SDK before I even loaded the paypal.Buttons().render() function which is inside my paypal.js file

<script src="https://www.paypal.com/sdk/js?client-id=<MY_CLIENT_ID_HERE>&currency=PHP"></script>

<script type="text/javascript" src="paypal.js"></script>

this is the content of my paypal.js file

paypal.Buttons({
createOrder : function(data, actions){
  return actions.order.create({
    purchase_units : [{
      amount : {
        value : amount_to_pay
      }
    }],
    application_context: {
        shipping_preference: "NO_SHIPPING",
    },
    country_code : "PH"
  })
},
style: {
      color:  'gold',
      shape:  'rect',
      label:  'buynow',
       size: 'responsive',
       branding: true

  },
  onApprove: function(data, actions) {
    // Capture the funds from the transaction
    return actions.order.capture().then(function(details) {

      return fetch('/pay-with-pp', {
        method: 'post',
        headers: {
          'content-type': 'application/json'
        },
        body: JSON.stringify({
          orderID: data.orderID,
          product_id : product_id,
          _token : token
        })
      }).then(function(res){
        alert('Payment has been made! Please see the delivery status on orders page!');
        window.location.href = redirect_url
      });
    });
  },

}).render('#paypal-button-container');
like image 915
Kim Carlo Avatar asked Nov 02 '25 04:11

Kim Carlo


2 Answers

I analyzed the errors carefully and found out the solution.

I added a data-namespace attribute to the script tag that loads the SDK

<script src="https://www.paypal.com/sdk/js?client-id=AaJMejIDjhumOr48XsycjfvQegxAku1dHdrA0DNfkqFSg7bFFkpJTnnwyaLIGUFsPijWx1g51gxp9F-5&currency=USD" data-namespace="paypal_sdk"></script>

then use the value of data-namespace in my paypal.js file

so instead of

paypal.Buttons().render()

i used

paypal_sdk.Buttons().render()

and it works!

like image 74
Kim Carlo Avatar answered Nov 03 '25 16:11

Kim Carlo


(I got this error in ReactJs) Make sure you're loading the <script> tags properly - to which I mean, don't delay their loading by adding things like the defer attribute, otherwise paypal.Buttons() is called before the script tags are called, hence the error.

I don't know if 2 years down the line since this question was asked whether my answer will be at all helpful.

like image 42
Thomas Sankara Avatar answered Nov 03 '25 18:11

Thomas Sankara