MailChimp API: Batch Check Subscription Status - php

What's the best way to check a batch of email addresses and whether or not they are subscribed to a particular list? My current method is making an API call for each email address, but this becomes very slow when the count becomes > 50.
I'm using V2.0, using PHP methods since I'm developing on CakePHP.
//Determine MailChimp Subscription
$args = array(
'id' => $this->apiKeys['mailchimp_list_ID'],
'emails' => array(1 => array('email' => $customer['User']['username']))
);
$mailChimpQuery = $this->mailChimp('member-info', $args);
$mailChimpStatus = ($mailChimpQuery['success_count'] == 1 ? 1 : 0);
$customer['Customer']['subscribed'] = $mailChimpStatus;
The mailChimp call in another Controller is:
public function mailChimp($action, $args=array()) {
$args['apikey'] = $this->apiKeys['mailchimp_api'];
$url = 'https://us8.api.mailchimp.com/2.0/lists/' . $action .'.json';
if (function_exists('curl_init') && function_exists('curl_setopt')){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_USERAGENT, 'PHP-MCAPI/2.0');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($args));
$result = curl_exec($ch);
curl_close($ch);
} else {
$json_data = json_encode($args);
$result = file_get_contents($url, null, stream_context_create(array(
'http' => array(
'protocol_version' => 1.1,
'user_agent' => 'PHP-MCAPI/2.0',
'method' => 'POST',
'header' => "Content-type: application/json\r\n".
"Connection: close\r\n" .
"Content-length: " . strlen($json_data) . "\r\n",
'content' => $json_data,
),
)));
}
return $result ? json_decode($result, true) : false;
}

