Jump to content
Latest News: (loading..)
tgely

Mailchimp App with 3.0API

Recommended Posts

Hi everybody,

 

 

Mailchimp is a good way going forward but the latest api v3.0 is not figured out for oscommerce. I have done it for my business but no more time to build an app at this moment.

 

 

Setup Enviroment

 

Download from github the latest api: https://github.com/drewm/mailchimp-api

 

Upload MailChimp.php and Batch.php from zip archive into YOUR_CATALOG/ext/api/mailchimp3/ folder.
 

 

Install ht_mailchimp_360.php header tag for constants or edit by directly list_id and api in the code below.

 

 

Create test.php file with build in class and test script codes for oscommerce enviroment in YOUR_CATALOG/ext/api/mailchimp3/ folder.

<?php
// see result in Mailchimp account API menu or use mailchimp class file logger
// https://us2.admin.mailchimp.com/account/api/

  chdir('../../../');
  // ini_set('display_errors', 1);
  // Prepaires
  // do oscommerce setup

  require('ext/api/mailchimp3/MailChimp.php');

  use DrewM\MailChimp;

  require('includes/application_top.php');

  class OSCOM_MailChimp {
    private $_api;
    private $list_id;
    private $logfile = 'mailchimp.log';
    private $logger_enabled = true;

    public function __construct() {
      $api_key = MODULE_HEADER_TAGS_MAILCHIMP_360_API_KEY;
      $this->list_id = MAILCHIMP_LIST_ID;

      $this->_api = new DrewM\MailChimp\MailChimp($api_key);
    }

    public function subscribe($email, $merge_fields = array()) {
      $subscriber_hash = $this->_api->subscriberHash($email);

      $this->_api->get("lists/" . $this->list_id . "/members/" . $subscriber_hash . "");

      $response = $this->_api->getLastResponse();
      if ($response['headers']['http_code'] == 404) {
        // add new user
        $result = $this->_api->post("lists/" . $this->list_id . "/members", [
                                    'email_address' => $email,
                                    'status'        => 'subscribed',
                                    'merge_fields'  => $merge_fields
                                  ]);

      } else {
        // modify user
        $this->_api->patch("lists/" . $this->list_id . "/members/" . $subscriber_hash . "", [
                    'status'        => 'subscribed'
                    ]);
      }

      if ($this->logger_enabled) {
        $this->logger($this->_api->getLastError());
        $this->logger($result);
        $this->logger($this->_api->getLastResponse());
        $this->logger($this->_api->getLastRequest());
      }
    }

    public function unsubscribe($email) {
      $subscriber_hash = $this->_api->subscriberHash($email);

      $this->_api->get("lists/" . $this->list_id . "/members/" . $subscriber_hash . "");

      $response = $this->_api->getLastResponse();
      if ($response['headers']['http_code'] == 200) {
        // modify user
        $this->_api->patch("lists/" . $this->list_id . "/members/" . $subscriber_hash . "", [
                          'status'        => 'unsubscribed'
                          ]);

        if ($this->logger_enabled) {
          $this->logger($this->_api->getLastError());
          $this->logger($result);
          $this->logger($this->_api->getLastResponse());
          $this->logger($this->_api->getLastRequest());
        }
      }
    }

    public function getListId() {
      return $this->list_id;
    }
    
    public function setListId($list_id) {
      $this->list_id = $list_id;
    }

    private function logger($msg) {
      file_put_contents($this->logfile, date("Y-m-d H:i:s") . " | " . print_r($msg, true) . "\n", FILE_APPEND);
    }
  }

  /* EXAMPLE CODE */
  // use ?up (subscribe) or ?down (unsubscribe) params in URL request for testing

  $M = new OSCOM_MailChimp();
  $merge_array = array('FNAME'=> 'Elek',
                       'LNAME'=> 'Test');

  if (isset($_GET['up'])) {
    $M->subscribe('test.elek@freemail.hu', $merge_array);
  } elseif (isset($_GET['down'])) {
    $M->unsubscribe('test.elek@freemail.hu');
  }


  require(DIR_WS_INCLUDES . 'application_bottom.php');
?>

Usage: http://YOUR_CATALOG/ext/api/mailchimp3/ test.php?up or http://YOUR_CATALOG/ext/api/mailchimp3/ test.php?down



