base() !== ''; } public static function datacenter(string $key): string { $pos = strrpos($key, '-'); $dc = $pos === false ? '' : strtolower(substr($key, $pos + 1)); return preg_match('/^[a-z]{2,4}\d{1,3}$/', $dc) ? $dc : ''; } public function base(): string { $dc = self::datacenter(Credentials::get('mailchimp_api_key')); return $dc !== '' ? 'https://' . $dc . '.api.mailchimp.com/3.0' : ''; } /** @return array */ private function headers(): array { return ['Authorization' => self::basic('zadex', Credentials::get('mailchimp_api_key'))]; } public function lists() { if (!$this->configured()) { return new WP_Error('zadex_integration_not_configured', 'Mailchimp API key missing or invalid.'); } $r = Http::request('GET', $this->base() . '/lists?count=100&fields=lists.id,lists.name', ['headers' => $this->headers()]); return $r instanceof WP_Error ? $r : self::options($r['json']['lists'] ?? [], 'id', 'name'); } public function subscribe(array $contact) { $list = rawurlencode($contact['list']); $hash = md5(strtolower($contact['email'])); $merge = $contact['fields']; if ($contact['first_name'] !== '' && !isset($merge['FNAME'])) { $merge['FNAME'] = $contact['first_name']; } if ($contact['last_name'] !== '' && !isset($merge['LNAME'])) { $merge['LNAME'] = $contact['last_name']; } $body = [ 'email_address' => $contact['email'], 'status_if_new' => $contact['double_optin'] ? 'pending' : 'subscribed', ]; if ($merge) { $body['merge_fields'] = $merge; } $member = $this->base() . '/lists/' . $list . '/members/' . $hash; $r = Http::json('PUT', $member, $body, $this->headers()); if ($r instanceof WP_Error) { return $r; } if ($contact['tags']) { $tags = array_map(static fn(string $t): array => ['name' => $t, 'status' => 'active'], $contact['tags']); $t = Http::json('POST', $member . '/tags', ['tags' => $tags], $this->headers()); if ($t instanceof WP_Error) { return $t; } } return true; } }