FYI, I came up with my own solution:
Create an array of all the email addresses in the database
Create a for-loop that takes segments of 50 email addresses from that array and runs a batch check using member-info (https://apidocs.mailchimp.com/api/2.0/lists/member-info.php)
Manipulate the return array from the API call to extract only the email address and whether or not it's subscribed to the list.
Within the for-loop, add each 50 email addresses return values into a new array and then by the end of it; you'll have an array of all the email addresses in your database with a corresponding true/false value depending on whether or not they are subscribed to the list.
Good luck!

Related

PHP Xero API is creating duplicate overpayment entries (BankTransaction)

We are creating overpayments via the PHP Xero API.
In some cases, the overpayments are being duplicated.
Here is the code we are using:
<?php
$endpoint = 'https://api.xero.com/api.xro/2.0/BankTransactions';
$headers = array(
"Content-Type: application/json",
"Xero-tenant-id: " . $xero_access['tenant_id'],
"Authorization: Bearer " . $xero_access['token'],
);
$postFields = array(
"Type" => "RECEIVE-OVERPAYMENT",
'Contact' => ['ContactID' => $contactID],
'BankAccount' => ['accountID' => $xero_settings['account_id']],
'LineAmountTypes' => 'NoTax',
'LineItems' => [0 => [
'Description' => 'Customer Credit',
'LineAmount' => $price
]]
);
try {
$ch = #curl_init();
#curl_setopt($ch, CURLOPT_URL, $endpoint);
#curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
#curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
#curl_setopt($ch, CURLOPT_POST, 1);
#curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postFields, JSON_PRETTY_PRINT));
$response = #curl_exec($ch);
$status_code = #curl_getinfo($ch, CURLINFO_HTTP_CODE);
error_log($status_code);
error_log($response);
} finally {
#curl_close($ch);
}
?>
I am not quite sure why the transactions are being duplicated or even if it is a network issue, or something in the code above.
Is there a way to make these API calls unique and make sure a request is not sent twice?
Thanks
Could you raise a case with Xero Support and include:
Your client id, the name of the connect tenant, the date and time of a call with duplication (and your timezone), the details of the overpayment eg the contact name, date and amount

Separate Notifications do not appear on a same device subscribed to a topic

when i push multiple notifications in a loop via api subscribed to topic using FCM, the previous notification replaced by new notification on my android device. Is there a way to push multiple notifications separately. I am using PHP Curl request.
foreach ($result as $item)
{
$message = array
(
'body' => "Details:".$item['tagid'],
'title' => "Tag:".$item['event'],
'key1' => "NotificationActivity"
);
$fields = array(
'to' => '/topics/all',
'data' => array
(
'message' => $message
),
);
$headers = array
(
'Authorization: key=' . API_ACCESS_KEY,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
curl_close($ch);
}
There was problem on my Firebase service. Not identifying notification on id basis.
Problem was, I was passing 0 in id field.
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
After setting unique id of each notification, it's working:
notificationManager.notify(id /* ID of notification */, notificationBuilder.build());

OneSignal push notification sending to all user instead of one player

I am trying to send push notification to one device by its player_id stored in my database.
but whine it try it keep sending to all users
i don't know what is wrong in my code
$fields = array(
'app_id' => 'XXXXXXXXXXXXXXXXXXXX',
'include_player_ids ' => $player_ids,
'included_segments' => array(
'All'
),
'data' => $data,
'headings' => $title,
'contents' => $content,
'web_buttons' => []
);
$fields = json_encode($fields);
if($player_ids) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json; charset=utf-8',
'Authorization: Basic XXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$response = curl_exec($ch);
curl_close($ch);
just remove 'included_segments' => array('All'),
If you fill both of included_segments and include_player_ids, you will send to all selected player ids and also all selected segments. Segment All mean all subscribers.
you can read about other option on official documentation
I need to remove included_segments and web_buttons
both of them not just included_segments , when I try to just remove included_segments it give me error of {"errors":["You must include which players, segments, or tags you wish to send this notification to."]}
also I don't need 'Authorization: Basic XXXXXXXXXXXXXXXXXXXXXXXXXXXXX'.

Cloudflare API - Create DNS (NS) record using CURL PHP

I am working on adding records to my zone using curl (PHP); I want to add test.gen.ng as the DNS record with nameservers (ns1.test.com, ns2.test.com, ns3.test.com, ns4.test.com). I am able to add A records, CNAME records and others with the code at the bottom but not NS records.
{"success":false,"errors":[{"code":1004,"message":"DNS Validation Error","error_chain":[{"code":9102,"message":"content must be a string."}]}],"messages":[],"result":null}
I am having errors as shown above; sending the content below.
<?php
/* Cloudflare.com | APİv4 | Api Ayarları */
$apikey = '61543253246426e7147'; // Cloudflare Global API
$email = 'rose#gen.ng'; // Cloudflare Email Adress
$domain = 'gen.ng'; // zone_name // Cloudflare Domain Name
$zoneid = 'a30b057777777777777777dadd'; // zone_id // Cloudflare Domain Zone ID
$dnsadgeldi = 'test';
$dnsnameserver1 = 'ns1.test.com';
$dnsnameserver2 = 'ns2.test.com';
$dnsnameserver3 = 'ns3.test.com';
$dnsnameserver4 = 'ns4.test.com';
$ttl = 120;
// A-record oluşturur DNS sistemi için.
$ch = curl_init("https://api.cloudflare.com/client/v4/zones/".$zoneid."/dns_records");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'X-Auth-Email: '.$email.'',
'X-Auth-Key: '.$apikey.'',
'Cache-Control: no-cache',
// 'Content-Type: multipart/form-data; charset=utf-8',
'Content-Type:application/json',
'purge_everything: true'
));
// -d curl parametresi.
$data = array(
'type' => 'NS',
'name' => ''.$dnsadgeldi.'',
'content' => Array
(
'0' => $dnsnameserver1,
'1' => $dnsnameserver2,
'2' => $dnsnameserver3,
'3' => $dnsnameserver4
),
'zone_name' => ''.$domain.'',
'zone_id' => ''.$zoneid.'',
'proxiable' => 'false',
'proxied' => false,
'ttl' => 1
);
$data_string = json_encode($data);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
//curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data_string));
$sonuc = curl_exec($ch);
// If you want show output remove code slash.
// print_r($sonuc);
curl_close($ch);
echo $sonuc;

Php function to Send Gcm more than 1000 users

I have function code to send gcm, it works until token GCM ID have reached more than 1000 users it will not send.
this is my function code.
private static function send_message($title,$url){
global $wpdb;
$token = $wpdb->get_results( 'SELECT * FROM '.$wpdb->prefix.'devices', ARRAY_N );
foreach ($token as $key) {
$registrationIds[] = $key[1];
}
$msg = array(
'registrationIds' => $group,
'message' => $title,
'url' => $url,
'title' => 'This is a title. title',
);
$fields = array(
'registration_ids' => $registrationIds,
'data' => $msg
);
$headers = array(
'Authorization: key=' . FA_API,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
Please help me how to send push notification more than 1000 users.
This parameter specifies a list of devices (registration tokens, or
IDs) receiving a multicast message. It must contain at least 1 and at
most 1000 registration tokens.
https://developers.google.com/cloud-messaging/http-server-ref#downstream-http-messages-json
GCM limit 1000 device each message.
So you have to split $registrationIds array into to smaller arrays. Then sends them away in a loop.

Categories