Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: update the code as the laravel best practices #524

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 64 additions & 0 deletions web/app/Http/Controllers/Shopify/AuthController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
<?php

namespace App\Http\Controllers\Shopify;

use App\Http\Controllers\Controller;
use App\Lib\AuthRedirection;
use App\Lib\EnsureBilling;
use App\Models\Session;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;
use Shopify\Auth\OAuth;
use Shopify\Utils;
use Shopify\Webhooks\Registry;
use Shopify\Webhooks\Topics;

/**
* @author Muhammad Huzaifa <[email protected]>
*/
class AuthController extends Controller
{
public function index(Request $request)
{
$shop = Utils::sanitizeShopDomain($request->query('shop'));

// Delete any previously created OAuth sessions that were not completed (don't have an access token)
Session::where('shop', $shop)->where('access_token', null)->delete();

return AuthRedirection::redirect($request);
}

public function callback(Request $request)
{
$session = OAuth::callback(
$request->cookie(),
$request->query(),
['App\Lib\CookieHandler', 'saveShopifyCookie'],
);

$host = $request->query('host');
$shop = Utils::sanitizeShopDomain($request->query('shop'));

$response = Registry::register('/api/webhooks', Topics::APP_UNINSTALLED, $shop, $session->getAccessToken());
if ($response->isSuccess()) {
Log::debug("Registered APP_UNINSTALLED webhook for shop $shop");
} else {
Log::error(
"Failed to register APP_UNINSTALLED webhook for shop $shop with response body: ".
print_r($response->getBody(), true)
);
}

$redirectUrl = Utils::getEmbeddedAppUrl($host);
if (Config::get('shopify.billing.required')) {
[$hasPayment, $confirmationUrl] = EnsureBilling::check($session, Config::get('shopify.billing'));

if (! $hasPayment) {
$redirectUrl = $confirmationUrl;
}
}

return redirect($redirectUrl);
}
}
27 changes: 27 additions & 0 deletions web/app/Http/Controllers/Shopify/FallbackController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

namespace App\Http\Controllers\Shopify;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Shopify\Context;
use Shopify\Utils;

/**
* @author Muhammad Huzaifa <[email protected]>
*/
class FallbackController extends Controller
{
public function __invoke(Request $request)
{
if (Context::$IS_EMBEDDED_APP && $request->query('embedded', false) === '1') {
if (env('APP_ENV') === 'production') {
return file_get_contents(public_path('index.html'));
} else {
return file_get_contents(base_path('frontend/index.html'));
}
}

return redirect(Utils::getEmbeddedAppUrl($request->query('host', null)).'/'.$request->path());
}
}
57 changes: 57 additions & 0 deletions web/app/Http/Controllers/Shopify/ProductController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<?php

namespace App\Http\Controllers\Shopify;

use App\Http\Controllers\Controller;
use App\Lib\ProductCreator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Shopify\Clients\Rest;

/**
* @author Muhammad Huzaifa <[email protected]>
*/
class ProductController extends Controller
{
public function count(Request $request)
{
/** @var \Shopify\Auth\Session */
$session = $request->get('shopifySession'); // Provided by the shopify.auth middleware, guaranteed to be active

$client = new Rest($session->getShop(), $session->getAccessToken());
$result = $client->get('products/count');

return response($result->getDecodedBody());
}

public function store(Request $request)
{
/** @var \Shopify\Auth\Session */
$session = $request->get('shopifySession'); // Provided by the shopify.auth middleware, guaranteed to be active

$success = $code = $error = null;
try {
ProductCreator::call($session, 5);
$success = true;
$code = 200;
$error = null;
} catch (\Exception $e) {
$success = false;

if ($e instanceof ShopifyProductCreatorException) {
$code = $e->response->getStatusCode();
$error = $e->response->getDecodedBody();
if (array_key_exists('errors', $error)) {
$error = $error['errors'];
}
} else {
$code = 500;
$error = $e->getMessage();
}

Log::error("Failed to create products: $error");
} finally {
return response()->json(['success' => $success, 'error' => $error], $code);
}
}
}
38 changes: 38 additions & 0 deletions web/app/Http/Controllers/Shopify/WebhookController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php

namespace App\Http\Controllers\Shopify;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Shopify\Clients\HttpHeaders;
use Shopify\Exception\InvalidWebhookException;
use Shopify\Webhooks\Registry;

/**
* @author Muhammad Huzaifa <[email protected]>
*/
class WebhookController extends Controller
{
public function __invoke(Request $request)
{
try {
$topic = $request->header(HttpHeaders::X_SHOPIFY_TOPIC, '');

$response = Registry::process($request->header(), $request->getContent());
if (! $response->isSuccess()) {
Log::error("Failed to process '$topic' webhook: {$response->getErrorMessage()}");

return response()->json(['message' => "Failed to process '$topic' webhook"], 500);
}
} catch (InvalidWebhookException $e) {
Log::error("Got invalid webhook request for topic '$topic': {$e->getMessage()}");

return response()->json(['message' => "Got invalid webhook request for topic '$topic'"], 401);
} catch (\Exception $e) {
Log::error("Got an exception when handling '$topic' webhook: {$e->getMessage()}");

return response()->json(['message' => "Got an exception when handling '$topic' webhook"], 500);
}
}
}
53 changes: 1 addition & 52 deletions web/app/Providers/AppServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,7 @@

