mailchimp api 2.0 subscribe through php? - php

I need an example of how to subscribe a email address to mailchimp newsletter.
Please check new api link here:
https://bitbucket.org/mailchimp/mailchimp-api-php
This is new malichimp api and I am not sure how to use it. :(
For MailChimp 2.0 API, not for 1.3.
Please somebody provide an example on how to subscribe user to mailchimp.
Thank You.
Edit1: Already tried following code, but not working:
$merge_vars = array('MM1'=>$mm1);
$MailChimp = new Mailchimp($apikey);
$result = $MailChimp->call('lists/subscribe', array(
'id' => $listid,
'email' => array('email'=>$email),
'merge_vars' => $merge_vars,
'double_optin' => false,
'update_existing' => true,
'replace_interests' => false,
'send_welcome' => false,
));
print_r($result);
But not working. Throwing following error:
Fatal error: Call to a member function call() on a non-object in subscribe.php on line 22

Referring to the documentation, this should be like so:
$merge_vars = array('MM1'=>$mm1);
$listid = 'YOURLISTID';
$MailChimp = new Mailchimp($apikey);
$result = $MailChimp->lists->subscribe($listid,
array('email'=>"contact#twittstrap.com"),
$merge_vars,
false,
true,
false,
false
);
print_r($result);
Tested and working.

this might be helpful for some, simple mailchimp subscriber API code sample with php
mailchimp subscriber API code example in PHP

Here is with Try & Catch (example for when dup emails)
header('Content-Type: application/json');
include_once 'Mailchimp.php';
$api_key = '';
$list_id = '';
$email = 'hello#email.com';
$merge_vars = array();
$Mailchimp = new Mailchimp($api_key);
$Mailchimp_Lists = new Mailchimp_Lists($Mailchimp);
try{
$subscriber = $Mailchimp_Lists->subscribe(
$list_id,
array('email'=>htmlentities($email)),
$merge_vars,
false,
false,
false,
false
);
echo json_encode(array('status' => !empty($subscriber['leid'])?'submitted':'error'));
} catch(Mailchimp_Error $e){
echo json_encode(array(
'status' => 'error',
'message' => $e->getMessage()
));
}
Readmore about subscribe() : https://apidocs.mailchimp.com/api/2.0/lists/subscribe.php

Subscribe through php using curl.
$apikey = 'xxxxxxxxxx'; //your apikey
$listId = 'xxxxxxxxxx'; // your list id
$endpoint = "http://yourdatacenter.api.mailchimp.com/3.0/lists/"; // find your datacenter in your apikey( xxxxxxxxxxxxxxxxxxxxxxxx-us13 <= this is your datacenter)
$auth = base64_encode( 'user:'. $apikey );
$data = array(
'apikey' => $apikey,
'email_address' => 'yourvalid_email_address',
'status' => 'subscribed',
'merge_fields' => array());
$json_data = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $endpoint.$listId.'/members/');
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',
'Authorization: Basic '.$auth));
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_data);
$result = curl_exec($ch);
echo "<pre>"; // Response form mailchimp
print_r(json_decode($result,true));

Here is example may it helpful for some one.
mailchimp subscriber api example

Related

Mailchimp api 3.0 error: "Schema describes object, array found instead" is the code or on mailchimp's end?

