{%title%}
{%description%}
Dynamically load Cashier Paddle buttons with renderless component
Reece May • November 13, 2020 • 5 min read
laravel paddle cashier vueA project I have been working on has been in need of an improved billing system, with the release of the cashier-paddle package I was able to add some subscriptions to the app.
Working with the package, one can see that it's relatively easy and fluent to get paddle / cashier working in your Laravel app. And this is great!
Noticing the load times on generating links
I noticed after a while that sometimes the loading of the payment links took a while. Taking into account the API is requested for each link. Making in turn the response from the server slow, ... ... ... waiting for each link to be generated.
Obviously, the immediate thing here is that if this isn't an SPA that doesn't have to get new pages, you will notice. And you would notice on an SPA 🤷♂️
Now, this is greatly exaggerated if you are showing a bunch of paddle links for a user to choose. That sucks really.
So I decided to make it a little more enjoyable to load up a bunch of possible subscriptions for an end user, and also make the vue component renderless. This makes it easier for me to port it between a few projects.
So off to work on a 'simplification'.
First thing, the original blade component file:
1<a href="#!" data-override="{{ $url }}" {{ $attributes->merge(['class' => 'paddle_button']) }}>2 {{ $slot }}3</a>
Basically, the important things here are: href="#!"
, data-override=""
and the css class paddle_button
Awesome, so when the component is made we just need to make sure those are there in either out component or the added ones.
Please note, there isn't any need to move away from the blade component, it's an awesome way of rendering the links each time. For this instance it didn't always work
Renderless Paddle Subscription Component
Now to the component, it is in Vuejs because currently that is the frontend it was made for :)
We can create a js file called Subscriptions.js
under your js folder, your choice. Mine are in a components folder.
We know that we need to hold the links that are retrieved, a loading state and error state, so lets get those into the component
1export default { 2 data() { 3 return { 4 payLinks: [], 5 loaded: false, 6 error: false, 7 }, 8 }, 9 render() {10 return this.$slots.default[0];11 }12}
This would be our basic component that we can return. But, I wanted to pass some things down to the elements in the slot area to use.
So we make use of the $scopedSlots
property, this allows us to pass data to the slots, and then pick up those in our html side.
1export default { 2 data() { 3 return { 4 payLinks: [], 5 loaded: false, 6 error: false, 7 }, 8 }, 9 render() {10- return this.$slots.default[0];11+ return this.$scopedSlots.default({12+ payLinks: this.payLinks,13+ loaded: this.loaded,14+ error: this.error,15+ })16 }17}
Fetching the Paddle PayLinks from the backend over an API endpoint
Now the fun part, getting the paddle links from the server and loading them into the component
I initially had the url for the endpoint hard coded, but then realized it would be better to have it as a prop, can then use something like: endpoint="{{ route('api.billing.links') }}"
.
Change the component to include the following:
1export default { 2 data() { 3 ... 4 }, 5+ props: { 6+ /** 7+ * The api endpoint to fetch the billing info 8+ */ 9+ endpoint: {10+ type: String,11+ default: '/api/settings/billing'12+ }13+ },14+ methods: {15+ fetch() {16+ axios.get(this.endpoint)17+ .then(({18+ data: { data }19+ }) => {20+ this.payLinks = data;21+ this.loaded = true;22+ this.error = false;23+ })24+ .catch(error => {25+ this.loaded = false;26+ this.error = true;27+ throw error;28+ });29+ }30+ },31 render() {32 return this.$scopedSlots.default({33 payLinks: this.payLinks,34 loaded: this.loaded,35 error: this.error,36+ fetch: this.fetch37 });38 }39}
The method fetch
uses the endpoint value in the axios request, this in turn loads the data from the response into the payLinks
url.
We also add the fetch method to the output of the slot scope, enabling us to trigger a reload from outside the component
Adding some messages and feedback
1export default { 2 data() { 3 return { 4 payLinks: [], 5 loaded: false, 6 error: false, 7+ message: 'Loading Subscriptions ...', 8 } 9 },10 11 ... // props12 13 methods: {14 fetch() {15 axios.get(this.endpoint)16 .then(({17 data: { data }18 }) => {19 this.payLinks = data;20 this.loaded = true;21 this.error = false;22 })23 .catch(error => {24 this.loaded = false;25 this.error = true;26+ this.message = 'Failed to load current subscriptions';27 throw error;28 });29 }30 },31 render() {32 return this.$scopedSlots.default({33 payLinks: this.payLinks,34 loaded: this.loaded,35 error: this.error,36+ message: this.message,37 fetch: this.fetch38 });39 }40}
Loading Paddle after getting the links.
When using the Laravel cashier-paddle package, you use the @paddleJs
directive, this loads buttons that are already there. Not our vue rendered checkout button.
When checking the methods available on the Paddle object that is loaded you find that the Paddle JS file has some methods that are callable, and one that instantiates the buttons, and we can call it, awesome stuff.
So, what we do is to make use of the fact that because we are rendering the data inside the component after fetching it, we can rely on the updated
method to reload the Paddle buttons. This is done using Paddle.Button.load()
So what we can do is add a new method and stick that into the updated handler:
1export default { 2 3+ updated() { 4+ this.loadPaddle() 5+ }, 6 7 methods: { 8+ loadPaddle() { 9+ // check if paddle is loaded.10+ if (Paddle) {11+ try {12+ Paddle.Button.load();13+ } catch (error) {14+ console.error(error);15+ }16+ }17+ }18 },19}
Loading up the Paddle links
Right so our file now has the needed methods and data properties, the final bit, and probably really, really important is the css paddle_button
.
Now lets look at the mounted method, this is where we are going to call all the methods and add the paddle_button
class to our links.
1mounted() { 2 this.$nextTick(() => { 3 this.fetch(); 4 5 this.$el.querySelectorAll('a') 6 .forEach(element => { 7 if (element.href === '#!') { 8 element.classList.add('paddle_button'); 9 }10 });11 });12},
Basically, after the component is mounted, we wait till the next tick from vue and all that, fetch the links from the backend.
We then use some good ol' Javascript 😁. Using the querySelectorAll('a')
function, we can get all the links that happen to be in the slot area, loop through them, then add the class paddle_button
on any link that has the href of #!
. That way we don't load up other random urls to have the paddle stuff.
Final JS file
Below is the final component file, a lot nicer than the bunch of diff markings all over...
1/** 2 * Paddle Subscription button renderless component. 3 * 4 * @author ReeceM 5 * @copyright MIT 6 * @filename Subscriptions.js 7 */ 8 9// import axios from 'axios'; // optional..10 11export default {12 data() {13 return {14 payLinks: [],15 loaded: false,16 error: false,17 message: 'Loading Subscriptions ...',18 }19 },20 21 props: {22 /**23 * The api endpoint to fetch the billing info24 */25 endpoint: {26 type: String,27 default: '/api/settings/billing'28 }29 },30 31 mounted() {32 this.$nextTick(() => {33 this.fetch();34 35 this.$el.querySelectorAll('a')36 .forEach(element => {37 if (element.href === '#!') {38 element.classList.add('paddle_button');39 }40 });41 });42 },43 44 updated() {45 this.loadPaddle()46 },47 48 methods: {49 /**50 * Fetch the Paddle Paylinks from the server.51 */52 fetch() {53 54 this.error = false;55 this.loaded = false;56 57 axios.get(this.endpoint)58 .then(({59 data: { data }60 }) => {61 this.payLinks = data;62 this.loaded = true;63 })64 .catch(error => {65 this.message = 'Failed to load current subscriptions';66 this.loaded = false;67 this.error = true;68 69 throw error;70 });71 },72 73 /**74 * reload the Paddle buttons75 */76 loadPaddle() {77 Paddle ? Paddle.Button.load() : console.warn('Up a creek!');78 }79 },80 81 render() {82 return this.$scopedSlots.default({83 payLinks: this.payLinks,84 loaded: this.loaded,85 error: this.error,86 message: this.message,87 fetch: this.fetch88 });89 }90}
Example usage
Below is an example that uses the laravel blade file, and then builds up a table with the buttons and the paylinks. The styling is in Bulma.
1<subscriptions> 2 <template v-slot="{payLinks, message, loaded, error, fetch}"> 3 <table class="table is-striped is-fullwidth table-bordered"> 4 <tbody> 5 <tr v-if="!loaded"> 6 <td v-text="message"></td> 7 <td v-if="error"> 8 <div class="notification is-warning"> 9 <button10 @click=fetch()11 class="button is-small is-outlined">12 Retry13 </button>14 </div>15 </td>16 </tr>17 <tr v-else18 v-for="payLink in payLinks"19 :key="payLink.title" >20 <td>@{{ payLink['title'] }} Plan</td>21 <td>terms</td>22 <td>23 <a24 href="#!"25 :data-override="payLink['link']"26 data-theme="none"27 28 class="button is-info"29 :class="{'is-success': payLink['current']}" >30 @{{payLink['current'] === true ? 'Subscribed' : 'Subscribe'}}31 </a>32 </td>33 </tr>34 </tbody>35 </table>36 </template>37</subscriptions>
To make use of the slot scope, we need to use a <template>
element, then add the v-slot="{payLinks, message, loaded, error, fetch}"
attribute, this allows us to access the needed data.
From there we can use the stuff inside the blade file to change how we render the Subscription links, this is nice because we don't have to recompile the JS file every time we need to make a change to a bit of wording.
Just don't forget the @
before the handlebar tags, or you going to end up with a bunch of errors from the blade engine.
I will share the follow up article to this on an example backend controller to get the links with.
I hope you enjoyed the post, please share any feedback you have on it or thoughts, you can give me a shout on twitter with @iexistin3d
.
0_o
Syntax highlighting by Torchlight.