php [mailchimp api] mailchimp php api #mail

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php [mailchimp api] mailchimp php api #mail相关的知识,希望对你有一定的参考价值。

<?php
/**
 * Get subscribers count via the MailChimp API.
 */
function mailchimp_get_subscribers_count() {
    $cache_key = 'mailchimp-subscribers';
    $api_key   = '';
    $username  = '';
    $dc        = '';
    $list_id   = '';
    $count = get_transient( $cache_key );
    if ( $count === false ) {
        $count = 0;
        $url = "https://{$dc}.api.mailchimp.com/3.0/lists/{$list_id}";
        $request = wp_remote_get( $url, array(
            'headers' => array(
                'Authorization' => 'Basic ' . base64_encode( $username . ':' . $api_key ),
            ),
        ) );
        if ( wp_remote_retrieve_response_code( $request ) == 200 ) {
            $body = wp_remote_retrieve_body( $request );
            $body = json_decode( $body, true );
            $count = absint( $body['stats']['member_count'] );
        }
        set_transient( $cache_key, $count, 12 * HOUR_IN_SECONDS );
    }
    return $count;
}
<!-- embed popup for mailchimp -->
<script type="text/javascript" src="//downloads.mailchimp.com/js/signup-forms/popup/unique-methods/embed.js" data-dojo-config="usePlainJson: true, isDebug: false"></script><script type="text/javascript">window.dojoRequire(["mojo/signup-forms/Loader"], function(L) { L.start({"baseUrl":"mc.us20.list-manage.com","uuid":"c58a38730b5cf6c32695a6ab0","lid":"2b523a0dc1","uniqueMethods":true}) })</script>

<style>
  .mc-layout__modalContent {height:auto !important;}
</style>
<script>
//insert HW_IO util from boostnote
var HW_IO={..};  
  
(function(){
    var tm=null,j=0;
function showMailingPopUp(loop) {
	window.dojoRequire(["mojo/signup-forms/Loader"], function(L) { L.start({"baseUrl":"mc.us20.list-manage.com","uuid":"c58a38730b5cf6c32695a6ab0","lid":"2b523a0dc1","uniqueMethods":true}) });
	document.cookie = 'MCEvilPopupClosed=;path=/;expires=Thu, 01 Jan 1970 00:00:00 UTC;';
	document.cookie = "MCPopupClosed=;path=/; expires=Thu, 01 Jan 1970 00:00:00 UTC";
	document.cookie = "MCPopupSubscribed=;path=/;expires=Thu, 01 Jan 1970 00:00:00 UTC";
	if(loop) return;
	
	HW_IO.waitForExist([function(){
	    showOverlay(0);
	    console.log('found popup');
	    console.log('bind click to popup');
	    HW_IO.data.lock=0;
	    jQuery('.mc-layout__modalContent').css('height','auto');
	    jQuery('body').on('click','.mc-closeModal', function(){
        	jQuery('.mc-modal').remove();
        	jQuery('.mc-modal-bg').remove();
        });
	},function(){
	    console.log('checking popup');
	    if(jQuery('.mc-modal').length==1) showOverlay(0);
        if(jQuery('.mc-modal').length==0 && j++==3 && jQuery('.mc-modal').length==0) {
            j=0;
            showMailingPopUp(true);
        }
	}], function(){return jQuery('.mc-modal').length>=1 && jQuery('.mc-layout__modalContent').length && jQuery('.mc-closeModal').length;});
	
	console.log('click to show popup');
	HW_IO.data.lock=1;
}
function showOverlay(show) {
    if(!jQuery.LoadingOverlay) return;
    jQuery.LoadingOverlay(show || typeof show=='undefined'? "show":'hide');
}
jQuery(document).ready(function($){
    HW_IO.waitForExist(function(){
        $('.spu-clickable').on('click', function(e){
          	e.preventDefault();
            showOverlay(1);
            if(!HW_IO.data.lock) showMailingPopUp();
        });
    },function(){return $('.spu-clickable').length;});
    
    if(!jQuery.LoadingOverlay) HW_IO.addJSFile('https://cdn.jsdelivr.net/npm/gasparesganga-jquery-loading-overlay@2.1.6/dist/loadingoverlay.min.js');
});
})();
</script>
<button id="open-popup" class="spu-clickable btn btn-primary">Subcribe</button>
<?php
/*
https://github.com/drewm/mailchimp-api
*/
include('./MailChimp.php'); 
//If you wish to use the batch request or webhook interfaces
include('./Batch.php'); 
include('./Webhook.php'); 