Webhook unsubscribe example codes for oscommerce:

<?php
/*
Configuring Webhooks

Webhooks are configured from your MailChimp account. Here are the basic steps:

    Log in to your MailChimp account
    Navigate to your Lists
    Click View Lists on the list you want to configure
    Click the List Tools menu option at the top
    Click Webhooks

Configuration is simple: Enter a valid url for us to contact, then select the events and event sources (see below for descriptions) you want to have sent to you.
*/


  chdir('../../../');
  require('includes/application_top.php');

  if (isset($_POST['type'])) {
    $customers_email = (isset($_POST['data']['email']) ? tep_db_prepare_input($_POST['data']['email']) : Null);

    if (tep_validate_email($customers_email)) {
      $check_query = tep_db_query("select customers_id from customers where customers_email_address = '" . tep_db_input($customers_email) . "'");

      if (tep_db_num_rows($check_query)) {
        $customers = tep_db_fetch_array($check_query);

        if ($_POST['type'] == 'subscribe') {
          tep_db_query("update customers set customers_newsletter = '1' where customers_email_address = '" . tep_db_input($customers_email) . "'");
        } elseif ($_POST['type'] == 'unsubscribe') {

          tep_db_query("update customers set customers_newsletter = '0' where customers_email_address = '" . tep_db_input($customers_email) . "'");
        }
        tep_db_query("update customers_info set customers_info_date_account_last_modified = now() where customers_info_id = '" . (int)$customers['customers_id']  . "'");
      }
    }
  }

  
    $my_key  = 'your_secret_code!';

    wh_log('==================[ Incoming Request ]==================');

    wh_log("Full _REQUEST dump:\n".print_r($_REQUEST,true)); 

    if ( !isset($_GET['key']) ){
        wh_log('No security key specified, ignoring request'); 
    } elseif ($_GET['key'] != $my_key) {
        wh_log('Security key specified, but not correct:');
        wh_log("\t".'Wanted: "'.$my_key.'", but received "'.$_GET['key'].'"');
    } else {
        //process the request
        wh_log('Processing a "'.$_POST['type'].'" request...');
        switch($_POST['type']){
            case 'subscribe'  : subscribe($_POST['data']);   break;
            case 'unsubscribe': unsubscribe($_POST['data']); break;
            case 'cleaned'    : cleaned($_POST['data']);     break;
            case 'upemail'    : upemail($_POST['data']);     break;
            case 'profile'    : profile($_POST['data']);     break;
            default:
                wh_log('Request type "'.$_POST['type'].'" unknown, ignoring.');
        }
    }
    wh_log('Finished processing request.');

    /***********************************************
        Helper Functions
    ***********************************************/
    function wh_log($msg){
        $logfile = 'webhook.log';
        file_put_contents($logfile,date("Y-m-d H:i:s")." | ".$msg."\n",FILE_APPEND);
    }

    function subscribe($data){
        wh_log($data['email'] . ' just subscribed!');
    }
    function unsubscribe($data){
        wh_log($data['email'] . ' just unsubscribed!');
    }
    function cleaned($data){
        wh_log($data['email'] . ' was cleaned from your list!');
    }
    function upemail($data){
        wh_log($data['old_email'] . ' changed their email address to '. $data['new_email']. '!');
    }
    function profile($data){
        wh_log($data['email'] . ' updated their profile!');
    }

  require(DIR_WS_INCLUDES . 'application_bottom.php');
?>

Hooks examle or direct oscommerce snipet code in create_account.php:
 

      //Mailchimp
      if (MODULE_HEADER_TAGS_MAILCHIMP_360_STATUS == 'True') {
        if ($newsletter == '1') {
          require_once('includes/classes/OSCOM_mailchimp.php');
          $M = new OSCOM_MailChimp();
          $merge_array = array('FNAME'=> $firstname,
                               'LNAME'=> $lastname
                              );
          $M->subscribe($email_address, $merge_array);
        }
      }

Note: OSCOM_mailchimp.php contains only the same class code as you use in test.php

 

use your own risk.

 

Have a good work!
 

Edited by Gergely

:blink:
osCommerce based shop owner with minimal design and focused on background works. When the less is more.
Email managment with tracking pixel, package managment for shipping, stock management, warehouse managment with bar code reader, parcel shops management on 3000 pickup points without local store.

