; ", which makes every plugin * on every site look identical in AddToWallet's logs and analytics. The API * parses the "AddToWallet-/" prefix, so this is also what attributes * passes from sites still running a build that predates the `source` field. */ private static function user_agent() { return 'AddToWallet-Bookly/' . ATW_BOOKLY_VERSION . '; ' . home_url(); } /** * @return array|WP_Error ['card_id' => string, 'share_url' => string] */ public static function create_pass(array $payload, array $settings) { if (empty($settings['api_key'])) { return new WP_Error( 'atw_no_api_key', __('No AddToWallet API key is configured.', 'addtowallet-for-bookly') ); } $response = wp_remote_post( untrailingslashit(ATW_BOOKLY_API_BASE) . '/api/card/create', [ 'timeout' => 30, 'user-agent' => self::user_agent(), 'headers' => [ 'Content-Type' => 'application/json', 'apikey' => $settings['api_key'], ], 'body' => wp_json_encode($payload), ] ); if (is_wp_error($response)) { return $response; } $code = wp_remote_retrieve_response_code($response); $body = json_decode(wp_remote_retrieve_body($response), true); if ($code < 200 || $code >= 300) { $message = ''; if (is_array($body)) { // The API reports validation problems under 'error' and other failures // under 'msg' or 'message'. foreach (['error', 'msg', 'message'] as $key) { if (!empty($body[$key]) && is_string($body[$key])) { $message = $body[$key]; break; } } } if ($message === '') { $message = sprintf( /* translators: %d: HTTP status code */ __('Pass creation failed with HTTP %d.', 'addtowallet-for-bookly'), (int) $code ); } return new WP_Error('atw_api_error', $message, ['status' => $code]); } $card_id = isset($body['cardId']) ? (string) $body['cardId'] : ''; $share_url = isset($body['shareUrl']) ? (string) $body['shareUrl'] : ''; if ($share_url === '' && $card_id !== '') { $share_url = untrailingslashit(ATW_BOOKLY_API_BASE) . '/card/' . $card_id; } if ($share_url === '') { return new WP_Error( 'atw_api_no_url', __('The API did not return a pass URL.', 'addtowallet-for-bookly') ); } return ['card_id' => $card_id, 'share_url' => $share_url]; } /** * Marks an issued pass as expired, so it moves to the expired section of the * customer's wallet. * * Deliberately not the delete endpoint: that sets deleted alongside EXPIRED and * drops the pass out of the account's pass list and stats. * * The logo has to be sent again. The API merges the body over the stored pass, but * its incoming-data cleanup runs first and, finding no logoUrl, substitutes its own * placeholder, which is unreachable and fails with "Image cannot be loaded ... * logo-placeholder.png" — verified against a live 400. A stateType-only body * therefore never expires anything. * * @param string $logo_url The logo the pass was created with. * @return true|WP_Error */ public static function expire_pass($card_id, array $settings, $logo_url = '') { if (empty($settings['api_key'])) { return new WP_Error( 'atw_no_api_key', __('No AddToWallet API key is configured.', 'addtowallet-for-bookly') ); } $card_id = trim((string) $card_id); if ($card_id === '') { return new WP_Error( 'atw_no_card_id', __('No pass id was stored for this booking.', 'addtowallet-for-bookly') ); } $response = wp_remote_request( untrailingslashit(ATW_BOOKLY_API_BASE) . '/api/card/edit/' . rawurlencode($card_id), [ 'method' => 'PUT', 'timeout' => 30, 'user-agent' => self::user_agent(), 'headers' => [ 'Content-Type' => 'application/json', 'apikey' => $settings['api_key'], ], 'body' => wp_json_encode(self::expire_body($logo_url)), ] ); if (is_wp_error($response)) { return $response; } $code = wp_remote_retrieve_response_code($response); if ($code < 200 || $code >= 300) { $body = json_decode(wp_remote_retrieve_body($response), true); $message = ''; if (is_array($body)) { foreach (['error', 'msg', 'message'] as $key) { if (!empty($body[$key]) && is_string($body[$key])) { $message = $body[$key]; break; } } } if ($message === '') { $message = sprintf( /* translators: %d: HTTP status code */ __('Expiring the pass failed with HTTP %d.', 'addtowallet-for-bookly'), (int) $code ); } return new WP_Error('atw_api_error', $message, ['status' => $code]); } return true; } /** * Replaces an issued pass's contents with a freshly built payload, so the pass on the * customer's phone follows a rescheduled appointment. Same endpoint as expiring; the * API merges the body over the stored pass and pushes the change to devices. * * @return true|WP_Error */ public static function update_pass($card_id, array $payload, array $settings) { if (empty($settings['api_key'])) { return new WP_Error('atw_no_api_key', __('No AddToWallet API key is configured.', 'addtowallet-for-bookly')); } $card_id = trim((string) $card_id); if ($card_id === '') { return new WP_Error('atw_no_card_id', __('No pass id was stored for this booking.', 'addtowallet-for-bookly')); } $response = wp_remote_request( untrailingslashit(ATW_BOOKLY_API_BASE) . '/api/card/edit/' . rawurlencode($card_id), [ 'method' => 'PUT', 'timeout' => 30, 'user-agent' => self::user_agent(), 'headers' => [ 'Content-Type' => 'application/json', 'apikey' => $settings['api_key'], ], 'body' => wp_json_encode($payload), ] ); if (is_wp_error($response)) { return $response; } $code = wp_remote_retrieve_response_code($response); if ($code < 200 || $code >= 300) { $body = json_decode(wp_remote_retrieve_body($response), true); $message = ''; if (is_array($body)) { foreach (['error', 'msg', 'message'] as $key) { if (!empty($body[$key]) && is_string($body[$key])) { $message = $body[$key]; break; } } } if ($message === '') { /* translators: %d: HTTP status code */ $message = sprintf(__('Updating the pass failed with HTTP %d.', 'addtowallet-for-bookly'), (int) $code); } return new WP_Error('atw_api_error', $message, ['status' => $code]); } return true; } /** The expiry body: the state change, plus the logo whenever one is known. */ private static function expire_body($logo_url) { $body = ['stateType' => 'EXPIRED']; $logo_url = trim((string) $logo_url); if ($logo_url !== '') { $body['logoUrl'] = $logo_url; } return $body; } /** * The account's credit balance, for the Settings tab. Cached for five minutes: the * screen is reloaded on every save and the balance does not move that fast. The * cache key hashes the API key so replacing the key never shows the old account's * balance. * * @return array|WP_Error paid, paid_total, free, free_total, plus remaining/total as the sums */ private static function remember_failure($cache_key, WP_Error $error) { set_transient($cache_key, $error, MINUTE_IN_SECONDS); return $error; } public static function get_credits(array $settings, $force = false) { if (empty($settings['api_key'])) { return new WP_Error('atw_no_api_key', __('No AddToWallet API key is configured.', 'addtowallet-for-bookly')); } $cache_key = 'atw_bookly_credits_' . substr(md5($settings['api_key']), 0, 12); if (!$force) { $cached = get_transient($cache_key); // Either a balance or a recent failure. Failures are cached too, for one // minute: with the API down, every settings-page load would otherwise block // for the full timeout before rendering. if ($cached instanceof WP_Error) { return $cached; } if (is_array($cached) && isset($cached['paid'], $cached['free'])) { return $cached; } } $response = wp_remote_get( untrailingslashit(ATW_BOOKLY_API_BASE) . '/api/payment/usage', [ 'timeout' => 10, 'user-agent' => self::user_agent(), 'headers' => ['apikey' => $settings['api_key']], ] ); if (is_wp_error($response)) { return self::remember_failure($cache_key, $response); } $code = (int) wp_remote_retrieve_response_code($response); $body = json_decode(wp_remote_retrieve_body($response), true); if ($code === 401 || $code === 403) { return self::remember_failure($cache_key, new WP_Error('atw_bad_api_key', __('AddToWallet did not accept this API key.', 'addtowallet-for-bookly'))); } $pools = is_array($body) && !empty($body['data']['breakdown']) ? $body['data']['breakdown'] : null; if ($code < 200 || $code >= 300 || !is_array($pools) || !isset($pools['premium']['remaining'], $pools['nonPremium']['remaining'])) { return self::remember_failure($cache_key, new WP_Error( 'atw_credits_failed', /* translators: %d: HTTP status code */ sprintf(__('Could not read the balance (HTTP %d).', 'addtowallet-for-bookly'), $code) )); } /** * Two pools, and the app draws from paid first then free (see * UserCreditService::reserveCredit), so a merchant with no paid credits but free * passes left can still issue passes. Reporting only the paid pool would tell * them they are out when they are not. */ $credits = [ 'paid' => max(0, (int) $pools['premium']['remaining']), 'paid_total' => (int) $pools['premium']['total'], 'free' => max(0, (int) $pools['nonPremium']['remaining']), 'free_total' => (int) $pools['nonPremium']['total'], ]; $credits['remaining'] = $credits['paid'] + $credits['free']; $credits['total'] = $credits['paid_total'] + $credits['free_total']; set_transient($cache_key, $credits, 5 * MINUTE_IN_SECONDS); return $credits; } }