Skip to content

Commit 63641fc

Browse files
jczhuoMetasol-loup
andauthored
Adding support for CPI repair endpoint in Magento extension (#662)
* When MiCE overview page load and in MBE update cron job, call repair CPI endpoint to update the latest fields * Run CPI repair in MBE update cron job * Update comment * Address comments * Address comments * Address comments * Revert unintented comment * New Ajax action class to get by the error of extending deprecated class * Trying to get by copy and paste detector * Revert changes to AbstractAjax.php * Revert format change in Setup.php * Revert format change in Setup.php * Revert format change in Setup.php * Try reverting format changes * Fix a typo * Switching away from using * Simplify the imports * Revert white space changes * Revert white space changes * Revert white space changes * Fix static errors * Fix static errors * fixing lint error * indentation --------- Co-authored-by: Paul Kang <[email protected]>
1 parent 9b12569 commit 63641fc

File tree

7 files changed

+261
-5
lines changed

7 files changed

+261
-5
lines changed

app/code/Meta/BusinessExtension/Block/Adminhtml/Setup.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -477,6 +477,16 @@ public function getCustomApiKey(): string
477477
return $this->apiKeyService->getCustomApiKey();
478478
}
479479

480+
/**
481+
* Get repair CPI ajax route
482+
*
483+
* @return mixed
484+
*/
485+
public function getRepairRepairCommercePartnerIntegrationAjaxRoute()
486+
{
487+
return $this->fbeHelper->getUrl('fbeadmin/ajax/RepairCommercePartnerIntegration');
488+
}
489+
480490
/**
481491
* Get MBE Update Installed Config ajax route
482492
*
Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
/**
6+
* Copyright (c) Meta Platforms, Inc. and affiliates.
7+
*
8+
* Licensed under the Apache License, Version 2.0 (the "License");
9+
* you may not use this file except in compliance with the License.
10+
* You may obtain a copy of the License at
11+
*
12+
* http://www.apache.org/licenses/LICENSE-2.0
13+
*
14+
* Unless required by applicable law or agreed to in writing, software
15+
* distributed under the License is distributed on an "AS IS" BASIS,
16+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17+
* See the License for the specific language governing permissions and
18+
* limitations under the License.
19+
*/
20+
21+
namespace Meta\BusinessExtension\Controller\Adminhtml\Ajax;
22+
23+
use Exception;
24+
use Magento\Framework\App\Action\HttpPostActionInterface;
25+
use Magento\Framework\App\RequestInterface;
26+
use Magento\Framework\Controller\Result\JsonFactory;
27+
use Magento\Framework\Exception\LocalizedException;
28+
use Meta\BusinessExtension\Helper\FBEHelper;
29+
use Meta\BusinessExtension\Model\MBEInstalls;
30+
use Psr\Log\LoggerInterface;
31+
32+
class RepairCommercePartnerIntegration implements HttpPostActionInterface
33+
{
34+
/**
35+
* @var JsonFactory
36+
*/
37+
private $resultJsonFactory;
38+
/**
39+
* @var FBEHelper
40+
*/
41+
private $fbeHelper;
42+
43+
/**
44+
* @var MBEInstalls
45+
*/
46+
private $mbeInstalls;
47+
48+
/**
49+
* @var RequestInterface
50+
*/
51+
private $request;
52+
53+
/**
54+
* @param JsonFactory $resultJsonFactory
55+
* @param FBEHelper $fbeHelper
56+
* @param MBEInstalls $mbeInstalls
57+
* @param RequestInterface $request
58+
*/
59+
public function __construct(
60+
JsonFactory $resultJsonFactory,
61+
FBEHelper $fbeHelper,
62+
MBEInstalls $mbeInstalls,
63+
RequestInterface $request,
64+
) {
65+
$this->resultJsonFactory = $resultJsonFactory;
66+
$this->fbeHelper = $fbeHelper;
67+
$this->mbeInstalls = $mbeInstalls;
68+
$this->request = $request;
69+
}
70+
71+
/**
72+
* Execute function
73+
*
74+
* @throws Exception
75+
*/
76+
public function execute()
77+
{
78+
try {
79+
$result = $this->resultJsonFactory->create();
80+
$this->fbeHelper->checkAdminEndpointPermission();
81+
$json = $this->repairCommercePartnerIntegration();
82+
return $result->setData($json);
83+
} catch (Exception $e) {
84+
$this->fbeHelper->logExceptionImmediatelyToMeta(
85+
$e,
86+
[
87+
'store_id' => $this->request->getParam('storeId'),
88+
'event' => 'repair_cpi_fail',
89+
'event_type' => 'save_config'
90+
]
91+
);
92+
throw new LocalizedException(
93+
__('The was an error while trying to repair Meta Commerce Partner Integration.' .
94+
' Please contact admin for more details.')
95+
);
96+
}
97+
}
98+
99+
/**
100+
* Execute function for repairCommercePartnerIntegration
101+
*
102+
* @throws Exception
103+
*/
104+
public function repairCommercePartnerIntegration()
105+
{
106+
$storeId = $this->request->getParam('storeId');
107+
if (empty($storeId)) {
108+
return [
109+
'success' => false,
110+
];
111+
}
112+
$this->mbeInstalls->repairCommercePartnerIntegration($storeId);
113+
return [
114+
'success' => true,
115+
];
116+
}
117+
}