I need to bulk update subscribers in my mailchimp lists using mailchimp's api and subscriber lists in my database.
I am trying implement the solution to the question here:
Mailchimp API 3.0 Batch Subscribe
but I'm getting the error
{"type":"http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/","title":"Invalid Resource","status":400,"detail":"The resource submitted could not be validated. For field-specific details, see the 'errors' array.","instance":"8198a6e9-9a7c-4e00-8365-3a7062f047f3","errors":[{"field":"","message":"Schema describes object, array found instead"}]}
I've seen people with similar issues, and sometimes it's a problem on mailchimp's end and sometimes it's a problem with how the data is being passed. Any insight into whether I need to fix the code or contact mailchimp would be appreciated!
script in question:
<?php
$apikey = 'myapi'; // Your Mailchimp ApiKey
$list_id = 'mylist'; // your List ID Where you want to add subscriber
$servername = 'myserver';
$username = 'myun';
$password = 'mypw';
$dbname = 'mydb';
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die('Connection failed: ' . $conn->connect_error);
}
$sql = 'SELECT * FROM emails Limit 2';
$result = $conn->query($sql);
$finalData = array();
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc()) {
$individulData = array(
'apikey' => $apikey,
'email_address' => $row['email'],
'status' => $row['status'],//subscribe,pending,unsubscribe
'merge_fields' => array(
'FNAME' => $row['FNAME'],
'LNAME' => $row['LNAME'],
'BARCODE' => $row['BARCODE'],
'SERVICE' => $row['SERVICE'],
'PURCHASE' => $row['PURCHASE'],
)
);
$json_individulData = json_encode($individulData);
$finalData['operations'][] =
array(
"method" => "PUT",
"path" => "/lists/$list_id/members/",
"body" => $json_individulData
);
}
}
$api_response = batchSubscribe($finalData, $apikey);
print_r($api_response);
$conn->close();
/**
* Mailchimp API- List Batch Subscribe added function
*
* #param array $data Passed you data as an array format.
* #param string $apikey your mailchimp api key.
*
* #return mixed
*/
function batchSubscribe(array $data, $apikey)
{
$auth = base64_encode('user:' . $apikey);
$json_postData = json_encode($data);
$ch = curl_init();
$dataCenter = substr($apikey, strpos($apikey, '-') + 1);
$curlopt_url = 'https://' . $dataCenter . '.api.mailchimp.com/3.0/batches/';
curl_setopt($ch, CURLOPT_URL, $curlopt_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',
'Authorization: Basic ' . $auth));
curl_setopt($ch, CURLOPT_USERAGENT, 'PHP-MCAPI/3.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_postData);
$result = curl_exec($ch);
return $result;
}
?>
I had a similar error.
Hope it's still relevant for future users.
The main problem is the mailchimp documentation.
$operations = [];
foreach ($customers as $customer)
{
if ($customer->hasEmail())
{
$operations['operations'][] = (object) [
'method' => 'post',
'path' => '/lists/' . $settings['list_id'] . '/members',
'body' => json_encode([
'email_address' => $customer->email,
'status' => 'subscribed',
'merge_fields' => (object) [],
])
];
}
}
try
{
$response = $mailchimp->batches->start($operations);
print_r($response);
}
catch (\Exception $e)
{
// var_dump($e->getMessage());
print_r($e->getResponse()->getBody()->getContents());
}
I had a similar issue, the message was "Schema describes string, boolean found instead". It seems that json_encode() has a problem with special characters.
I solved it using this code, maybe it will work for you:
utf8_encode($row['FNAME']) or you could try using (string).
I hope this can help somebody. I used POST instead of PUT
Example:
$stringData = array(
'apikey' => $api_key,
'email_address' => $row['email'],
'status' => 'subscribed',
'merge_fields' => array(
'FNAME' => utf8_encode($row['FNAME']),
'LNAME' => utf8_encode($row['LNAME'])
)
);
casting object is unnecessary.
refactored from Kevin's code:
$operations = [];
foreach ($customers as $customer)
{
if ($customer->hasEmail())
{
$operations[] = [
'method' => 'post',
'path' => '/lists/' . $settings['list_id'] . '/members',
'body' => json_encode([
'email_address' => $customer->email,
'status' => 'subscribed',
'merge_fields' => [],
])
];
}
}
try
{
$response = $mailchimp->batches->start(['operations'=>$operations]);
print_r($response);
}
catch (\Exception $e)
{
// var_dump($e->getMessage());
print_r($e->getResponse()->getBody()->getContents());
}
missing bit is the operation list must be owned by 'operations' key in request payload

instamojo payment gate way implementation in server

