Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

womack's avatar

How would you structure your code to interact with a third party API?

I am trying to understand the best way to structure my code in Laravel for dealing with a third party API mainly for scalability. If you take the Stripe API for example if you were looking to deal directly with the API yourself instead of using something like Laravel\Cashier how would you go about structuring your code?

From the videos I have watched I can see there being a couple of options

  • Splitting up the logic into commands for each interaction e.g. a CreateSubscriptionCommand or ChargeUserCommand

  • Creating a repository for the interaction, comprised of methods for different API calls e.g. createSubscription

  • Creating a Service which seems similar to the repository method, just a class that is comprised of methods for interacting with the API

  • Or possibly a combination of a Repository and a Service where the repository handles retrieving information from the API e.g. getting a users subscriptions, and the service handles pushing information to the API e.g. creating subscriptions

This isn't necessarily for integrating with Stripe alone just third party APIs in general, any advice would be greatly appreciated

0 likes
3 replies
NormySan's avatar

It depends on the scope of the API. If it was something like Stripe i would probably create a Service class or put it into it's own folder with all classes related to the API.

2 likes
CraftThatBlock's avatar

Interfaces Interfaces Interfaces Interfaces Interfaces Interfaces Interfaces Interfaces Interfaces Interfaces Interfaces Interfaces Interfaces Interfaces Interfaces.

1 like
womack's avatar

I think I am leaning towards the implementation of a service class and would definitely create an interface and a service provider so that should I ever change the third party API I am using I will be able to change fairly effortlessly

Please or to participate in this conversation.