app/code/Meta/BusinessExtension/Cron/UpdateMBESettings.php

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ class UpdateMBESettings
4646
* Construct
4747
*
4848
* @param FBEHelper $fbeHelper
49+
* @param MBEInstalls $mbeInstalls
4950
* @param CollectionFactory $collectionFactory
5051
*/
5152
public function __construct(
@@ -72,9 +73,21 @@ public function execute()
7273
$this->fbeHelper->logExceptionImmediatelyToMeta(
7374
$e,
7475
[
75-
'store_id' => $storeId,
76-
'event' => 'update_mbe_settings_cron',
77-
'event_type' => 'update_mbe_settings'
76+
'store_id' => $storeId,
77+
'event' => 'update_mbe_settings_cron',
78+
'event_type' => 'update_mbe_settings'
79+
]
80+
);
81+
}
82+
try {
83+
$this->mbeInstalls->repairCommercePartnerIntegration($storeId);
84+
} catch (\Exception $e) {
85+
$this->fbeHelper->logExceptionImmediatelyToMeta(
86+
$e,
87+
[
88+
'store_id' => $storeId,
89+
'event' => 'update_mbe_settings_cron_repair_cpi',
90+
'event_type' => 'update_mbe_settings'
7891
]
7992
);
8093
}

app/code/Meta/BusinessExtension/Helper/GraphAPIAdapter.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1068,4 +1068,25 @@ public function getGraphApiVersion(): string
10681068
$latestGraphApiVersion = $this->systemConfig->getGraphAPIVersion();
10691069
return $latestGraphApiVersion ?? $this->graphAPIVersion;
10701070
}
1071+
1072+
/**
1073+
* Call Meta's Repair Commerce Partner Integration endpoint
1074+
*
1075+
* @param string $externalBusinessId
1076+
* @param string $shopDomain
1077+
* @param string $customToken
1078+
* @param string $accessToken
1079+
* @throws GuzzleException
1080+
*/
1081+
public function repairCommercePartnerIntegration($externalBusinessId, $shopDomain, $customToken, $accessToken)
1082+
{
1083+
$request = [
1084+
'access_token' => $accessToken,
1085+
'fbe_external_business_id' => $externalBusinessId,
1086+
'custom_token' => $customToken,
1087+
'shop_domain' => $shopDomain
1088+
];
1089+
$response = $this->callApi('POST', "commerce_partner_integrations_repair", $request);
1090+
return json_decode($response->getBody()->__toString(), true);
1091+
}
10711092
}

app/code/Meta/BusinessExtension/Model/MBEInstalls.php