we are using instamojo payment gate way in our website,its working successfully in localhost but not in live server(godady) its getting error like 500(page not working). may i request you can you suggest me to solve my problem
we are using below code
<?php
$product_name=$_POST['product_name'];
$price=$_POST['product_price'];
$name=$_POST['name'];
$phone=$_POST['phone'];
$email=$_POST['email'];
include 'src/instamojo.php';
$api = new Instamojo\Instamojo('a9979a24478f77cf21688ca8a8f46151', '025caf249cec5ad8345192a15e71602b');
try {
$response = $api->paymentRequestCreate(array(
"purpose" => $product_name,
"amount" => $price,
"buyer_name" => $name,
"phone" => $phone,
"send_email" => true,
"send_sms" => false,
"email" => $email,
"allow_repeated_payments" => false,
"redirect_url" => "http://e2dshop.com/thanq.php",
"webhook" => "http://e2dshop.com/webhook.php"
));
// print_r($response);
$pay_ulr = $response['longurl'];
echo "<script>window.location.href='$pay_ulr'</script>";
//header("Location : $pay_ulr");
exit();
}
catch (Exception $e) {
print('Error: ' . $e->getMessage());
}
?>
I know it's been very long since you asked your question, but today i faced the same issue so I am sharing my solution.
The code you pasted will work fine on localhost, but will show HTTP Error 500.
For the payment gateway to work on GoDaddy or on any live server you need to use CURL.
Please refer to the code below.
<?php
if((isset($_POST['totalAmount'])) && (!empty($_POST['totalAmount'])))
{
$amount = $_POST['totalAmount'];
$purpose = $_POST['product_name'];
$phone = $_POST['buyer_phone'];
$buyername = $_POST['buyer_name'];
$email = $_POST['buyer_email'];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.instamojo.com/api/1.1/payment-requests/');
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER,
array("X-Api-Key:yourApiKeyHere",
"X-Auth-Token:yourAuthTokenHere"));
$payload = Array(
'purpose' => $purpose,
'amount' => $amount,
'phone' => $phone,
'buyer_name' => $buyername,
'redirect_url' => 'https://www.yourwebsitehere.com/thankyou.php',
'webhook' => 'https://www.yourwebsitehere.com/webhook.php',
'send_email' => true,
'send_sms' => true,
'email' => $email,
'allow_repeated_payments' => false
);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($payload));
$response = curl_exec($ch);
curl_close($ch);
$data = json_decode($response,true);
var_dump($data);
$site=$data["payment_request"]["longurl"];
header('HTTP/1.1 301 Moved Permanently');
header('Location:'.$site);
} else {
header("Location:payment.php");
}
?>
I hope this helps you or the others who's facing the same issue currently :)
Give's a thumbs up if this helps.
Thanks.

Send email to assigned user Sugar CRM Rest API

Normally assigned user gets email when created/updated a lead in Sugar CRM.
I am using the REST API to add/update leads in suite CRM.I need to send email to the assigned user.How can it be done?
$url = "http://{site_url}/service/v4_1/rest.php";
$username = "admin";
$password = "password";
function call($method, $parameters, $url)
{
ob_start();
$curl_request = curl_init();
curl_setopt($curl_request, CURLOPT_URL, $url);
curl_setopt($curl_request, CURLOPT_POST, 1);
curl_setopt($curl_request, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
curl_setopt($curl_request, CURLOPT_HEADER, 1);
curl_setopt($curl_request, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl_request, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_request, CURLOPT_FOLLOWLOCATION, 0);
$jsonEncodedData = json_encode($parameters);
$post = array(
"method" => $method,
"input_type" => "JSON",
"response_type" => "JSON",
"rest_data" => $jsonEncodedData
);
curl_setopt($curl_request, CURLOPT_POSTFIELDS, $post);
$result = curl_exec($curl_request);
curl_close($curl_request);
$result = explode("\r\n\r\n", $result, 2);
$response = json_decode($result[1]);
ob_end_flush();
return $response;
}
$login_parameters = array(
"user_auth" => array(
"user_name" => $username,
"password" => md5($password),
"version" => "1"
),
"application_name" => "RestTest",
"name_value_list" => array(),
);
$login_result = call("login", $login_parameters, $url);
$session_id = $login_result->id;
$set_entry_parameters = array(
"session" => $session_id,
"module_name" => "Leads",
"name_value_list" => array(
array("firstnamename" => "name", "email1" => "email","assigned_user_id"=>"xxxxx-xxxxx-xx-x-xxx"),
),
);
$set_entry_result = call("set_entry", $set_entry_parameters, $url);
?>
I can update the record.I need to send the email to the assigned user id.
Looks like it's a known bug in Sugar API since version 6.5 (and not yet corrected).
Creating a new Lead via the API not sending email Version 6.5.16 (Build 1082)
Defect 68115: Cases created or updated and assigned via REST API doesn't send out a notification
In the original forum post a guy suggested using logic hooks as a workaround. I know logic hooks exist but never used them, though I believe it's a path to try.
Good luck!

How to get a list of users of bugzilla project using XMLRPC after login

I'm looking for XMLRPC keywords to find out a list of users of a BUGZILLA project.
Here is my code, login works fine and im' able to use several keywords to find out what i need : Bug.search, Bug.fields.
public function loginBz($url,$login,$password,$getResult)
{
set_time_limit(0);
$URI = $url;
$xml_data = array(
'login' => $login,
'password' => $password,
'remember' => 1
);
$ch = curl_init();
$file_cookie = tempnam ("/tmp", "CURLCOOKIE");
$options = array(
//CURLOPT_VERBOSE => true,
CURLOPT_URL => $URI,
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array( 'Content-Type: text/xml', 'charset=utf-8' )
);
curl_setopt($ch, CURLOPT_TIMEOUT,60);
curl_setopt_array($ch, $options);
$request = xmlrpc_encode_request("User.login", $xml_data);
// var_dump($request);
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
curl_setopt($ch, CURLOPT_COOKIEJAR, $file_cookie);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$server_output = curl_exec($ch); // Array( [id] => 1 ) for example
$response = xmlrpc_decode($server_output);
//print_r ($response);
if($getResult)
return $response;
else
return $ch;
}
public function getFieldsBz($product,$component,$ch){
$xml_data = array(
'product' => $product,
'component' => '$component'
);
$request = xmlrpc_encode_request("Bug.user", $xml_data); // create a request for filing bugs
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
$server_output = curl_exec($ch); // Array( [id] => 1 ) for example
$response = xmlrpc_decode($server_output);
return $response;
}
I've been searching into BugZilla API but did not found what I need : List of Users for a product Bz.
Does anyone know which keyword I have to use in xmlrpc_encode_request(keyword,array_filter) ?
It would help :)
First there isn't a method called Bug.user, see https://www.bugzilla.org/docs/4.4/en/html/api/Bugzilla/WebService/Bug.html for a complete list.
There is a method called User.get, see https://www.bugzilla.org/docs/4.4/en/html/api/Bugzilla/WebService/User.html#get
There is a parameter called groups which may do what you want depending on how you setup Bugzilla security.
You can use https://xmlrpc.devzing.com/ to experiment or if you upgrade to Bugzilla 5.x you can use the new REST API. https://www.bugzilla.org/docs/5.0/en/html/api/Bugzilla/WebService/Server/REST.html

