_config) { $this->_config = Qs_Config::getByInstance($this); } if (null === $field) { return $this->_config; } return $this->_config->get($field, $default); } /** * @param $url * @param array|string $body * @param array $headers * @param $method * @return mixed */ protected function getCurlData($urlSuffix, $body = [], $headers = [], $method = self::CURL_REQUEST_GET) { $curlHandle = self::_getCurlHandle(); if ($method == self::CURL_REQUEST_POST) { curl_setopt($curlHandle, CURLOPT_POST, 1); curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $body); } elseif ($method == self::CURL_REQUEST_PUT) { curl_setopt($curlHandle, CURLOPT_CUSTOMREQUEST, 'PUT'); curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $body); } else { curl_setopt($curlHandle, CURLOPT_POST, 0); if (is_array($body) && count($body)) { $urlSuffix .= '?' . http_build_query($body); } } curl_setopt($curlHandle, CURLOPT_URL, $this->getConfig('endPoint') . $urlSuffix); curl_setopt($curlHandle, CURLOPT_USERPWD, 'username:' . $this->getConfig('apiKey')); curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true); if (count($headers)) { curl_setopt($curlHandle, CURLOPT_HTTPHEADER, $headers); } $response = curl_exec($curlHandle); if (self::HTTP_OK == curl_getinfo($curlHandle, CURLINFO_HTTP_CODE)) { $data = json_decode($response, true); } else { $data = null; } return $data; } protected static function _getCurlHandle() { if (null === self::$_curlHandle) { self::$_curlHandle = curl_init(); curl_setopt(self::$_curlHandle, CURLOPT_HEADER, false); } return self::$_curlHandle; } public function getMember($email) { $urlSuffix = 'lists/' . $this->getConfig('listId') . '/members/' . md5(strtolower($email)); return $this->getCurlData($urlSuffix); } public function addMember($data) { $urlSuffix = 'lists/' . $this->getConfig('listId') . '/members/'; $fullName = explode(' ', $data['fullName'], 2); $params = [ 'email_address' => $data['email'], 'status' => self::MAILCHIMP_STATUS_SUBSCRIBED, 'merge_fields' => [ 'FNAME' => $data['firstName'] ?: Qs_Array::get($fullName, 0, ''), 'LNAME' => $data['lastName'] ?: Qs_Array::get($fullName, 1, ''), ] ]; return $this->getCurlData($urlSuffix, json_encode($params), [], self::CURL_REQUEST_POST); } public function setSubscribed($email) { $urlSuffix = 'lists/' . $this->getConfig('listId') . '/members/' . md5(strtolower($email)); return $this->getCurlData($urlSuffix, json_encode([ 'status' => self::MAILCHIMP_STATUS_SUBSCRIBED ]), [], self::CURL_REQUEST_PUT); } public function subscribeMember($data) { if (null !== ($member = $this->getMember($data['email']))) { if ($member['status'] != self::MAILCHIMP_STATUS_SUBSCRIBED) { return $this->setSubscribed($data['email']); } return false; } else { return $this->addMember($data); } } }