use \DrewM\MailChimp\MailChimp;

//with your API key
$MailChimp = new MailChimp('abc123abc123abc123abc123abc123-us1');

/**----------------------------------------------------------------------
	user info
*/
//https://developer.mailchimp.com/documentation/mailchimp/reference/root/
$user = $mc->get();
print_r($user['account_id']);

/**----------------------------------------------------------------------
	lists
*/
//get lists
$result = $MailChimp->get('lists');
print_r($result);

//get a list
$t=$mc->get('lists/2bd8c52cfe');
print_r($t);

//create a new list
$list = $mc->post('lists', [
	'name'=> 'test123',
	'contact'=> [
		'company' => 'test123',
        'address1' => 'Hn',
        'address2' => '',
        'city' => 'Hanoi',
        'state' => 'Hn',
        'zip' => '10000',
        'country' => 'VN',
        'phone' => ''
	],
	'permission_reminder' => 'You are receiving this email because you opted in via our website.',
    'use_archive_bar' => true,
    'campaign_defaults' => Array
        (
            'from_name' => 'hoang',
            'from_email' => 'test123.com@gmail.com',
            'subject' => '' ,
            'language' => 'en'
        ),

    'notify_on_subscribe' => '',
    'notify_on_unsubscribe' => '',
    'email_type_option' => false,
    'visibility' => 'pub',
    'double_optin' => false,
    'marketing_permissions' => false
]);
echo $list['id'];

//update a list
$list = $mc->patch('lists/2bd8c52cfe', [
	'name'=> 'test124',
	'contact'=> [
		'company' => 'test124',
        'address1' => 'Hn',
        'address2' => '',
        'city' => 'Hanoi',
        'state' => 'Hn',
        'zip' => '10000',
        'country' => 'VN',
        'phone' => ''
	],
	'permission_reminder' => 'XX You are receiving this email because you opted in via our website.',
	'campaign_defaults'=> [
		'from_name' => 'hoangX',
        'from_email' => 'test124.com@gmail.com',
        'subject' => '' ,
        'language' => 'en'
	],
	'email_type_option'=> false
]);
print_r($list);

//delete a list
$mc->delete('lists/{list_id}');

/**----------------------------------------------------------------------
	List subcriber
*/
//Subscribe someone to a list
$list_id = 'b1234346';

$result = $MailChimp->post("lists/$list_id/members", [
				'email_address' => 'davy@example.com',
				'status'        => 'subscribed',
			]);
if ($MailChimp->success()) {
	print_r($result);	
} else {
	echo $MailChimp->getLastError();
}

//Update a list member with more information
$list_id = 'b1234346';
$subscriber_hash = $MailChimp->subscriberHash('davy@example.com');

$result = $MailChimp->patch("lists/$list_id/members/$subscriber_hash", [
				'merge_fields' => ['FNAME'=>'Davy', 'LNAME'=>'Jones'],
				'interests'    => ['2s3a384h' => true],
			]);

print_r($result);

//Remove a list member
$list_id = 'b1234346';
$subscriber_hash = $MailChimp->subscriberHash('davy@example.com');

$MailChimp->delete("lists/$list_id/members/$subscriber_hash");

/**----------------------------------------------------------------------
	List merge fields
*/
//read fields
$fields = $mc->get('lists/{list_id}/merge-fields');
print_r($fields);

//Get a specific merge field
$mc->get('lists/{list_id}/merge-fields/{merge_id}');

//edit field
$mc->patch('lists/2bd8c52cfe/merge-fields/0',['name'=> 'Email']);
$t=$mc->patch('lists/2bd8c52cfe/merge-fields/1',[
	'name'=> 'Ho Ten',	//First Name
  	'public'=> true,
  	'required'=> true,
  	'default_value'=> 'Ho & ten'
]);
print_r($t);

