Automattic\WooCommerce\Blocks\AI

Connection::get_jwt_token()publicWC 1.0

Fetch the JWT token.

Method of the class: Connection{}

No Hooks.

Return

String|\WP_Error. The JWT token or a WP_Error object.

Usage

$Connection = new Connection();
$Connection->get_jwt_token( $site_id );
$site_id(int) (required)
The site ID.

Connection::get_jwt_token() code WC 9.4.2

public function get_jwt_token( $site_id ) {
	if ( is_wp_error( $site_id ) ) {
		return $site_id;
	}

	$request = Client::wpcom_json_api_request_as_user(
		sprintf( '/sites/%d/jetpack-openai-query/jwt', $site_id ),
		'2',
		array(
			'method'  => 'POST',
			'headers' => array( 'Content-Type' => 'application/json; charset=utf-8' ),
		)
	);

	$response = json_decode( wp_remote_retrieve_body( $request ) );

	if ( $response instanceof \WP_Error ) {
		return new \WP_Error( $response->get_error_code(), esc_html__( 'Failed to generate the JWT token', 'woocommerce' ), $response->get_error_message() );
	}

	if ( ! isset( $response->token ) ) {
		return new \WP_Error( 'failed-to-retrieve-jwt-token', esc_html__( 'Failed to retrieve the JWT token: Try again later.', 'woocommerce' ) );
	}

	return $response->token;
}