15, 'headers' => array( 'Accept' => 'application/json' ), ) ); if ( is_wp_error( $response ) ) { return new WP_Error( 'pubchem_api_error', 'PubChem API request failed: ' . $response->get_error_message() ); } $code = wp_remote_retrieve_response_code( $response ); if ( 200 !== $code ) { return new WP_Error( 'pubchem_http_error', 'PubChem returned HTTP ' . $code ); } $body = json_decode( wp_remote_retrieve_body( $response ), true ); return isset( $body['IdentifierList']['CID'][0] ) ? (int) $body['IdentifierList']['CID'][0] : null; } /** * Get molecular properties for a given CID. * * @param int $cid PubChem Compound ID. * @return array|WP_Error|null Properties array, WP_Error on failure, or null if not found. */ private static function get_properties( int $cid ) { $props = 'MolecularFormula,MolecularWeight,IUPACName,CanonicalSMILES,InChI'; $url = self::API_BASE . '/compound/cid/' . (int) $cid . '/property/' . $props . '/JSON'; $response = wp_remote_get( $url, array( 'timeout' => 15, 'headers' => array( 'Accept' => 'application/json' ), ) ); if ( is_wp_error( $response ) ) { return new WP_Error( 'pubchem_api_error', 'PubChem API request failed: ' . $response->get_error_message() ); } $code = wp_remote_retrieve_response_code( $response ); if ( 200 !== $code ) { return new WP_Error( 'pubchem_http_error', 'PubChem returned HTTP ' . $code ); } $body = json_decode( wp_remote_retrieve_body( $response ), true ); if ( ! isset( $body['PropertyTable']['Properties'][0] ) ) { return null; } $p = $body['PropertyTable']['Properties'][0]; return array( 'molecular_formula' => $p['MolecularFormula'] ?? '', 'molecular_weight' => isset( $p['MolecularWeight'] ) ? $p['MolecularWeight'] . ' Da' : '', 'iupac_name' => $p['IUPACName'] ?? '', 'smiles' => $p['CanonicalSMILES'] ?? '', 'inchi' => $p['InChI'] ?? '', ); } }