Share this post


Link to post
Share on other sites

v3 API sucks so much it blows.  

Mailchimp went backwards badly on this update.


This is a signature that appears on all my posts.  
IF YOU MAKE A POST REQUESTING HELP...please state the exact version
of osCommerce that you are using. THANKS

 
Get the latest current code (community-supported responsive 2.3.4.1BS Edge) here

 

Share this post


Link to post
Share on other sites

@@burt I dont see the drama, but we should work with it. Gorilla services are focusing to global things. This is not bad. The same is in PayPal or Facebook.


:blink:
osCommerce based shop owner with minimal design and focused on background works. When the less is more.
Email managment with tracking pixel, package managment for shipping, stock management, warehouse managment with bar code reader, parcel shops management on 3000 pickup points without local store.

Share this post


Link to post
Share on other sites

It's a massive problem this v3.  Having been the only dev to make the Mailchimp Module in all versions, I can tell you that v3 sucks, and their own customer service know it.


This is a signature that appears on all my posts.  
IF YOU MAKE A POST REQUESTING HELP...please state the exact version
of osCommerce that you are using. THANKS

 
Get the latest current code (community-supported responsive 2.3.4.1BS Edge) here

 

Share this post


Link to post
Share on other sites

Consider to language codes OSCOM_mailchimp class extended:

<?php
// see result in Mailchimp account API menu or use mailchimp class file logger

  require('ext/api/mailchimp3/MailChimp.php');

  use DrewM\MailChimp;

  class OSCOM_MailChimp {

    // mailchimp api class
    private $_api;

    // mailchimp list id
    private $list_id;

    // default log file name
    private $logfile = 'mailchimp.log';

    // set logger
    private $logger_enabled = true;

    // subscribe language
    private $default_mailchimp_language = 'en';

    // instance of all languages
    private $Mlanguages;

    public function __construct() {
      $api_key = MODULES_HEADER_TAGS_MAILCHIMP_API;
      $this->list_id = MODULES_HEADER_TAGS_MAILCHIMP_LIST_CUSTOMERS;

      $this->_api = new DrewM\MailChimp\MailChimp($api_key);

      $this->Mlanguages = $this->getMailChimpLanguageCodes();
    }

    public function subscribe($email, $merge_fields = array(), $language = null) {
      $subscriber_hash = $this->_api->subscriberHash($email);

      $this->_api->get("lists/" . $this->list_id . "/members/" . $subscriber_hash . "");

      $response = $this->_api->getLastResponse();
      if ($response['headers']['http_code'] == 404) {
        // add new user
        $result = $this->_api->post("lists/" . $this->list_id . "/members", [
                                    'email_address' => $email,
                                    'status'        => 'subscribed',
                                    'language'      => $language,
                                    'merge_fields'  => $merge_fields
                                  ]);

      } else {
        // modify user
        $result = $this->_api->patch("lists/" . $this->list_id . "/members/" . $subscriber_hash . "", [
                                    'status'        => 'subscribed',
                                    'language'      => $language
                                    ]);
      }

      if ($this->logger_enabled) {
        $this->logger($this->_api->getLastError());
        $this->logger($result);
        $this->logger($this->_api->getLastResponse());
        $this->logger($this->_api->getLastRequest());
      }
      return (empty($this->_api->getLastError()) ? true : false);
    }

    public function unsubscribe($email) {
      $subscriber_hash = $this->_api->subscriberHash($email);

      $this->_api->get("lists/" . $this->list_id . "/members/" . $subscriber_hash . "");

      $response = $this->_api->getLastResponse();
      if ($response['headers']['http_code'] == 200) {
        // modify user
        $result = $this->_api->patch("lists/" . $this->list_id . "/members/" . $subscriber_hash . "", [
                                    'status'        => 'unsubscribed'
                                    ]);

        if ($this->logger_enabled) {
          $this->logger($this->_api->getLastError());
          $this->logger($result);
          $this->logger($this->_api->getLastResponse());
          $this->logger($this->_api->getLastRequest());
        }
      }
      return (empty($this->_api->getLastError()) ? true : false);
    }

    public function getListId() {
      return $this->list_id;
    }

    public function setListId($list_id) {
      $this->list_id = $list_id;
    }

    private function logger($msg) {
      file_put_contents($this->logfile, date("Y-m-d H:i:s") . " | " . print_r($msg, true) . "\n", FILE_APPEND);
    }

    private function getMailChimpLanguageCodes() {
      $lng = array( 'en'    => 'English',
                    'ar'    => 'Arabic',
                    'af'    => 'Afrikaans',
                    'be'    => 'Belarusian',
                    'bg'    => 'Bulgarian',
                    'ca'    => 'Catalan',
                    'zh'    => 'Chinese',
                    'hr'    => 'Croatian',
                    'cs'    => 'Czech',
                    'da'    => 'Danish',
                    'nl'    => 'Dutch',
                    'et'    => 'Estonian',
                    'fa'    => 'Farsi',
                    'fi'    => 'Finnish',
                    'fr'    => 'French (France)',
                    'fr_CA' => 'French (Canada)',
                    'de'    => 'German',
                    'el'    => 'Greek',
                    'he'    => 'Hebrew',
                    'hi'    => 'Hindi',
                    'hu'    => 'Hungarian',
                    'is'    => 'Icelandic',
                    'id'    => 'Indonesian',
                    'ga'    => 'Irish',
                    'it'    => 'Italian',
                    'ja'    => 'Japanese',
                    'km'    => 'Khmer',
                    'ko'    => 'Korean',
                    'lv'    => 'Latvian',
                    'lt'    => 'Lithuanian',
                    'mt'    => 'Maltese',
                    'ms'    => 'Malay',
                    'mk'    => 'Macedonian',
                    'no'    => 'Norwegian',
                    'pl'    => 'Polish',
                    'pt'    => 'Portuguese (Brazil)',
                    'pt_PT' => 'Portuguese (Portugal)',
                    'ro'    => 'Romanian',
                    'ru'    => 'Russian',
                    'sr'    => 'Serbian',
                    'sk'    => 'Slovak',
                    'sl'    => 'Slovenian',
                    'es'    => 'Spanish (Mexico)',
                    'es_ES' => 'Spanish (Spain)',
                    'sw'    => 'Swahili',
                    'sv'    => 'Swedish',
                    'ta'    => 'Tamil',
                    'th'    => 'Thai',
                    'tr'    => 'Turkish',
                    'uk'    => 'Ukrainian',
                    'vi'    => 'Vietnamese');

      return $lng;
    }

    // use oscommerce language_id to identify MailChimp language code
    public function getMailChimpLanguageCode($language_id) {

      $language_query = tep_db_query("select max(code) as code from languages where languages_id = '" . (int)$language_id . "'");
      $language = tep_db_fetch_array($language_query);

      if ( isset($this->Mlanguages[$language['code']]) ) {
        return $language['code'];
      } else {
        return $this->default_mailchimp_language;
      }
    }

    public function setDefaultMailChimpLanguageCode($code) {
      $this->default_mailchimp_language = $this->getMailChimpLanguageCode($code);
    }
  }
