From 8fbc663cf9df8e89c10daf5511d004e826e36690 Mon Sep 17 00:00:00 2001 From: Niels Wijers Date: Wed, 12 Oct 2022 11:53:56 +0200 Subject: [PATCH] Added support for PUT requests to the subscribe endpoint --- src/controllers/MailchimpController.php | 13 ++++++++++--- src/services/MailchimpService.php | 12 +++++++++--- 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/src/controllers/MailchimpController.php b/src/controllers/MailchimpController.php index 51e263c..360aac3 100644 --- a/src/controllers/MailchimpController.php +++ b/src/controllers/MailchimpController.php @@ -1,4 +1,5 @@ asJson(SimpleMailchimp::getInstance()->smcService->subscribe($_POST)); + if (in_array($this->request->method, self::ALLOWED_METHODS)) { + $params = $this->request->getBodyParams(); + + return $this->asJson(SimpleMailchimp::getInstance()->smcService->subscribe($params, $this->request->isPut)); } - return $this->asJson(['success' => false, 'msg' => 'Direct access not allowed']); + $this->response->setStatusCode(405); + return $this->asJson(['success' => false, 'msg' => 'Method not allowed']); } } diff --git a/src/services/MailchimpService.php b/src/services/MailchimpService.php index 254d105..3368f11 100644 --- a/src/services/MailchimpService.php +++ b/src/services/MailchimpService.php @@ -1,4 +1,5 @@ false, 'msg' => 'Email can\'t be empty']; @@ -52,14 +54,18 @@ public function subscribe($data): array $MailChimp = new MC(App::parseEnv($settings['mcApiKey'] ?: '')); - $result = $MailChimp->post("lists/" . App::parseEnv($settings['mcListID'] ?: '') . "/members", $dataMC); + if ($upsert) { + $result = $MailChimp->put("lists/" . App::parseEnv($settings['mcListID'] ?: '') . "/members/" . md5($data["email"]), $dataMC); + } else { + $result = $MailChimp->post("lists/" . App::parseEnv($settings['mcListID'] ?: '') . "/members", $dataMC); + } + if ($result['status'] == 'subscribed') { return ['success' => true, 'msg' => 'Email subscribed successfully', 'id' => $result['contact_id']]; } return ['success' => false, 'msg' => 'Mailchimp error: ' . $result['title']]; - } catch (\Exception $e) { return ['success' => false, 'msg' => $e->getMessage()]; }