__( 'Permission denied.', 'aisp-smart-autocomplete-address' ) ], 403 ); } // 2. Verification of the nonce sent by the JavaScript // This nonce was generated by wp_create_nonce('aisp_check_api_key') in the file class-settings-page.php check_ajax_referer( 'aisp_check_api_key', 'nonce' ); // 3. Reading the key sent from the form. $api_key = isset( $_POST['api_key'] ) ? sanitize_text_field( wp_unslash( $_POST['api_key'] ) ) : ''; if ( empty( $api_key ) ) { wp_send_json_error( [ 'message' => __( 'API key is empty.', 'aisp-smart-autocomplete-address' ) ], 400 ); } // 4. Sending a test request to the HERE API $url = add_query_arg( [ 'q' => 'Montreal', 'limit' => 1, 'apiKey' => $api_key, ], 'https://autocomplete.search.hereapi.com/v1/autocomplete' ); $response = wp_remote_get( $url, [ 'timeout' => 10 ] ); if ( is_wp_error( $response ) ) { wp_send_json_error( [ 'message' => __( 'Request failed.', 'aisp-smart-autocomplete-address' ) ], 500 ); } $code = wp_remote_retrieve_response_code( $response ); // 5. Résultat de la vérification if ( 200 === $code ) { wp_send_json_success( [ 'message' => __( '✅ Valid API key', 'aisp-smart-autocomplete-address' ) ] ); } if ( in_array( $code, [ 401, 403 ], true ) ) { wp_send_json_error( [ 'message' => __( '❌ Invalid or expired API key', 'aisp-smart-autocomplete-address' ) ], $code ); } // translators: %d is the HTTP status code returned by the HERE API. wp_send_json_error( [ 'message' => sprintf( // translators: %d is the HTTP status code returned by the HERE API. __( 'Request error (HTTP %d).', 'aisp-smart-autocomplete-address' ), $code ), ], $code ?: 500 ); } );