|
| 1 | +<?php |
| 2 | +/** |
| 3 | + * GA4 Admin API client backed by Newspack's Google OAuth credentials. |
| 4 | + * |
| 5 | + * Mirrors the subset of the GA4 Admin API surface used by |
| 6 | + * GA4_Custom_Dimensions (list + create custom dimensions), but calls |
| 7 | + * analyticsadmin.googleapis.com directly with a Bearer token obtained |
| 8 | + * through Newspack's own OAuth proxy rather than delegating to Site Kit. |
| 9 | + * |
| 10 | + * @package Newspack |
| 11 | + */ |
| 12 | + |
| 13 | +namespace Newspack; |
| 14 | + |
| 15 | +defined( 'ABSPATH' ) || exit; |
| 16 | + |
| 17 | +/** |
| 18 | + * Newspack-OAuth-backed GA4 Admin API client. |
| 19 | + */ |
| 20 | +final class Google_OAuth_GA4_Client { |
| 21 | + const BASE_URL = 'https://analyticsadmin.googleapis.com/v1beta'; |
| 22 | + |
| 23 | + /** |
| 24 | + * OAuth scope required to create GA4 custom dimensions via the Admin API. |
| 25 | + */ |
| 26 | + const EDIT_SCOPE = 'https://www.googleapis.com/auth/analytics.edit'; |
| 27 | + |
| 28 | + /** |
| 29 | + * OAuth access token. |
| 30 | + * |
| 31 | + * @var string |
| 32 | + */ |
| 33 | + private $access_token; |
| 34 | + |
| 35 | + /** |
| 36 | + * Constructor. |
| 37 | + * |
| 38 | + * @param string $access_token OAuth access token. |
| 39 | + */ |
| 40 | + private function __construct( $access_token ) { |
| 41 | + $this->access_token = $access_token; |
| 42 | + } |
| 43 | + |
| 44 | + /** |
| 45 | + * Build a client using Newspack's saved Google OAuth credentials. |
| 46 | + * |
| 47 | + * Returns null if the OAuth proxy is not configured, no credentials are |
| 48 | + * saved, or the token can't be resolved. Callers should treat null as a |
| 49 | + * signal to fall back to another auth route. |
| 50 | + * |
| 51 | + * @return self|null |
| 52 | + */ |
| 53 | + public static function build() { |
| 54 | + if ( ! class_exists( __NAMESPACE__ . '\\Google_OAuth' ) ) { |
| 55 | + return null; |
| 56 | + } |
| 57 | + if ( ! Google_OAuth::is_oauth_configured() ) { |
| 58 | + return null; |
| 59 | + } |
| 60 | + $credentials = Google_OAuth::get_oauth2_credentials(); |
| 61 | + if ( ! $credentials ) { |
| 62 | + return null; |
| 63 | + } |
| 64 | + $token = $credentials->getAccessToken(); |
| 65 | + if ( empty( $token ) ) { |
| 66 | + return null; |
| 67 | + } |
| 68 | + return new self( $token ); |
| 69 | + } |
| 70 | + |
| 71 | + /** |
| 72 | + * Whether Newspack's stored Google OAuth token currently carries the |
| 73 | + * `analytics.edit` scope. Tokens issued before that scope was added to |
| 74 | + * Google_OAuth::REQUIRED_SCOPES, or after a publisher revoked it, will not – |
| 75 | + * in which case the Admin API rejects writes with a 403 and callers should |
| 76 | + * fall back to another auth route rather than this client. |
| 77 | + * |
| 78 | + * @return bool |
| 79 | + */ |
| 80 | + public static function has_edit_scope() { |
| 81 | + return class_exists( __NAMESPACE__ . '\\Google_OAuth' ) |
| 82 | + && Google_OAuth::token_has_scope( self::EDIT_SCOPE ); |
| 83 | + } |
| 84 | + |
| 85 | + /** |
| 86 | + * List all custom dimensions on a GA4 property. |
| 87 | + * |
| 88 | + * @param string $property_id GA4 property ID (numeric, no "properties/" prefix). |
| 89 | + * @return array<int,array{name:string,parameterName:string,displayName:string,scope:string}> |
| 90 | + * @throws \RuntimeException On HTTP or API error. |
| 91 | + */ |
| 92 | + public function list_custom_dimensions( $property_id ) { |
| 93 | + $dimensions = []; |
| 94 | + $page_token = null; |
| 95 | + do { |
| 96 | + $url = self::BASE_URL . '/properties/' . rawurlencode( $property_id ) . '/customDimensions'; |
| 97 | + if ( $page_token ) { |
| 98 | + $url = add_query_arg( 'pageToken', $page_token, $url ); |
| 99 | + } |
| 100 | + $body = $this->request( 'GET', $url ); |
| 101 | + $items = isset( $body['customDimensions'] ) && is_array( $body['customDimensions'] ) ? $body['customDimensions'] : []; |
| 102 | + foreach ( $items as $dimension ) { |
| 103 | + $dimensions[] = [ |
| 104 | + 'name' => isset( $dimension['name'] ) ? $dimension['name'] : '', |
| 105 | + 'parameterName' => isset( $dimension['parameterName'] ) ? $dimension['parameterName'] : '', |
| 106 | + 'displayName' => isset( $dimension['displayName'] ) ? $dimension['displayName'] : '', |
| 107 | + 'scope' => isset( $dimension['scope'] ) ? $dimension['scope'] : '', |
| 108 | + ]; |
| 109 | + } |
| 110 | + $page_token = isset( $body['nextPageToken'] ) ? $body['nextPageToken'] : null; |
| 111 | + } while ( $page_token ); |
| 112 | + return $dimensions; |
| 113 | + } |
| 114 | + |
| 115 | + /** |
| 116 | + * Create an event-scoped custom dimension on a GA4 property. |
| 117 | + * |
| 118 | + * @param string $property_id GA4 property ID. |
| 119 | + * @param string $parameter_name Event parameter name. |
| 120 | + * @param string $display_name Display name shown in the GA4 UI. |
| 121 | + * @return array Decoded API response. |
| 122 | + * @throws \RuntimeException On HTTP or API error. |
| 123 | + */ |
| 124 | + public function create_custom_dimension( $property_id, $parameter_name, $display_name ) { |
| 125 | + $url = self::BASE_URL . '/properties/' . rawurlencode( $property_id ) . '/customDimensions'; |
| 126 | + $payload = [ |
| 127 | + 'parameterName' => $parameter_name, |
| 128 | + 'displayName' => $display_name, |
| 129 | + 'scope' => 'EVENT', |
| 130 | + ]; |
| 131 | + return $this->request( 'POST', $url, $payload ); |
| 132 | + } |
| 133 | + |
| 134 | + /** |
| 135 | + * Issue an authenticated request to the Analytics Admin API. |
| 136 | + * |
| 137 | + * @param string $method HTTP method. |
| 138 | + * @param string $url Full URL. |
| 139 | + * @param array|null $body Optional JSON body. |
| 140 | + * @return array Decoded response. |
| 141 | + * @throws \RuntimeException On HTTP or API error. |
| 142 | + */ |
| 143 | + private function request( $method, $url, $body = null ) { |
| 144 | + $args = [ |
| 145 | + 'method' => $method, |
| 146 | + 'timeout' => 15, // phpcs:ignore WordPressVIPMinimum.Performance.RemoteRequestTimeout.timeout_timeout |
| 147 | + 'headers' => [ |
| 148 | + 'Authorization' => 'Bearer ' . $this->access_token, |
| 149 | + 'Accept' => 'application/json', |
| 150 | + ], |
| 151 | + ]; |
| 152 | + if ( null !== $body ) { |
| 153 | + $args['headers']['Content-Type'] = 'application/json'; |
| 154 | + $args['body'] = wp_json_encode( $body ); |
| 155 | + } |
| 156 | + $response = wp_remote_request( $url, $args ); |
| 157 | + if ( is_wp_error( $response ) ) { |
| 158 | + throw new \RuntimeException( esc_html( $response->get_error_message() ) ); |
| 159 | + } |
| 160 | + $code = wp_remote_retrieve_response_code( $response ); |
| 161 | + $decoded = json_decode( wp_remote_retrieve_body( $response ), true ); |
| 162 | + if ( $code < 200 || $code >= 300 ) { |
| 163 | + $message = is_array( $decoded ) && isset( $decoded['error']['message'] ) |
| 164 | + ? $decoded['error']['message'] |
| 165 | + : 'HTTP ' . $code; |
| 166 | + throw new \RuntimeException( esc_html( "Analytics Admin API error ($code): $message" ) ); |
| 167 | + } |
| 168 | + return is_array( $decoded ) ? $decoded : []; |
| 169 | + } |
| 170 | +} |
0 commit comments