I will say up front, that I am sure there may be easier or better ways to do this, so if you know of one feel free to comment and explain your method.
For my application though, some things cannot change:
- Solution must work with Laravel
- Solution must work with Paypal Checkout
- Best if solution can’t be easily circumvented (don’t want people able to easily alter the price of what gets processed for example. So I want the information to come from server side database, or a controller, etc.)
Right now I have things setup as follows:
In the Laravel view:
@push('scripts') <script src="https://www.paypal.com/sdk/js?client-id=CLIENT_ID_HERE"></script> <script src="{{ asset('js/paypalbutton.js') }}" type="text/javascript"></script> @endpush //LOTS OF STUFF HERE //|Further Down| //| | //v v <div class="show-price"> {{'$' . $offering['price']}} //This will display the price for current item from mysql </div> <div class="click-to-purchase"> <div id="paypal-button-container" load="paypalbutton(this)"> </div> </div>
in a .js file called paypalbutton.js inside the laravel project directory:
$(document).ready(function paypalbutton(){ paypal.Buttons({ createOrder: function(data, actions) { return actions.order.create({ purchase_units: [{ amount: { value: '0.01' } }] }); }, onApprove: function(data, actions) { return actions.order.capture().then(function(details) { alert('Transaction completed by ' + details.payer.name.given_name); }); } }).render('#paypal-button-container'); // Display payment options on your web page });
This works fine to display the paypal buttons on the page, and it works to process a payment, problem is, I need to pass information from sqlite database to the javascript file with information like for example, the amount of the transaction.
Ideally I would just save variables for each piece of information on top of the .js file, and have them get initialized with the correct values at run time.
Advertisement
Answer
you can do this by global js variable :
@push('scripts') <script> let amount ='{{$amount}}' </script> <script src="https://www.paypal.com/sdk/js?client-id=CLIENT_ID_HERE"></script> <script src="{{ asset('js/paypalbutton.js') }}" type="text/javascript"></script> @endpush
and in your js file :
$(document).ready(function paypalbutton(){ paypal.Buttons({ createOrder: function(data, actions) { return actions.order.create({ purchase_units: [{ amount: { value: amount } }] }); }, onApprove: function(data, actions) { return actions.order.capture().then(function(details) { alert('Transaction completed by ' + details.payer.name.given_name); }); } }).render('#paypal-button-container'); // Display payment options on your web page });