Lines changed: 78 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,9 +23,11 @@
2323
use GuzzleHttp\Exception\GuzzleException;
2424
use Magento\Framework\Exception\LocalizedException;
2525
use Magento\Store\Model\ScopeInterface;
26+
use Magento\Store\Model\StoreManagerInterface;
2627
use Meta\BusinessExtension\Helper\CatalogConfigUpdateHelper;
2728
use Meta\BusinessExtension\Helper\FBEHelper;
2829
use Meta\BusinessExtension\Helper\GraphAPIAdapter;
30+
use Meta\BusinessExtension\Model\Api\CustomApiKey\ApiKeyService;
2931
use Meta\BusinessExtension\Model\ResourceModel\FacebookInstalledFeature;
3032
use Meta\BusinessExtension\Model\System\Config as SystemConfig;
3133
use Psr\Log\LoggerInterface;
@@ -56,6 +58,18 @@ class MBEInstalls
5658
* @var CatalogConfigUpdateHelper
5759
*/
5860
private CatalogConfigUpdateHelper $catalogConfigUpdateHelper;
61+
/**
62+
* @var ApiKeyService
63+
*/
64+
private ApiKeyService $apiKeyService;
65+
/**
66+
* @var StoreManagerInterface
67+
*/
68+
private StoreManagerInterface $storeManager;
69+
/**
70+
* @var LoggerInterface
71+
*/
72+
private LoggerInterface $logger;
5973

6074
/**
6175
* Construct
@@ -65,19 +79,28 @@ class MBEInstalls
6579
* @param GraphAPIAdapter $graphApiAdapter
6680
* @param FacebookInstalledFeature $installedFeatureResource
6781
* @param CatalogConfigUpdateHelper $catalogConfigUpdateHelper
82+
* @param ApiKeyService $apiKeyService
83+
* @param StoreManagerInterface $storeManager
84+
* @param LoggerInterface $logger
6885
*/
6986
public function __construct(
7087
FBEHelper $fbeHelper,
7188
SystemConfig $systemConfig,
7289
GraphAPIAdapter $graphApiAdapter,
7390
FacebookInstalledFeature $installedFeatureResource,
7491
CatalogConfigUpdateHelper $catalogConfigUpdateHelper,
92+
ApiKeyService $apiKeyService,
93+
StoreManagerInterface $storeManager,
94+
LoggerInterface $logger
7595
) {
7696
$this->fbeHelper = $fbeHelper;
7797
$this->systemConfig = $systemConfig;
7898
$this->graphApiAdapter = $graphApiAdapter;
7999
$this->installedFeatureResource = $installedFeatureResource;
80100
$this->catalogConfigUpdateHelper = $catalogConfigUpdateHelper;
101+
$this->apiKeyService = $apiKeyService;
102+
$this->storeManager = $storeManager;
103+
$this->logger = $logger;
81104
}
82105

