How to Build Shopify App using Laravel & PHP

How to Build Shopify Apps wuth Laravel

Shopify, a leading e-commerce platform, offers a vast ecosystem for businesses to enhance their functionality through custom apps. If you’re looking to Build Shopify app using Laravel & PHP, you’re in the right place. In this comprehensive guide, we’ll take you through the process step by step, enabling you to create a powerful and tailor-made solution for your e-commerce needs.

What is a Shopify App?

You can easily design and personalize your online store and offers with Shopify across a variety of channels, including web, mobile, social media, online marketplaces, brick-and-mortar locations, and pop-up shops. Through Laravel Shopify integration, it also enables efficient inventory, product, payment, and shipping administration tools.

Shopify is totally cloud-based and hosted, which means you can access it from any device that supports it, and they manage software and server updates, allowing you to run your business from anywhere with an internet connection. Most significantly, everything in the admin interface can be accessed and edited using APIs, providing you with complete control.

Shopify makes it simple to set up an online store and provides a self-hosted platform alternative. The admin interface is simple, clear, and easy to use. Because all functions are logically grouped, thorough documentation and video instructions are available on the Shopify website. You simply need one product to sell!

It provides an added benefit for managing and controlling Shopify stores. With the help of GraphQL and the Shopify API, you can build apps like Oberlo to help users explore available products.

Why Build Shopify App Using Laravel?

Shopify offers an outstanding blend of ease of use and broad customization choices, gaining accolades for its numerous built-in features, apps, and marketing tools. Whether you’re a small-scale, first-time seller or an e-commerce behemoth with hundreds of products, Shopify provides the ease of quickly and successfully launching a dynamic online store without the need for coding or web design experience.

All of your business processes are consolidated into a centralized command center with Shopify. If you have a Shopify business with both an online presence and a physical store, your inventory and stock will automatically sync, allowing you to manage your store from any device with a single account.

How to Integrate Shopify App with Laravel?

Requirements

  • You have installed XAMPP >= 8.0
  • You have installed NodeJs >= 17.0
  • You have installed Composer

Creating Shopify App in Shopify Store

Step 1: Go to your Shopify Partner Account and log in. Click on the Apps Menu from the Sidebar. Then, Click on Create app Button.

Image explaining go to Apps and clicking on Create app button

Step 2: Click on Create app manually button, then give your app name, and then click on create button.

Image explanining create app manually.

Step 3: It will redirect to this page. From here, you can see the client ID and Client secret key. These keys will be needed while setting up app in the Laravel.

Image denoting Overview page of a Shopify App

Install Laravel

Step 1: Now, go to xampp -> htdocs Folder and open the terminal here. We Will use Laravel 8 version for developing Shopify App. Please enter the below command to create Laravel Project.

composer create-project laravel/laravel="^8.0" my-shopify-app

This will create a folder named my-shopify-app in htdocs directory.

Step 2: Now, run the below command to enter the my-shopify-app directory.

cd my-shopify-app

Installing kyon147 Laravel Shopify Plugin

Run the below command to install kyon147 Laravel Shopify Plugin.

composer require kyon147/laravel-shopify

Package Configuration

Run the below command to configure this package.

php artisan vendor:publish --tag=shopify-config

You’re now able to access config in config/shopify-app.php.

Essentially you will need to fill in the app_nameapi_keyapi_secret, and api_scopes to generate a working app. Go to the overview page of the Shopify App which you just created, and copy the Client ID and Client secret key.

Now, Go to Laravel project/config/shopify-app.php File. Configure app_name, api_key, api_secret, and api_scope.

Routing

Edit routes/web.php and modify the default route to use the verify.shopify middleware with the home named, example:

Route::get('/', function () {
    return view('welcome');
})->middleware(['verify.shopify'])->name('home');

Next, modify resources -> views -> welcome.blade.php to extend this package’s layout for Shopify AppBridge abilities, for example:

@extends('shopify-app::layouts.default')

@section('content')
    <!-- You are: (shop domain name) -->
    <p>You are: {{ $shopDomain ?? Auth::user()->name }}</p>
@endsection

@section('scripts')
    @parent

    <script>
        actions.TitleBar.create(app, { title: 'Welcome' });
    </script>
@endsection

Models

We need to modify the Laravel user model which is normally located in app -> User.php or app -> Models -> User.php.

Open the file, and add after the namespace:

use Osiset\ShopifyApp\Contracts\ShopModel as IShopModel;
use Osiset\ShopifyApp\Traits\ShopModel;

Next, modify the class line to become:

class User extends Authenticatable implements IShopModel

Next, inside the class, add:

use ShopModel;

A complete file after the changes

<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Osiset\ShopifyApp\Contracts\ShopModel as IShopModel;
use Osiset\ShopifyApp\Traits\ShopModel;

class User extends Authenticatable implements IShopModel
{
    use HasApiTokens, HasFactory, Notifiable;
    use ShopModel;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

Jobs

In this package, we utilize jobs to efficiently install webhooks, scripttags, and, if applicable, an after-install hook based on the configuration settings. If you don’t have any after-install hooks, scripttags, or webhooks to add to the shop, feel free to skip this section. It’s designed to seamlessly handle the installation process for these elements, making it hassle-free for you!

ScriptTags Job

Before proceeding, you must obtain permission to write script tags for the storefront. To do this, simply add “write_script_tags” to the “api_scopes” section in your config/shopify-app.php file or set it in the “SHOPIFY_API_SCOPES” environment variable, as shown below:

'api_scopes' => env('SHOPIFY_API_SCOPES', 'read_products,write_products,write_script_tags'),

Second, add script tag values to scripttags in config/shopify-app.php:

'scripttags' => [
    [
        'src' => env('SHOPIFY_SCRIPTTAG_1_SRC', 'https://some-app.com/some-controller/js-method-response'),
        'event' => env('SHOPIFY_SCRIPTTAG_1_EVENT', 'onload'),
        'display_scope' => env('SHOPIFY_SCRIPTTAG_1_DISPLAY_SCOPE', 'online_store')
    ]
],

Uninstalled Job (recommended)

We have a default job that makes it easy to delete your shop and any charges linked to it. You can directly install this job or modify it to suit your preferences. It’s designed to be user-friendly and straightforward!

To install, first run:

php artisan vendor:publish --tag=shopify-jobs

It will place a job in App/Jobs/AppUninstalledJob.

Next, edit config/shopify-app.php to enable the job:

 'webhooks' => [
        [
            'topic' => env('SHOPIFY_WEBHOOK_1_TOPIC', 'APP_UNINSTALLED'),
            'address' => env('SHOPIFY_WEBHOOK_1_ADDRESS', 'https://(your-domain).com/webhook/app-uninstalled')
        ],
    ],

To personalize the values, such as the domain, use your environment file. Make sure to set the topic as “app/uninstalled” and the path as “/webhook/app-uninstalled” to allow the webhook manager to handle the intricate details for you. It simplifies the process!

Migrations

Create a database of your own name in phpmyadmin. For example, You are creating project named my-shopify-app. Then, you also need to configure .env file and setup DB_DATABASE to my-shopify-app

DB_DATABASE=my-shopify-app

After configuring .env file, Run below command.

php artisan optimize

Now, for setting up database tables, Please run this command for migrations.

php artisan migrate

CSRF

You need to disable CSRF as there is currently no solution for verifying session tokens with CSRF, there is a conflict due to new login creation for each request.

Go to app -> http ->middleware -> VerifyCsrfToken.php, and add or edit:

protected $except = [
    '*',
];

SPA Support

Starting from version 17.3.0, the package has undergone some modifications to accommodate the use of React, Vue, and other Single Page Applications (SPAs).

If you are using React you can add to your env

SHOPIFY_FRONTEND_ENGINE="REACT"

If you are using Vue you can add to your env

SHOPIFY_FRONTEND_ENGINE="VUE"

If you are continuing to use the Blade templates then you can leave the ENV variable out of your .env file or just add it in as follows.

SHOPIFY_FRONTEND_ENGINE="BLADE"

AppBridge

Important Note: If you decide to utilize the “frontend_engine” option as mentioned earlier, it’s essential to be aware that generating tokens in the blade templates will no longer occur. Despite this change, you must still ensure that you remove the X-Frame-Options, as detailed below.

By default, Appbridge is enabled and necessary for session tokens to work correctly.

In order for AppBridge to function properly, the X-Frame-Options header must be removed. This package makes an attempt to remove this header through the responses in Laravel, but please be aware that it might not work in all cases.

For users employing Nginx, and specifically those using Laravel Forge, you will need to explicitly comment-out or remove the specified line from the Nginx configuration for everything to work as intended:

add_header X-Frame-Options “SAMEORIGIN”;

The Nginx configuration is found in Laravel Forge at the very bottom of the page for the site in question: Files->Edit Nginx Configuration.

Installing Laravel Project on Shopify

Ngrok

To install laravel project on the Shopify store, you will need https connection. Ngrok provides this secure environment for Laravel project

Go to Ngrok website and Download this application. After it is downloaded, please install it on your PC.

Now, create an account in Ngrok here

It will be provide dashboard as shown below in the image.

Ngrok Dashboard Page

Go to Connect your account and copy highlighted code.

Now, open Ngrok Application and paste this command. It will configure the Application.

Setting up Ngrok Application

Run Laravel Project

To run Laravel project, you need to run two command simultaneously, which means open two terminal in the same folder and run these commands

php artisan serve
php artisan queue:listen

Now, Go to the Ngrok terminal and run this command.

ngrok http 8000

It will generate secure URL with https. Copy this URL.

Setting up Shopify App on Shopify Store

Now, go to the Shopify app which you have created on the Shopify store. Go to App Setup -> App URLs. Please URLs as shown in the screenshot below.

Final Installation

Now, go to the browser and paste ngrok URL with appending /authenticate?shop=SHOPIFY_STORE_NAME without myshopify.com at the end and then press enter. For Example

https://3e23-103-251-59-170.ngrok-free.app/authenticate?shop=candiland

It will automatically authenticate with Shopify store.

Now, Click on the Install button, and hurrah 🙌🎉👏, your App is installed.

If you have any questions regarding building Shopify App, then comment down below. I will surely help you.

FAQs to Build Shopify App using Laravel & PHP

Q. Can I use PHP frameworks other than Laravel?
For its powerful features, Laravel is suggested, although you can also use alternative PHP frameworks. But Laravel is a great option because of its comprehensive documentation and active community.

Q. Is there a cost involved in creating a Shopify app?
Costs associated with developing a Shopify app include hosting and optional other services. The advantages of a customized app, however, may exceed these expenses.

Q. Can I make money off of my Shopify app?
Yes, you can make money off your app using subscription services, one-time sales, or freemium models. The billing API for Shopify enables smooth payment processing.

Q. Is JavaScript required while using Laravel to create apps?
Although front-end interactions frequently utilize JavaScript, you can create a simple Shopify app using Laravel’s Blade templating engine without having a deep understanding of JavaScript.

Q. How can I list my app in Shopify’s App Store?
You can submit your app for evaluation to the Shopify App Store once it has been developed and extensively tested. Make sure it adheres to their rules and requirements.

Let’s Create Shopify Theme App Extension to enhance User Experience.

Hardik Davra
Hardik Davra
Hardik Davra is a CEO at Candisoft Tech, a Company specializing in Shopify Development. I have over 5 years of experience in Shopify website development.

Leave a Reply

Your email address will not be published. Required fields are marked *