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

Adding APP_UNINSTALLED webhook #19

Merged
merged 1 commit into from
May 17, 2021
Merged
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
5 changes: 3 additions & 2 deletions app/Http/Middleware/VerifyCsrfToken.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ class VerifyCsrfToken extends Middleware
*
* @var array
*/
protected $except = ['graphql'
//
protected $except = [
'graphql',
'webhooks',
];
}
18 changes: 18 additions & 0 deletions app/Lib/Handlers/AppUninstalled.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

declare(strict_types=1);

namespace App\Lib\Handlers;

use Illuminate\Support\Facades\Log;
use Shopify\Webhooks\Handler;
use App\Models\Session;

class AppUninstalled implements Handler
{
public function handle(string $topic, string $shop, array $body): void
{
Log::debug("App was uninstalled from $shop - removing all sessions");
Session::where('shop', $shop)->delete();
}
}
7 changes: 6 additions & 1 deletion app/Providers/AppServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,12 @@
namespace App\Providers;

use App\Lib\DbSessionStorage;
use App\Lib\Handlers\AppUninstalled;
use Illuminate\Support\ServiceProvider;
use Shopify\Context;
use Illuminate\Support\Facades\URL;
use Shopify\Context;
use Shopify\Webhooks\Registry;
use Shopify\Webhooks\Topics;

class AppServiceProvider extends ServiceProvider
{
Expand Down Expand Up @@ -36,5 +39,7 @@ public function boot()
);

URL::forceScheme('https');

Registry::addHandler(Topics::APP_UNINSTALLED, new AppUninstalled());
}
}
43 changes: 37 additions & 6 deletions routes/web.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,11 @@
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\Log;
use Shopify\Context;
use Shopify\Auth\OAuth;
use Shopify\Utils;
use Shopify\Auth\OAuth;
use Shopify\Clients\HttpHeaders;
use Shopify\Webhooks\Registry;
use Shopify\Webhooks\Topics;