83106
/**
@@ -230,7 +253,7 @@ public function saveCommercePartnerIntegrationId($commercePartnerIntegrationId,
230253
$storeId
231254
);
232255
$this->fbeHelper->log("Saved fbe_installs commerce_partner_integration_id ---" .
233-
"{$commercePartnerIntegrationId} for storeID: {$storeId}");
256+
"{$commercePartnerIntegrationId} for storeID: {$storeId}");
234257
}
235258
return $this;
236259
}
@@ -271,7 +294,6 @@ private function saveInstalledFeatures($data, $storeId)
271294
$this->fbeHelper->log("Saved fbe_installs 'installed_features' for storeId: {$storeId}");
272295
}
273296

274-
275297
/**
276298
* Update MBE settings through the 'fbe_installs' API
277299
*
@@ -290,4 +312,58 @@ public function updateMBESettings($storeId)
290312
$this->save($response['data'], $storeId);
291313
$this->fbeHelper->log("Updated MBE Settings for storeId: {$storeId}");
292314
}
315+
316+
/**
317+
* Call Repair CommercePartnerIntegration endpoint
318+
*
319+
* Keep Meta side CommercePartnerIntegration updated with latest info from Magento
320+
*
321+
* @param int $storeId
322+
* @return bool
323+
* @throws \Exception
324+
*/
325+
public function repairCommercePartnerIntegration($storeId): bool
326+
{
327+
try {
328+
$accessToken = $this->systemConfig->getAccessToken($storeId);
329+
$externalBusinessId = $this->systemConfig->getExternalBusinessId($storeId);
330+
$customToken = $this->apiKeyService->getCustomApiKey();
331+
$domain = $this->storeManager->getStore($storeId)->getBaseUrl();
332+
333+
$response = $this->graphApiAdapter->repairCommercePartnerIntegration(
334+
$externalBusinessId,
335+
$domain,
336+
$customToken,
337+
$accessToken
338+
);
339+
if ($response['success'] === true) {
340+
$integrationId = $response['id'];
341+
$existingIntegrationId = $this->systemConfig->getCommercePartnerIntegrationId($storeId);
342+
if ($existingIntegrationId !== null && $existingIntegrationId === $integrationId) {
343+
return true;
344+
}
345+
346+
// For some legacy sellers the Integration ID was obtained from CMS.
347+
// The method should be the ground truth.
348+
// Updating the ID and notify Meta.
349+
if ($existingIntegrationId !== $integrationId) {
350+
$context = [
351+
'store_id' => $storeId,
352+
'event' => 'inconsistent_cpi',
353+
];
354+
$e = new \Exception("Commerce Partner Integration ID inconsistent between Meta and Magento.
355+
Existing ID: $existingIntegrationId and New ID: $integrationId");
356+
$this->fbeHelper->logExceptionImmediatelyToMeta($e, $context);
357+
}
358+
$this->saveCommercePartnerIntegrationId($integrationId, $storeId);
359+
$this->systemConfig->cleanCache();
360+
return true;
361+
} else {
362+
return false;
363+
}
364+
} catch (\Exception $ex) {
365+
$this->logger->error("Error trying to repair Meta Commerce Partner Integration");
366+
throw $ex;
367+
}
368+
}
293369
}

app/code/Meta/BusinessExtension/view/adminhtml/templates/setup.phtml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,9 @@
3535
cleanConfigCacheUrl: '<?= $escaper->escapeHtml($block->getCleanCacheAjaxRoute()) ?>',
3636
commerce_partner_seller_platform_type:
3737
'<?= $escaper->escapeHtml($block->getCommercePartnerSellerPlatformType()) ?>',
38+
repairRepairCommercePartnerIntegrationUrl: '<?=
39+
$escaper->escapeHtml($block->getRepairRepairCommercePartnerIntegrationAjaxRoute())
40+
?>',
3841
currency: '<?= $escaper->escapeHtml($block->getCurrencyCode()) ?>',
3942
customApiKey: '<?= $escaper->escapeHtml($block->getCustomApiKey()) ?>',
4043
debug: true,

app/code/Meta/BusinessExtension/view/adminhtml/web/js/commerce_extension.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,9 +143,25 @@ require(['jquery'], function (jQuery) {
143143
}
144144
}
145145

146+
function repairCommercePartnerIntegration() {
147+
jQuery.ajax({
148+
type: 'post',
149+
url: ajaxify(window.facebookBusinessExtensionConfig.repairRepairCommercePartnerIntegrationUrl),
150+
data: ajaxParam({
151+
storeId: window.facebookBusinessExtensionConfig.storeId,
152+
}),
153+
success: function onSuccess(_data) {
154+
},
155+
error: function () {
156+
console.error('There was error repairing the Meta Commerce Partner Integration');
157+
}
158+
});
159+
}
160+
146161
const commerceIframe = document.getElementById("commerce-extension-iframe");
147162
if (commerceIframe != null) {
148163
window.addEventListener('message', listenForCommerceExtensionMessage);
164+
repairCommercePartnerIntegration();
149165
}
150166

151167
const resetLink = document.getElementById('commerce-extension-reset-link');

0 commit comments

Comments
 (0)