Skip to content
Snippets Groups Projects

Start webhook implementation

Merged Christel Loftus requested to merge magento_webhooks into dev
Files
7
+ 68
0
@@ -864,6 +864,11 @@ class BobGo extends AbstractCarrierOnline implements \Magento\Shipping\Model\Car
return UData::RATES_ENDPOINT;
}
private function getWebhookUrl(): string
{
return UData::WEBHOOK_URL;
}
/**
* Perform API Request to Bob Go API and return response.
*
@@ -1310,4 +1315,67 @@ class BobGo extends AbstractCarrierOnline implements \Magento\Shipping\Model\Car
}
return false;
}
public function isWebhookEnabled(): bool
{
$enabled = $this->scopeConfig->getValue(
'carriers/bobgo/enable_webhooks',
\Magento\Store\Model\ScopeInterface::SCOPE_STORE
);
// Cast the value to a boolean
return filter_var($enabled, FILTER_VALIDATE_BOOLEAN);
}
public function triggerWebhookTest(): bool
{
$webhookKey = $this->scopeConfig->getValue(
'carriers/bobgo/webhook_key',
\Magento\Store\Model\ScopeInterface::SCOPE_STORE
);
// Convert the string to a boolean value
$isEnabled = $this->isWebhookEnabled();
$storeId = strval($this->_storeManager->getStore()->getId());
$payload = [
'event' => 'webhook_validation',
'channel_identifier' => $this->getBaseUrl(),
'store_id' => $storeId,
'webhooks_enabled' => $isEnabled,
];
try {
$this->encodeWebhookAndPostRequest($this->getWebhookUrl(), $payload, $storeId, $webhookKey);
$statusCode = $this->curl->getStatus();
$responseBody = $this->curl->getBody();
if ($statusCode != 200) {
throw new LocalizedException(__('Status code from BobGo: %1', $statusCode));
}
} catch (\Exception $e) {
return false;
}
return true;
}
public function encodeWebhookAndPostRequest($url, $data, $storeId, $webhookKey) {
// Generate the HMAC-SHA256 hash as raw binary data
$rawSignature = hash_hmac('sha256', $storeId, $webhookKey, true);
// Encode the binary data in Base64
$signature = base64_encode($rawSignature);
// Set headers and post the data
$this->curl->addHeader('Content-Type', 'application/json');
$this->curl->addHeader('x-m-webhook-signature', $signature);
$payloadJson = json_encode($data);
if ($payloadJson === false) {
throw new \RuntimeException('Failed to encode payload to JSON.');
}
$this->curl->addHeader('Content-Type', 'application/json');
$this->curl->post($url, $payloadJson);
}
}
Loading