/*
|--------------------------------------------------------------------------
Expand Down Expand Up @@ -82,17 +85,45 @@ function(Shopify\Auth\OAuthCookie $cookie) {
});

Route::get('/auth/callback', function (Request $request) {
Log::info($request->cookie(OAuth::SESSION_ID_COOKIE_NAME));
OAuth::callback(
[OAuth::SESSION_ID_COOKIE_NAME => $request->cookie(OAuth::SESSION_ID_COOKIE_NAME)],
$request->query()
);
$session = OAuth::callback($request->cookie(), $request->query());

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

$response = Registry::register(
path: '/webhooks',
topic: Topics::APP_UNINSTALLED,
shop: $shop,
accessToken: $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)
);
}
Comment on lines +93 to +106
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe we can think of a way to pull this code into the library. Webhooks path could be a configuration. We already know the topics from the Registery::addHandler. Not part of this PR though

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What I mean, we don't need to explicitly pass arguments to register. Maybe we can have a method registerAll that would register all webhooks.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hm, interesting, that's a really good idea. I just wonder if it wouldn't 'hide' the topics a little bit (and not sure if that's even a problem). We could also just make that an app method, though it's probably generic enough that it can go into the lib.


return redirect("?" . http_build_query(['host' => $host, 'shop' => $shop]));
});

Route::post('/graphql', function (Request $request) {
$result = Utils::graphqlProxy($request->header(), $request->cookie(), $request->getContent());
return response($result->getDecodedBody())->withHeaders($result->getHeaders());
});

Route::post('/webhooks', function (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 (\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);
}
});
57 changes: 32 additions & 25 deletions tests/Feature/CallbackTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,14 @@ class CallbackTest extends BaseTestCase
],
];

private array $webhookCheckEmpty = [
'data' => [
'webhookSubscriptions' => [
'edges' => [],
],
],
];

public function testCallBackForOfflineSession()
{
$offlineSession = new Session(
Expand All @@ -49,22 +57,21 @@ public function testCallBackForOfflineSession()
// Session is already stored in the OAuth::begin
Context::$SESSION_STORAGE->storeSession($offlineSession);

$client = $this->mockClient();

$oauthTokenUrl = "https://test-shop.myshopify.io/admin/oauth/access_token";
$graphqlUrl = "https://test-shop.myshopify.io/admin/api/unstable/graphql.json";

$client->expects($this->exactly(1))
$client = $this->mockClient();
$client->expects($this->exactly(3))
->method('sendRequest')
->with(
$this->callback(
fn($request) => $request->getUri() == "https://test-shop.myshopify.io/admin/oauth/access_token"
)
->withConsecutive(
[$this->callback(fn($request) => $request->getUri() == $oauthTokenUrl)],
[$this->callback(fn($request) => $request->getUri() == $graphqlUrl)],
[$this->callback(fn($request) => $request->getUri() == $graphqlUrl)],
)
->willReturn(
new Response(
status: 200,
headers: [],
body: json_encode($this->offlineResponse)
)
->willReturnOnConsecutiveCalls(
new Response(status: 200, headers: [], body: json_encode($this->onlineResponse)),
new Response(status: 200, headers: [], body: json_encode($this->webhookCheckEmpty)),
new Response(status: 200, headers: [], body: '[]'),
);

$query = $this->requestQueryParameters();
Expand Down Expand Up @@ -107,21 +114,21 @@ public function testCallBackForOnlineSession()

Context::$SESSION_STORAGE->storeSession($onlineSession);

$client = $this->mockClient();
$oauthTokenUrl = "https://test-shop.myshopify.io/admin/oauth/access_token";
$graphqlUrl = "https://test-shop.myshopify.io/admin/api/unstable/graphql.json";

$client->expects($this->exactly(1))
$client = $this->mockClient();
$client->expects($this->exactly(3))
->method('sendRequest')
->with(
$this->callback(
fn($request) => $request->getUri() == "https://test-shop.myshopify.io/admin/oauth/access_token"
)
->withConsecutive(
[$this->callback(fn($request) => $request->getUri() == $oauthTokenUrl)],
[$this->callback(fn($request) => $request->getUri() == $graphqlUrl)],
[$this->callback(fn($request) => $request->getUri() == $graphqlUrl)],
)
->willReturn(
new Response(
status: 200,
headers: [],
body: json_encode($this->onlineResponse)
)
->willReturnOnConsecutiveCalls(
new Response(status: 200, headers: [], body: json_encode($this->onlineResponse)),
new Response(status: 200, headers: [], body: json_encode($this->webhookCheckEmpty)),
new Response(status: 200, headers: [], body: '[]'),
);

$query = $this->requestQueryParameters();
Expand Down
49 changes: 49 additions & 0 deletions tests/Feature/WebhookTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
<?php

namespace Tests\Feature;

use Illuminate\Foundation\Testing\RefreshDatabase;
use PHPUnit\Framework\MockObject\MockObject;
use Shopify\Clients\HttpHeaders;
use Shopify\Context;
use Shopify\Webhooks\Handler;
use Shopify\Webhooks\Registry;
use Shopify\Webhooks\Topics;

class WebhookTest extends BaseTestCase
{
use RefreshDatabase;

private string $domain = "test-shop.myshopify.io";

public function testWebhookIsProcessed()
{
$shop = $this->domain;
$topic = Topics::APP_UNINSTALLED;
$body = ['dummy' => 'data'];

/** @var MockObject|Handler */
$mock = $this->getMockBuilder(Handler::class)
->getMock();
$mock->expects($this->once())
->method('handle')
->with($topic, $shop, $body);

Registry::addHandler($topic, $mock);

$hmac = base64_encode(hash_hmac('sha256', json_encode($body), Context::$API_SECRET_KEY, true));
$response = $this
->json(
method: 'POST',
uri: "/webhooks",
data: $body,
headers: [
HttpHeaders::X_SHOPIFY_TOPIC => $topic,
HttpHeaders::X_SHOPIFY_DOMAIN => $shop,
HttpHeaders::X_SHOPIFY_HMAC => $hmac,
],
);

$response->assertStatus(200);
}
}