hookSuffix = add_submenu_page(
'woocommerce',
__('Afileasy', 'afileasy-for-woocommerce'),
__('Afileasy', 'afileasy-for-woocommerce'),
'manage_woocommerce',
'afileasy-for-woocommerce',
[$this, 'renderPage']
) ?: null;
}
/**
* @param string $hookSuffix
*/
public function enqueueAssets($hookSuffix): void
{
// The test button only renders on this page, and only once connected.
if ($this->hookSuffix === null || $hookSuffix !== $this->hookSuffix) {
return;
}
if (Connection::get() === null) {
return;
}
wp_enqueue_script(
self::HANDLE,
plugins_url('assets/admin.js', AFILEASY_WC_FILE),
[],
AFILEASY_WC_VERSION,
true
);
wp_localize_script(self::HANDLE, 'afileasyWc', [
'ajaxUrl' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce(self::NONCE),
'testing' => __('Testing…', 'afileasy-for-woocommerce'),
'ok' => __('Connection OK', 'afileasy-for-woocommerce'),
'fail' => __('Connection failed', 'afileasy-for-woocommerce'),
]);
}
public function renderPage(): void
{
$connection = Connection::get();
$connected = $connection !== null;
?>
redirectBack('disconnected');
}
$decoded = Connection::decode($raw);
if ($decoded === null) {
$this->redirectBack('invalid');
}
Connection::store($decoded);
Events::forgetRegistration();
Events::queueRegistration();
$this->redirectBack('saved');
}
public function handleTest(): void
{
check_ajax_referer(self::NONCE);
if (! current_user_can('manage_woocommerce')) {
wp_send_json_error('forbidden', 403);
}
$connection = Connection::get();
if ($connection === null) {
wp_send_json_error('not_connected', 400);
}
$response = wp_remote_post(Connection::webhookUrl($connection), [
'headers' => [
'Content-Type' => 'application/json',
'X-Afileasy-Token' => $connection['s'],
],
'body' => wp_json_encode([
'event' => 'ping',
'event_id' => 'ping_'.time(),
'site_url' => site_url(),
]),
'timeout' => 20,
]);
if (is_wp_error($response)) {
wp_send_json_error($response->get_error_message());
}
$code = wp_remote_retrieve_response_code($response);
if ($code >= 200 && $code < 300) {
// Re-announce the store: a merchant testing the connection is also
// the one fixing it, and the coupon credentials may be missing.
Events::queueRegistration();
wp_send_json_success();
}
wp_send_json_error('HTTP '.$code);
}
private function redirectBack(string $status): void
{
wp_safe_redirect(add_query_arg(
['page' => 'afileasy-for-woocommerce', 'afileasy_status' => $status],
admin_url('admin.php')
));
exit;
}
}