The quickest way to integrate PayPal checkout with Blazor SSR in .NET 8
You have a Blazor web app and want to integrate with PayPal to accept payments.
How to make it work?
You could go down the road of using Blazor Server/Web Assembly and a little bit of JavaScript Interop to stitch it all together…
But what if you’re keen to avoid paying the interactivity tax, and want to stick with Blazor Server-side rendering?
The challenge#
PayPal has a JavaScript script you can use to initiate checkout and accept payments online.
In a .NET 8 Blazor app you can reference that script in App.razor (more on that in a moment).
Then, one of the easier ways to trigger PayPal checkout is to use PayPal’s Buttons API to show checkout buttons:
<div id="paypal_container"></div>
let container = document.getElementById('paypal_container');
paypal.Buttons({ style: { shape: 'rect', color: 'gold', layout: 'vertical', label: 'subscribe' }, createSubscription: function (data, actions) { return actions.subscription.create({ // replace with your own plan Id plan_id: 'P-61S92112RP924735VMOE434Y' }); }, onApprove: function (data, actions) { alert(data.subscriptionID); // optional success message for the subscriber }}).render(container); // Renders the PayPal button
Run this script and you get PayPal Buttons rendered in the #paypal_container
element.
At this point users can click one of the buttons and proceed to checkout via PayPal’s hosted checkout UI.
But how to do this with Blazor when you’re using static server-side rendering?
Reference the PayPal script#
The first step is to load the PayPal script.
We can do that directly in App.razor.
<!DOCTYPE html><html lang="en">
<head> ... <HeadOutlet/>
<script src="https://www.paypal.com/sdk/js?client-id=<your-client-id-here>&vault=true&intent=subscription" data-sdk-integration-source="button-factory"></script></head>
<body><Routes/><script src="_framework/blazor.web.js"></script>
</body>
</html>