WP_REST_Server::CREATABLE, 'callback' => [__CLASS__, 'handle'], // Only someone who can already read the API key on the Settings tab. 'permission_callback' => function () { return current_user_can('manage_options'); }, 'args' => [ 'name' => ['required' => true, 'type' => 'string'], 'email' => ['required' => true, 'type' => 'string'], 'message' => ['required' => true, 'type' => 'string'], ], ] ); } public static function handle(WP_REST_Request $request) { // Plain text only: this ends up in the support team's inbox. $name = trim(sanitize_text_field((string) $request->get_param('name'))); $email = trim(sanitize_email((string) $request->get_param('email'))); $message = trim(sanitize_textarea_field((string) $request->get_param('message'))); if ($name === '' || $message === '') { return new WP_Error('atw_support_incomplete', __('Please fill in every field.', 'addtowallet-for-bookly'), ['status' => 400]); } if (!is_email($email)) { return new WP_Error('atw_support_email', __('That email address does not look right.', 'addtowallet-for-bookly'), ['status' => 400]); } /** * The site and plugin version ride along in the message: a merchant writing in * rarely thinks to say which site or build they are on, and support cannot ask * without a round trip. */ $context = sprintf( "\n\n---\nSent from the Bookly WordPress plugin v%s\nSite: %s", ATW_BOOKLY_VERSION, home_url() ); $response = wp_remote_post( ATW_BOOKLY_API_BASE . '/api/admin/contactus', [ 'timeout' => 20, 'headers' => ['Content-Type' => 'application/json'], 'body' => wp_json_encode([ 'formData' => [ 'name' => $name, 'email' => $email, 'message' => $message . $context, ], 'attachments' => [], ]), ] ); if (is_wp_error($response)) { return new WP_Error('atw_support_unreachable', $response->get_error_message(), ['status' => 502]); } $code = (int) wp_remote_retrieve_response_code($response); if ($code < 200 || $code >= 300) { return new WP_Error( 'atw_support_failed', /* translators: %d: HTTP status code returned by AddToWallet */ sprintf(__('AddToWallet answered %d.', 'addtowallet-for-bookly'), $code), ['status' => 502] ); } return rest_ensure_response(['sent' => true]); } /** * The "Message us" card on the Help tab. The current user is a reasonable guess at who * is writing, so the name and email are prefilled rather than asked for twice. */ public static function render() { $user = wp_get_current_user(); ?>