?>

So you can use language identification in API subscribes

http://kb.mailchimp.com/lists/managing-subscribers/view-and-edit-subscriber-languages?_ga=1.148192372.2136989545.1378013731


:blink:
osCommerce based shop owner with minimal design and focused on background works. When the less is more.
Email managment with tracking pixel, package managment for shipping, stock management, warehouse managment with bar code reader, parcel shops management on 3000 pickup points without local store.

Share this post


Link to post
Share on other sites
On 4/21/2016 at 8:08 PM, burt said:

It's a massive problem this v3.  Having been the only dev to make the Mailchimp Module in all versions, I can tell you that v3 sucks, and their own customer service know it.

Why?

Share this post


Link to post
Share on other sites
15 hours ago, dr_lucas said:

Why?

2.5 years ago was early adoption of v3 - and a lot of what was available in v2 was not available in v3.  Some things in the documentation for v3 simply did not exist in the code or did not work.  

Today (or at least the last time I looked), the API does not include their roll-up of GDPR, which means the API is unusable for "Joe Average" shopowners who does not want to have to delve deep into code or does not want to spend money on a developer.


This is a signature that appears on all my posts.  
IF YOU MAKE A POST REQUESTING HELP...please state the exact version
of osCommerce that you are using. THANKS

 
Get the latest current code (community-supported responsive 2.3.4.1BS Edge) here

 

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×