[ 'newFormat' => 1, 'scope' => 'crmapi', 'wfTrigger' => 'true', 'authtoken' => null, 'xmlData' => null, ], self::METHOD_GET_RECORD_BY_ID => [ 'scope' => 'crmapi', 'authtoken' => null, 'id' => null, ], self::METHOD_SEARCH_RECORDS => [ 'newFormat' => 1, 'scope' => 'crmapi', 'criteria' => null, // (((Last Name:Steve)AND(Company:Zillum))OR(Lead Status:Contacted)) ], ]; /** * @param $module * @param $method * @param array $data * * @return bool|array * @throws Exception */ public static function request( $module, $method, array $data ) { if ( ! in_array( $module, self::$allowed_modules ) ) { throw new Exception( 'Unknown ZOHO CRM API module.' ); } if ( ! array_key_exists( $method, self::$methods_url_params ) ) { throw new Exception( 'Unknown ZOHO CRM API method.' ); } $token = get_option( 'fqp_zoho_auth_token' ); if ( ! $token ) { throw new Exception( 'Zoho CRM Authentication Token is empty.' ); } $url_params = self::$methods_url_params[$method]; $url_params['authtoken'] = $token; switch ( $method ) { case self::METHOD_INSERT_RECORDS: $xml = static::get_xml( $module, $data ); if ( ! $xml ) { throw new Exception( 'Request XML is empty.' ); } $url_params['xmlData'] = $xml; break; case self::METHOD_GET_RECORD_BY_ID: $url_params['id'] = $data['id']; break; case self::METHOD_SEARCH_RECORDS: $url_params['criteria'] = $data['criteria']; break; } $url_data = [ '%module%' => urlencode( $module ), '%method%' => urlencode( $method ), ]; $url = str_replace( array_keys( $url_data ), $url_data, static::$url ) . http_build_query( $url_params ); $ch = curl_init(); curl_setopt( $ch, CURLOPT_URL, $url ); curl_setopt( $ch, CURLOPT_HEADER, 0 ); curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 ); $result = curl_exec( $ch ); curl_close( $ch ); $result = json_decode( $result, true ); static::prepare_response( $result ); return $result; } public static function get_error_message( $response ) { if ( empty( $response ) && ! is_array( $response ) ) { return 'Zoho response format is wrong.'; } if ( is_array( @$response['response'] ) && array_key_exists( 'error', $response['response'] ) ) { return "({$response['response']['error']['code']}) {$response['response']['error']['message']}"; } return false; } protected static function prepare_response( array &$response ) { foreach ( $response as $key => &$value ) { $key = strval( $key ); if ( 'FL' == $key ) { $new_value = []; foreach ( $value as $item) { $new_value[ $item['val'] ] = $item['content']; } $value = $new_value; } else { if ( is_array( $value ) ) { self::prepare_response( $value ); } } } } /** * @param $module * @param array $data * * @return mixed * @throws Exception */ protected static function get_xml( $module, array $data ) { $class = "FQP\\ZOHO\\{$module}"; if ( ! class_exists( $class ) ) { throw new Exception( "Class '{$class}' in not found." ); } return call_user_func_array( [ $class, 'get_xml' ], [ $data ] ); } }