Getting error in setting Transdirect Shipping sender APi code

I am trying to implement transdirect.com shipping set sender API to my website but i am getting error i don't know what is the main cause of it.
here is the snippet::
$params = array(
'session' => $session,
'postcode' => '2164',
'name' => 'abc',
'company'=>'abc',
'email' => $email ,
'phone' => '4561237',
'streetName' => 'abcStreet',
'streetNumber' => '28',
'streetType' => 'St',
'suburb' => 'JHONFEILD',
'state' => 'NSW',
'pickupDate' => date( 'Y-m-d' ),
'pickupTime' => '1-4pm',
'hydraulicGate' =>'false'
);
$query = http_build_query($params);
$query = 'http://transdirect.com.au/api/v2/booking/sender?'.$query;
$result = json_decode( curl_sender( $query, $session, $email, $arg = 'sender') );
// curl_sender method::
function curl_sender( $url, $session, $email, $arg ) {
if ( $arg == 'sender' ) {
$datastring = "postcode=2164&name=Tara Trampolines&company=abc&email=".$email."&phone=0280049375&streetName=Unit 4/28 Victoria St&streetNumber=28&streetType=St&suburb=SMITHFIELD&state=NSW&pickupDate". date( 'Y-m-d' )."&pickupTime=1-4pm&hydraulicGate=false";
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $datastring);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data1 = curl_exec( $ch );
curl_close( $ch );
return $data1;
}
I am getting:
stdClass Object (
[message] => Must be authenticated-please create a session first.
[code] => 403
)
Here is the link from we have implemented the api::
http://transdirect.com.au/api/v2/documentation
please specify how we can authenticate each method.
Any help will be appreciable, Thanks in advance.
You've to create a valid session before you requesting the API.
Create the session:
$credentials = array(
'email' => 'test#example.com',
'password' => 'secret'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $credentials);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
var_dump($response);
Take a look at the session part: http://transdirect.com.au/api/v2/documentation
You can't mix the session creation process and the real API request.
Create session
Create API request with this session from step 1.
I'm not sure but I think you don't have to use the valid session as any parameter.
The documentation says only create a valid session, there is no parameter specified to append the session, so creation is maybe enough.
This is maybe very important for you:
Confirm booking with any special instructions etc. Once the booking is
confirmed your session is cleared and you will need to
re-authenticate.

Categories