From 8a3a0ca3b75d81a433fff8682e3b705d417b215d Mon Sep 17 00:00:00 2001
From: enmaboya <vita-dubov@yandex.ru>
Date: Sun, 10 Nov 2024 05:06:42 +0400
Subject: [PATCH 1/4] remove old config parameters

---
 src/Traits/AuthController.php        |  1 -
 src/resources/config/shopify-app.php | 33 ----------------------------
 2 files changed, 34 deletions(-)

diff --git a/src/Traits/AuthController.php b/src/Traits/AuthController.php
index ab443566..3e9ee209 100644
--- a/src/Traits/AuthController.php
+++ b/src/Traits/AuthController.php
@@ -64,7 +64,6 @@ public function authenticate(Request $request, AuthenticateShop $authShop)
                 'shopify-app::auth.fullpage_redirect',
                 [
                     'apiKey' => Util::getShopifyConfig('api_key', $shopOrigin),
-                    'appBridgeVersion' => Util::getShopifyConfig('appbridge_version') ? '@'.config('shopify-app.appbridge_version') : '',
                     'authUrl' => $result['url'],
                     'host' => $request->get('host'),
                     'shopDomain' => $shopDomain,
diff --git a/src/resources/config/shopify-app.php b/src/resources/config/shopify-app.php
index 6acbfd7a..34770d10 100644
--- a/src/resources/config/shopify-app.php
+++ b/src/resources/config/shopify-app.php
@@ -37,7 +37,6 @@
     */
 
     'domain' => env('SHOPIFY_DOMAIN'),
-    
     /*
     |--------------------------------------------------------------------------
     | Manual routes
@@ -138,26 +137,6 @@
 
     'prefix' => env('SHOPIFY_APP_PREFIX', ''),
 
-    /*
-    |--------------------------------------------------------------------------
-    | AppBridge Mode
-    |--------------------------------------------------------------------------
-    |
-    | AppBridge (embedded apps) are enabled by default. Set to false to use legacy
-    | mode and host the app inside your own container.
-    |
-    */
-
-    'appbridge_enabled' => (bool) env('SHOPIFY_APPBRIDGE_ENABLED', true),
-
-    // Use semver range to link to a major or minor version number.
-    // Leaving empty will use the latest version - not recommended in production.
-    'appbridge_version' => env('SHOPIFY_APPBRIDGE_VERSION', 'latest'),
-
-    // Set a new CDN URL if you want to host the AppBridge JS yourself or unpkg goes down.
-    // DO NOT include a trailing slash.
-    'appbridge_cdn_url' => env('SHOPIFY_APPBRIDGE_CDN_URL', 'https://unpkg.com'),
-
     /*
     |--------------------------------------------------------------------------
     | Shopify App Name
@@ -513,18 +492,6 @@
 
     'config_api_callback' => null,
 
-    /*
-    |--------------------------------------------------------------------------
-    | Enable Turbolinks or Hotwire Turbo
-    |--------------------------------------------------------------------------
-    |
-    | If you use Turbolinks/Turbo and Livewire, turn on this setting to get
-    | the token assigned automatically.
-    |
-    */
-
-    'turbo_enabled' => (bool) env('SHOPIFY_TURBO_ENABLED', false),
-
     /*
     |--------------------------------------------------------------------------
     | Customize Models and Table Name

From 023c9514f39b116787c27da111b62f791e309080 Mon Sep 17 00:00:00 2001
From: enmaboya <vita-dubov@yandex.ru>
Date: Sun, 10 Nov 2024 05:07:08 +0400
Subject: [PATCH 2/4] use shopify global object from app bridge cdn

---
 .../views/auth/fullpage_redirect.blade.php    | 23 +++----------
 src/resources/views/auth/token.blade.php      | 13 ++++---
 .../views/billing/fullpage_redirect.blade.php | 23 ++++++-------
 src/resources/views/home/index.blade.php      | 16 +++------
 src/resources/views/layouts/default.blade.php | 23 ++-----------
 .../views/partials/flash_messages.blade.php   | 22 ------------
 .../views/partials/token_handler.blade.php    | 34 +++++++------------
 7 files changed, 42 insertions(+), 112 deletions(-)
 delete mode 100644 src/resources/views/partials/flash_messages.blade.php

diff --git a/src/resources/views/auth/fullpage_redirect.blade.php b/src/resources/views/auth/fullpage_redirect.blade.php
index 8ed3435d..0c911ca4 100644
--- a/src/resources/views/auth/fullpage_redirect.blade.php
+++ b/src/resources/views/auth/fullpage_redirect.blade.php
@@ -3,32 +3,19 @@
     <head>
         <meta charset="utf-8">
         <base target="_top">
+        <meta name="shopify-api-key" content="{{ config('shopify-app.api_key') }}" />
+        <script src="https://cdn.shopify.com/shopifycloud/app-bridge.js"></script>
 
         <title>Redirecting...</title>
 
-        <script src="{{config('shopify-app.appbridge_cdn_url') ?? 'https://unpkg.com'}}/@shopify/app-bridge{!! $appBridgeVersion !!}"></script>
         <script type="text/javascript">
             document.addEventListener('DOMContentLoaded', function () {
-                var redirectUrl = "{!! $authUrl !!}";
-                var normalizedLink;
+                let redirectUrl = "{!! $authUrl !!}";
+
                 if (window.top === window.self) {
-                    // If the current window is the 'parent', change the URL by setting location.href
                     window.top.location.href = redirectUrl;
                 } else {
-                    // If the current window is the 'child', change the parent's URL with postMessage
-                    normalizedLink = document.createElement('a');
-                    normalizedLink.href = redirectUrl;
-
-                    var AppBridge = window['app-bridge'];
-                    var createApp = AppBridge.default;
-                    var Redirect = AppBridge.actions.Redirect;
-                    var app = createApp({
-                        apiKey: "{{ $apiKey }}",
-                        host: "{{ $host }}",
-                    });
-
-                    var redirect = Redirect.create(app);
-                    redirect.dispatch(Redirect.Action.REMOTE, normalizedLink.href);
+                    open(redirectUrl, '_top');
                 }
             });
         </script>
diff --git a/src/resources/views/auth/token.blade.php b/src/resources/views/auth/token.blade.php
index 8433d57f..b021b5e6 100644
--- a/src/resources/views/auth/token.blade.php
+++ b/src/resources/views/auth/token.blade.php
@@ -35,12 +35,15 @@
 @section('scripts')
     @parent
 
-    @if(config('shopify-app.appbridge_enabled'))
         <script>
-            const host = new URLSearchParams(location.search).get("host")
-            utils.getSessionToken(app).then((token) => {
-                window.location.href = `{!! $target !!}{!! Str::contains($target, '?') ? '&' : '?' !!}token=${token}{{ Str::contains($target, 'host')? '' : '&host=${host}'}}`;
+            shopify.idToken().then((token) => {
+                const host = new URLSearchParams(location.search).get("host");
+                const url = new URL(`{!! $target !!}`, window.location.origin);
+
+                url.searchParams.set('token', token);
+                url.searchParams.set('host', host);
+
+                open(url.toString(), "_self");
             });
         </script>
-    @endif
 @endsection
diff --git a/src/resources/views/billing/fullpage_redirect.blade.php b/src/resources/views/billing/fullpage_redirect.blade.php
index 300d96d4..0c911ca4 100644
--- a/src/resources/views/billing/fullpage_redirect.blade.php
+++ b/src/resources/views/billing/fullpage_redirect.blade.php
@@ -3,24 +3,21 @@
     <head>
         <meta charset="utf-8">
         <base target="_top">
+        <meta name="shopify-api-key" content="{{ config('shopify-app.api_key') }}" />
+        <script src="https://cdn.shopify.com/shopifycloud/app-bridge.js"></script>
 
         <title>Redirecting...</title>
-        <script src="{{config('shopify-app.appbridge_cdn_url') ?? 'https://unpkg.com'}}/@shopify/app-bridge{{ \Osiset\ShopifyApp\Util::getShopifyConfig('appbridge_version') ? '@'.config('shopify-app.appbridge_version') : '' }}"></script>
+
         <script type="text/javascript">
-            const redirectUrl = "{!! $url !!}";
+            document.addEventListener('DOMContentLoaded', function () {
+                let redirectUrl = "{!! $authUrl !!}";
 
-            const AppBridge = window['app-bridge'];
-            const createApp = AppBridge.default;
-            const Redirect = AppBridge.actions.Redirect;
-            const app = createApp({
-                apiKey: "{{ $apiKey }}",
-                host: "{{ $host }}",
+                if (window.top === window.self) {
+                    window.top.location.href = redirectUrl;
+                } else {
+                    open(redirectUrl, '_top');
+                }
             });
-
-            console.log( 'app', app );
-
-            const redirect = Redirect.create(app);
-            redirect.dispatch(Redirect.Action.REMOTE, redirectUrl);
         </script>
     </head>
     <body>
diff --git a/src/resources/views/home/index.blade.php b/src/resources/views/home/index.blade.php
index 633a6b3d..5ab6e32b 100644
--- a/src/resources/views/home/index.blade.php
+++ b/src/resources/views/home/index.blade.php
@@ -5,6 +5,8 @@
 @endsection
 
 @section('content')
+    <ui-title-bar title="Welcome"></ui-title-bar>
+
     <div class="flex-center position-ref full-height">
         <div class="content">
             <div class="title m-b-md">
@@ -17,20 +19,10 @@
             <p>&nbsp;</p>
 
             <div class="links">
-                <a href="https://github.com/osiset/laravel-shopify" target="_blank">Package</a>
+                <a href="https://github.com/Kyon147/laravel-shopify" target="_blank">Package</a>
                 <a href="https://laravel.com" target="_blank">Laravel</a>
-                <a href="https://github.com/osiset/laravel-shopify" target="_blank">GitHub</a>
+                <a href="https://github.com/Kyon147/laravel-shopify" target="_blank">GitHub</a>
             </div>
         </div>
     </div>
 @endsection
-
-@section('scripts')
-    @parent
-
-    @if(config('shopify-app.appbridge_enabled'))
-        <script>
-            actions.TitleBar.create(app, { title: 'Welcome' });
-        </script>
-    @endif
-@endsection
diff --git a/src/resources/views/layouts/default.blade.php b/src/resources/views/layouts/default.blade.php
index 313e2bfd..fb66892c 100644
--- a/src/resources/views/layouts/default.blade.php
+++ b/src/resources/views/layouts/default.blade.php
@@ -3,6 +3,8 @@
     <head>
         <meta charset="utf-8">
         <meta name="csrf-token" content="{{ csrf_token() }}">
+        <meta name="shopify-api-key" content="{{ config('shopify-app.api_key') }}" />
+        <script src="https://cdn.shopify.com/shopifycloud/app-bridge.js"></script>
 
         <title>{{ \Osiset\ShopifyApp\Util::getShopifyConfig('app_name') }}</title>
         @yield('styles')
@@ -17,28 +19,9 @@
             </div>
         </div>
 
-        @if(\Osiset\ShopifyApp\Util::getShopifyConfig('appbridge_enabled') && \Osiset\ShopifyApp\Util::useNativeAppBridge())
-            <script src="{{config('shopify-app.appbridge_cdn_url') ?? 'https://unpkg.com'}}/@shopify/app-bridge{{ \Osiset\ShopifyApp\Util::getShopifyConfig('appbridge_version') ? '@'.config('shopify-app.appbridge_version') : '' }}"></script>
-            <script
-                @if(\Osiset\ShopifyApp\Util::getShopifyConfig('turbo_enabled'))
-                    data-turbolinks-eval="false"
-                @endif
-            >
-                var AppBridge = window['app-bridge'];
-                var actions = AppBridge.actions;
-                var utils = AppBridge.utilities;
-                var createApp = AppBridge.default;
-                var app = createApp({
-                    apiKey: "{{ \Osiset\ShopifyApp\Util::getShopifyConfig('api_key', $shopDomain ?? Auth::user()->name ) }}",
-                    host: "{{ \Request::get('host') }}",
-                    forceRedirect: true,
-                });
-            </script>
-
+        @if(\Osiset\ShopifyApp\Util::useNativeAppBridge())
             @include('shopify-app::partials.token_handler')
-            @include('shopify-app::partials.flash_messages')
         @endif
-
         @yield('scripts')
     </body>
 </html>
diff --git a/src/resources/views/partials/flash_messages.blade.php b/src/resources/views/partials/flash_messages.blade.php
deleted file mode 100644
index 5298a344..00000000
--- a/src/resources/views/partials/flash_messages.blade.php
+++ /dev/null
@@ -1,22 +0,0 @@
-<script type="text/javascript">
-    document.addEventListener('DOMContentLoaded', function () {
-        var Toast = actions.Toast;
-
-        @if (isset($flashNotice) || request()->has('notice'))
-            var toastNotice = Toast.create(app, {
-                message: "{{ request()->get('notice', $flashNotice ?? null) }}",
-                duration: 3000,
-            });
-            toastNotice.dispatch(Toast.Action.SHOW);
-        @endif
-
-        @if (isset($flashError) || request()->has('error'))
-            var toastNotice = Toast.create(app, {
-                message: "{{ request()->get('error', $flashError ?? null) }}",
-                duration: 3000,
-                isError: true,
-            });
-            toastNotice.dispatch(Toast.Action.SHOW);
-        @endif
-    });
-</script>
diff --git a/src/resources/views/partials/token_handler.blade.php b/src/resources/views/partials/token_handler.blade.php
index a13efaf6..e8fced08 100644
--- a/src/resources/views/partials/token_handler.blade.php
+++ b/src/resources/views/partials/token_handler.blade.php
@@ -1,18 +1,14 @@
-<script data-turbolinks-eval="false">
-    var SESSION_TOKEN_REFRESH_INTERVAL = {{ \Osiset\ShopifyApp\Util::getShopifyConfig('session_token_refresh_interval') }};
-    var LOAD_EVENT = '{{ \Osiset\ShopifyApp\Util::getShopifyConfig('turbo_enabled') ? 'turbolinks:load' : 'DOMContentLoaded' }}';
-
-    // Token updates
-    document.addEventListener(LOAD_EVENT, () => {
-        retrieveToken(app);
-        keepRetrievingToken(app);
+<script>
+    let SESSION_TOKEN_REFRESH_INTERVAL = {{ \Osiset\ShopifyApp\Util::getShopifyConfig('session_token_refresh_interval') }};
+
+    document.addEventListener('DOMContentLoaded', () => {
+        retrieveToken();
+        keepRetrievingToken();
     });
 
-    // Retrieve session token
-    async function retrieveToken(app) {
-        window.sessionToken = await utils.getSessionToken(app);
+    async function retrieveToken() {
+        window.sessionToken = await shopify.idToken();
 
-        // Update everything with the session-token class
         Array.from(document.getElementsByClassName('session-token')).forEach((el) => {
             if (el.hasAttribute('value')) {
                 el.value = window.sessionToken;
@@ -23,8 +19,8 @@
         });
 
         const bearer = `Bearer ${window.sessionToken}`;
+
         if (window.jQuery) {
-            // jQuery
             if (window.jQuery.ajaxSettings.headers) {
                 window.jQuery.ajaxSettings.headers['Authorization'] = bearer;
             } else {
@@ -33,6 +29,7 @@
         }
 
         if (window.Livewire) {
+            // Works only with Livewire 2
             window.Livewire.hook('request', ({options}) => {
                 options.headers['Authorization'] = `Bearer ${window.sessionToken}`;
                 options.headers['Content-Type'] = 'application/json';
@@ -41,20 +38,13 @@
         }
 
         if (window.axios) {
-            // Axios
             window.axios.defaults.headers.common['Authorization'] = bearer;
         }
     }
 
-    // Keep retrieving a session token periodically
-    function keepRetrievingToken(app) {
+    function keepRetrievingToken() {
         setInterval(() => {
-            retrieveToken(app);
+            retrieveToken();
         }, SESSION_TOKEN_REFRESH_INTERVAL);
     }
-
-    document.addEventListener('turbolinks:request-start', (event) => {
-        var xhr = event.data.xhr;
-        xhr.setRequestHeader('Authorization', `Bearer ${window.sessionToken}`);
-    });
 </script>

From 41e641d444325d97f955d8b7c31a6e4e680b5054 Mon Sep 17 00:00:00 2001
From: enmaboya <vita-dubov@yandex.ru>
Date: Sun, 10 Nov 2024 05:07:33 +0400
Subject: [PATCH 3/4] remove unsupported turbolinks

---
 src/Http/Middleware/VerifyShopify.php | 17 +++--------------
 1 file changed, 3 insertions(+), 14 deletions(-)

diff --git a/src/Http/Middleware/VerifyShopify.php b/src/Http/Middleware/VerifyShopify.php
index f2f29cd7..4818e5cb 100644
--- a/src/Http/Middleware/VerifyShopify.php
+++ b/src/Http/Middleware/VerifyShopify.php
@@ -377,20 +377,9 @@ protected function getHmacFromRequest(Request $request): array
      */
     protected function getAccessTokenFromRequest(Request $request): ?string
     {
-        if (Util::getShopifyConfig('turbo_enabled')) {
-            if ($request->bearerToken()) {
-                // Bearer tokens collect.
-                // Turbo does not refresh the page, values are attached to the same header.
-                $bearerTokens = Collection::make(explode(',', $request->header('Authorization', '')));
-                $newestToken = Str::substr(trim($bearerTokens->last()), 7);
-
-                return $newestToken;
-            }
-
-            return $request->get('token');
-        }
-
-        return $this->isApiRequest($request) ? $request->bearerToken() : $request->get('token');
+        return $this->isApiRequest($request)
+            ? $request->bearerToken()
+            : $request->get('token');
     }
 
     /**