namespace App\Providers;

use App\Lib\DbSessionStorage;
use App\Lib\Handlers\AppUninstalled;
use App\Lib\Handlers\Privacy\CustomersDataRequest;
use App\Lib\Handlers\Privacy\CustomersRedact;
use App\Lib\Handlers\Privacy\ShopRedact;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\URL;
use Shopify\Context;
use Shopify\ApiVersion;
use Shopify\Webhooks\Registry;
use Shopify\Webhooks\Topics;

class AppServiceProvider extends ServiceProvider
{
Expand All @@ -26,49 +16,8 @@ public function register()
//
}

/**
* Bootstrap any application services.
*
* @return void
* @throws \Shopify\Exception\MissingArgumentException
*/
public function boot()
{
$host = str_replace('https://', '', env('HOST', 'not_defined'));

$customDomain = env('SHOP_CUSTOM_DOMAIN', null);
Context::initialize(
env('SHOPIFY_API_KEY', 'not_defined'),
env('SHOPIFY_API_SECRET', 'not_defined'),
env('SCOPES', 'not_defined'),
$host,
new DbSessionStorage(),
ApiVersion::LATEST,
true,
false,
null,
'',
null,
(array)$customDomain,
);

URL::forceRootUrl("https://$host");
URL::forceScheme('https');

Registry::addHandler(Topics::APP_UNINSTALLED, new AppUninstalled());

/*
* This sets up the mandatory privacy webhooks. You’ll need to fill in the endpoint to be used by your app in
* the “Privacy webhooks” section in the “App setup” tab, and customize the code when you store customer data
* in the handlers being registered below.
*
* More details can be found on shopify.dev:
* https://shopify.dev/docs/apps/webhooks/configuration/mandatory-webhooks
*
* Note that you'll only receive these webhooks if your app has the relevant scopes as detailed in the docs.
*/
Registry::addHandler('CUSTOMERS_DATA_REQUEST', new CustomersDataRequest());
Registry::addHandler('CUSTOMERS_REDACT', new CustomersRedact());
Registry::addHandler('SHOP_REDACT', new ShopRedact());
//
}
}
77 changes: 77 additions & 0 deletions web/app/Providers/ShopifyServiceProvider.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
<?php

namespace App\Providers;

use App\Lib\DbSessionStorage;
use App\Lib\Handlers\AppUninstalled;
use App\Lib\Handlers\Privacy\CustomersDataRequest;
use App\Lib\Handlers\Privacy\CustomersRedact;
use App\Lib\Handlers\Privacy\ShopRedact;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\ServiceProvider;
use Shopify\ApiVersion;
use Shopify\Context;
use Shopify\Webhooks\Registry;
use Shopify\Webhooks\Topics;

/**
* @author Muhammad Huzaifa <[email protected]>
*/
class ShopifyServiceProvider extends ServiceProvider
{
/**
* Register services.
*
* @return void
*/
public function register()
{
//
}

/**
* Bootstrap shopify service.
*
* @return void
*
* @throws \Shopify\Exception\MissingArgumentException
*/
public function boot()
{
$host = str_replace('https://', '', config('shopify.host'));

Context::initialize(
config('shopify.api_key'),
config('shopify.api_secret'),
config('shopify.scopes'),
$host,
new DbSessionStorage(),
ApiVersion::LATEST,
true,
false,
null,
'',
null,
(array) config('shopify.shop_custom_domain'),
);

URL::forceRootUrl("https://$host");
URL::forceScheme('https');

Registry::addHandler(Topics::APP_UNINSTALLED, new AppUninstalled());

/*
* This sets up the mandatory privacy webhooks. You’ll need to fill in the endpoint to be used by your app in
* the “Privacy webhooks” section in the “App setup” tab, and customize the code when you store customer data
* in the handlers being registered below.
*
* More details can be found on shopify.dev:
* https://shopify.dev/docs/apps/webhooks/configuration/mandatory-webhooks
*
* Note that you'll only receive these webhooks if your app has the relevant scopes as detailed in the docs.
*/
Registry::addHandler('CUSTOMERS_DATA_REQUEST', new CustomersDataRequest());
Registry::addHandler('CUSTOMERS_REDACT', new CustomersRedact());
Registry::addHandler('SHOP_REDACT', new ShopRedact());
}
}
1 change: 1 addition & 0 deletions web/config/app.php
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,7 @@
// App\Providers\BroadcastServiceProvider::class,
App\Providers\EventServiceProvider::class,
App\Providers\RouteServiceProvider::class,
App\Providers\ShopifyServiceProvider::class,

],

Expand Down
Loading
Loading