//delete field
$mc->delete('/lists/{list_id}/merge-fields/{merge_id}');

/**----------------------------------------------------------------------
	List webhook
*/
//create new hook, for update use: `patch`
$mc->post('lists/{list_id}/webhooks', [
  'url'=> 'https://demo.hoangdata.com/mailchimp_hook.php',
  'events'=> [
    'subscribe'=> true,
    'unsubscribe'=> true
  ]
]);

//list hooks
$mc->get('lists/{list_id}/webhooks');

//get a hook
$mc->get('lists/{list_id}/webhooks/{webhook_id}');

//delete a hook
$mc->delete('lists/{list_id}/webhooks/{webhook_id}');

/**----------------------------------------------------------------------
	List signup form
*/
//create new
$r = $mc->post('lists/{list_id}/signup-forms', [
  'header'=> [
    'image_url'=> 'https://img.hoangweb.com/2018/10/logo-hoangweb.png',
    'text'=> 'Header text',
    'image_alt'=> 'Hoangweb',
    'image_link'=> 'http://hoangweb.com',
    'image_align'=> 'center',
    'image_target'=> '_blank'
  ],
  'content'=> [
    {'section'=> 'signup_message','value'=> 'You subscribed to Freddie'},
    {"section": "unsub_message", "value": "You'\''ve unsubscribed from Freddie'\''s Joke of the Day."},
    {"section": "signup_thank_you_title", "value": "Thanks for signing up!"}
  ]
]);

//get a form for list
$mc->get('lists/{list_id}/signup-forms');

/**----------------------------------------------------------------------
	Campaigns
*/
//create new campaign
$camp = $mc->post('campaigns', [
  'type'=> 'rss',
  'recipients'=> [
    "list_id":"3c307a9f3f",
    'list_is_active' => 1,
    'list_name' => 'volunteersforeducation',
    'segment_text' => '',
    'recipient_count' => 1
  ],
  'settings'=> [
    'subject_line'=> 'Bài viết mới:  *|RSSFEED:TITLE|* từ *|RSSFEED:DATE|*',
    'title'=> 'RSS Subcribe Form',
    'from_name'=> 'Customer Service',
    "reply_to":"orders@mammothhouse.com"
  ],
  'variate_settings'=> [
    'winner_criteria'=> 'opens'
  ],
  'tracking'=> [
    'opens'=> true,
    "html_clicks": true,
    "text_clicks": false,
    "goal_tracking": true,
    "ecomm360": true,
    "google_analytics": true,
    "clicktale": ""
  ],
  'rss_opts'=> [
    'feed_url'=> 'https://abc.com/feed',
    'frequency'=> 'daily',
    'schedule'=> [
      'hour'=> 4,
      'daily_send' => Array
      (
        'sunday' => 1,
        'monday' => 1,
        'tuesday' => 1,
        'wednesday' => 1,
        'thursday' => 1,
        'friday' => 1,
        'saturday' => 1
      ),

      'weekly_send_day' => '',
      'monthly_send_date' => 0
    ]
  ],
  'delivery_status'=> false
]);
echo $camp['id'];

//list all campaigns
$all = $mc->get('campaigns');
print_r($all);

//get a campaign
$mc->get('campaigns/{campaign_id}');

//delete a campaign
$mc->delete('campaigns/{campaign_id}');

/**----------------------------------------------------------------------
	Campaign content
*/
//update content for a campaign.
$camp = $mc->put('campaigns/{campaign_id}/content', [
  'plain_text'=> '',
  'html'=> '<p>..</p>',
  'archive_html'=> '',
]);

以上是关于php [mailchimp api] mailchimp php api #mail的主要内容,如果未能解决你的问题,请参考以下文章

React 中的自定义 mailchimp 注册表单

@mailchimp/mailchimp_marketing/types.d.ts' 不是 nodeJs 中的模块

Mailchimp PHP Marketing API 传递请求参数

Mailchimp API PHP:500 错误

php Api mailchimp

将查询参数添加到 PHP 的 Mailchimp API 请求