veda-consulting-company / uk.co.vedaconsulting.mailchimp

Other
22 stars 43 forks source link

Unsubscribed contact are resubscribed in CiviCRM after edition in Mailchimp #336

Open samuelsov opened 4 years ago

samuelsov commented 4 years ago

To reproduce:

Screenshot_2020-04-06 - Mailchimp

The contact will be resubscribed to the list.

samuelsov commented 4 years ago

The following patch seems to fix it:

diff --git a/CRM/Mailchimp/Page/WebHook.php b/CRM/Mailchimp/Page/WebHook.php
index 9bd13d9..3eaec26 100644
--- a/CRM/Mailchimp/Page/WebHook.php
+++ b/CRM/Mailchimp/Page/WebHook.php
@@ -350,11 +366,19 @@ class CRM_Mailchimp_Page_WebHook extends CRM_Core_Page {
       civicrm_api3('Contact', 'create', ['contact_id' => $this->contact_id] + $edits);
     }

+    // [SV] fixing a bug where the contact is unsubscribed in Mailchimp but added here
+    // it would happen any time an admin update an account in mailchimp
+    $api = CRM_Mailchimp_Utils::getMailchimpApi();
+    $subscriber_hash = md5(strtolower($this->request_data['email']));
+    $list_id = $this->request_data['list_id'];
+    $response = $api->get("/lists/{$list_id}/members/{$subscriber_hash}", ['fields' => 'status']);
+    $status = $response->data->status == 'unsubscribed' ? 'Removed' : 'Added';
+
     // Contact has just subscribed, we'll need to add them to the list.
     civicrm_api3('GroupContact', 'create', [
       'contact_id' => $this->contact_id,
       'group_id'   => $this->sync->membership_group_id,
-      'status'     => 'Added',
+      'status'     => $status,
       ]);

     $this->updateInterestsFromMerges();

Not sure my code works for all cases as I assume only unsubscibed is Removed but the status value is one of:

samuelsov commented 4 years ago

I'm trying to see any difference between Mailchimp and CiviCRM list and:

samuelsov commented 4 years ago

I'm trying to see any difference between Mailchimp and CiviCRM list and:

* cleaned => hard bounce so we should ideally put the email on_hold in CiviCRM or have a way to identify them

I've seen that it's already in the code so let's ignore the cleaned part and focus on the bug described.