api_key = $api_key; } protected function make_request($route = '', $body = array(), $method = 'GET', $response_code = 200) { $request_url = 'https://a.klaviyo.com/api/' . $route; // Construct headers. $headers = array( 'content-Type' => 'application/json', 'accept' => 'application/json', 'Authorization' => 'Klaviyo-API-Key ' . $this->api_key, 'revision' => '2024-05-15', ); $args = [ 'method' => $method, 'headers' => $headers ]; if ('GET' !== $method) { $args['body'] = wp_json_encode($body); } $result = wp_remote_request($request_url, $args); if (is_wp_error($result)) { return $result; } $response = wp_remote_retrieve_body($result); $response = GFCommon::maybe_decode_json($response); $api_response_code = (int) wp_remote_retrieve_response_code($result); if ($api_response_code !== $response_code) { $message = is_array($response) ? rgars($response, 'errors/0/detail') : ''; return new WP_Error( $api_response_code, $message ? $message : sprintf('Unexpected response code %d from Klaviyo.', $api_response_code), $response ); } return $response; } public function get_account() { return $this->make_request("accounts/"); } public function get_lists() { return $this->make_request("lists/"); } /** * Create a profile, or return the existing profile's ID when one already exists for the email. * * @return string|WP_Error The Klaviyo profile ID. */ public function create_profile($attributes) { $profile_attributes = array( 'email' => (string) $attributes['email'], ); if (! rgblank(rgar($attributes, 'name'))) { $profile_attributes['first_name'] = (string) $attributes['name']; } // Build the payload as data so values containing quotes can't break or extend the JSON. $body = array( 'data' => array( 'type' => 'profile', 'attributes' => $profile_attributes, ), ); $profile = $this->make_request('profiles/', $body, 'POST', 201); if (is_wp_error($profile)) { // Klaviyo answers 409 for an email that already has a profile and tells us its ID. $duplicate_id = rgars((array) $profile->get_error_data(), 'errors/0/meta/duplicate_profile_id'); if (409 === (int) $profile->get_error_code() && $duplicate_id) { return (string) $duplicate_id; } return $profile; } $profile_id = rgars($profile, 'data/id'); return $profile_id ? (string) $profile_id : new WP_Error('alphagf_klaviyo_no_profile', 'Klaviyo did not return a profile ID.'); } public function add_profile_with_list($attributes) { $profile_id = $this->create_profile($attributes); if (is_wp_error($profile_id)) { return $profile_id; } gform_update_meta($attributes['entry_id'], 'klaviyo_free_profile_id', $profile_id); $body = array( 'data' => array( array( 'type' => 'profile', 'id' => $profile_id, ), ), ); return $this->make_request('lists/' . rawurlencode($attributes['list']['klaviyoId']) . '/relationships/profiles/', $body, 'POST', 204); } }