MailChimp Add Subscriber using API 3.0 PHP - php

I am trying to add a php file that adds a new subscriber to my MailChimp list. Here is my form that SHOULD trigger the php file to add the new subscriber:
<form action="/scripts/freemonth_action.php" class="email_form_freemonth" method="post">
<h3>Get your first month free</h3>
<div class="form-group customised-formgroup"> <span class="icon-user"></span>
<input type="text" name="full_name" class="form-control" placeholder="Name">
</div>
<div class="form-group customised-formgroup"> <span class="icon-envelope"></span>
<input type="email" name="email" class="form-control" placeholder="Email">
</div>
<!--<div class="form-group customised-formgroup"> <span class="icon-telephone"></span>
<input type="text" name="phone" class="form-control" placeholder="Phone (optional)">
</div>-->
<div class="form-group customised-formgroup"> <span class="icon-laptop"></span>
<input type="text" name="website" class="form-control" placeholder="Website (optional)">
</div>
<!--<div class="form-group customised-formgroup"> <span class="icon-bubble"></span>
<textarea name="message" class="form-control" placeholder="Message"></textarea>
</div>-->
<div>
<br>
<button style="margin: 0 auto" type="submit" class="btn btn-fill full-width">GET FREE MONTH<span class="icon-chevron-right"></span></button>
</div>
</form>
And here is freemonth_action.php:
<?php
session_start();
if(isset($_POST['submit'])){
$name = trim($_POST['full_name']);
$email = trim($_POST['email']);
if(!empty($email) && !filter_var($email, FILTER_VALIDATE_EMAIL) === false){
// MailChimp API credentials
$apiKey = '6b610769fd3353643c7427db98d43ad6-us16';
$listID = '0cf013d1d9';
// MailChimp API URL
$memberID = md5(strtolower($email));
$dataCenter = substr($apiKey,strpos($apiKey,'-')+1);
$url = 'https://' . $dataCenter . '.api.mailchimp.com/3.0/lists/' . $listID . '/members/' . $memberID;
// member information
$json = json_encode([
'email_address' => $email,
'status' => 'subscribed',
'merge_fields' => [
'NAME' => $name,
]
]);
// send a HTTP POST request with curl
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_USERPWD, 'user:' . $apiKey);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
$result = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
echo json_encode($result);
// store the status message based on response code
if ($httpCode == 200) {
$_SESSION['msg'] = '<p style="color: #34A853">You have successfully subscribed to CodexWorld.</p>';
} else {
switch ($httpCode) {
case 214:
$msg = 'You are already subscribed.';
break;
default:
$msg = 'Some problem occurred, please try again.';
break;
}
$_SESSION['msg'] = '<p style="color: #EA4335">'.$msg.'</p>';
}
}else{
$_SESSION['msg'] = '<p style="color: #EA4335">Please enter valid email address.</p>';
}
}
I'm not even sure how to debug this, because when i do echo $result (or anything like that) I do not see anything on the page or logged to the console. I'm also open to any suggestions that use javascript as long as it is still the 3.0 API.

Your subscription code works fine. The reason you aren't seeing any result is because isset($_POST['submit']) looks for an element with the name 'submit' rather than the type 'submit'. Just add the name attribute to your button, and it should work for you:
<button style="margin: 0 auto" type="submit" name="submit" class="btn btn-fill full-width">GET FREE MONTH<span class="icon-chevron-right"></span></button>
Also, you should keep the API key secret so other people can't access your MailChimp account through the API. I'd recommend disabling your current key and creating a new one. See MailChimp's knowledgebase article about API Keys for more details.

Related

How to pass user input to an api endpoint using php curl?

I am trying to POST HTML form login credentials(email & password) to an endpoint using PHP cURL and subsequently redirect to a different page(admin/index.php) after a successful login. However, I keep getting {"success":"false","message":"please provide email and password"} error from my nodejs login endpoint. I am inexperienced with cURL hence I am failing to notice where I am getting it wrong. Please help.
<?php
session_start();
// include('includes/config.php');
$error = ''; //Variable to Store error message;
if (isset($_POST['login'])) {
if (empty($_POST['email']) || empty($_POST['password'])) {
$error = "Email or Password is Invalid";
} else {
//Define $user and $pass
$email = ($_POST['email']);
$password = ($_POST['password']);
$url = 'http://localhost:5000/auth/login';
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_USERPWD, $email.":".$password);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode(['email' => $email, 'password' =>$password]));
$result = curl_exec($curl);
echo $result;
if ($result == 200) {
$_SESSION['alogin'] = $email;
header("Location: admin/index.php"); // Redirecting to other page
} else {
$error = "Try to login.";
}
curl_close($curl);
}
}
?>
Here is the HTML form.
<div class="panel panel-info">
<div class="panel-heading">
LOGIN FORM
</div>
<div class="panel-body">
<form role="form" method="post" name="login" action="index.php" role="form">
<div class="form-group">
<label>Enter Email</label>
<input class="form-control" type="email" name="email" autocomplete="off" />
</div>
<div class="form-group">
<label>Password</label>
<input class="form-control" type="password" name="password" autocomplete="off" />
</div>
<button type="submit" name="login" class="btn btn-info">LOGIN</button>
</form>
</div>
</div>
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode(['email' => $email, 'password' =>$password]));
There are two formats for CURLOPT_POSTFIELDS Neither is JSON.
$post = 'key1=value1&key2=value2&key3=value3';
$post = array('key1'=>$value1,'key2'=>$value2,'key3'=>'value3');
You may need to use urlencode() on username and password.
Were you told to use the CURLOPT_USERPWD,
That is unconventional.
And this is just wrong. It might work, but it is still wrong.
if ($result == 200) {
Use
$status = curl_getinfo($ch,CURLINFO_HTTP_CODE);
if ($status == 200){...

How to log in with username or email using NATS API in php?

I have a login form that uses NATS API (Next-Generation Administration and Tracking System). In my form I have username and password fields that successfully log user on site. Now I want user to be able to also write his email if he wishes in username field and to be successfully logged in on site. I need to perform an additional search on that members email to get their username from NATS to authenticate them. Since I am using the member_auth table if a member enters an email address I would need to get the username from NATS using the API to perform the login. I need help on how to write that in this function that logs in user.
function.php
function elx_nats_api($endpoint = "member/details", $member_username, $member_email, $nats_site_id = 1){
$API_credentials["URL"] = "http://nats.site.com/api/";
$API_credentials["USR"] = "Oktogon";
$API_credentials["KEY"] = "51e2a35b50d9fd1f15a31827f32427edd";
if( $member_username == "" ) $member_username = $_SERVER["REMOTE_USER"];
// CURL
$curl = curl_init();
$data = array(
'username' => $member_username,
'email' => $member_email,
'full_info' => true,
'subscriptions' => true,
'siteid' => $nats_site_id
);
$data_string = http_build_query($data);
$url = $API_credentials["URL"] . $endpoint . "?" . $data_string;
$headers = array(
"api-key: ".$API_credentials["KEY"],
"api-username: ".$API_credentials["USR"]
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_URL, $url);
$resp = curl_exec($curl);
$result = json_decode($resp, true);
// Close request to clear up some resources
curl_close($curl);
// Return the Result Array
return $result;
}
form.php
%%PRX_FORM%%
<div class="logbox">
<div class="box clear">
<h2>Members Area</h2>
<div class="logTypes">
<input type=text name=uid class="logtextbox" placeholder="Username">
<input type=password name=pwd class="logtextbox" placeholder="Password"><br>
<input type=text name=img class="logtextbox" placeholder="Enter the code shown below"></br>
<img style="margin: 0 auto;" src="/img.cptcha">
<div style="text-align: center">Remember my login: <input name=rmb type=checkbox value=”y”></div>
</div>
</div>
<input type="submit" value="submit" class="logBtn">
</div>
</form>
I am using NATS 4.1 and any help is appreciated.

Linking Mailchimp to Sign-Up Boxes

I am linking an e-mail sign-up and a post code (UK English for zip code) input box (see html code below) to an existing Mailchimp e-mail list. I have taken out the $apiKey, $listId and $submit_url identifiers from the code below. I have been able to successfully link the Mailchimp list to the e-mail input (so that e-mail address are populated when they are input in the Mailchimp list but I cannot figure out how to get post codes to automatically update in mailchimp list when they are input).
I am relatively new to php and would be so grateful for any help.
<div class="subscribe">
<form method="post" action="bokacsubscribe.php" role="form">
<input type="email" placeholder="Enter your e-mail address..." class="subscribe-input" name="email" style="margin-bottom: 10px;">
<form method="post" action="bokacsubscribe.php" role="form">
<input type="email" placeholder="Enter your postcode" class="subscribe-input" name="postcode" style="margin-bottom: 10px;">
<button type="submit" class="btn btn-subscribe success" style="border-radius:120px;background-color:rgb(241,174,200);border:1px solid rgb(241,174,200)"><b>Send</b></button>
<input type="hidden" name="referr" id="referr"/>
</form>
</div>
</div>
<?php
// Credits: https://gist.github.com/mfkp/1488819
session_cache_limiter('nocache');
$apiKey = ''; - // How get your Mailchimp API KEY - http://kb.mailchimp.com/article/where-can-i-find-my-api-key
$listId = ''; - // How to get your Mailchimp LIST ID - http://kb.mailchimp.com/article/how-can-i-find-my-list-id
$submit_url = ""; - // Replace us2 with your actual datacenter
$double_optin = false;
$send_welcome = false;
$email_type = 'html';
$email = $_POST['email'];
$merge_vars = array( 'YNAME' => $_POST['yname'] );
$data = array(
'email_address' => $email,
'apikey' => $apiKey,
'id' => $listId,
'double_optin' => $double_optin,
'send_welcome' => $send_welcome,
'merge_vars' => $merge_vars,
'email_type' => $email_type
);
$payload = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $submit_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, urlencode($payload));
$result = curl_exec($ch);
curl_close ($ch);
$data = json_decode($result);
if ($data->error) {
// do whatever you do on failure here
} else {
// do whatever you do on success here
$arrResult = array ('response'=>'success');
}

How do I implement a MailChimp API form embed?

sorry for the perhaps naive question, but I have absolutely 0 experience in web design and I've been plowing through .html/.css for 2 days straight, and I think it's time I just seek some help.
I'm making a simple landing page for a conference, and I've been using a few templates. The most recent template I'm using is perfect, except the email signup sends direct emails to my account, rather than creating a list using a service such as mailchimp - highly inefficient.
A previous template I tried out, however, did implement mailchimp, and I was wondering how I might just grab its code and throw it in the current template I have.
Here is the subscribe.php from the mailchimp template:
<?php
$apiKey = '';
$listId = '';
$double_optin=true;
$send_welcome=true;
$email_type = 'html';
$email = $_POST['email'];
//replace us2 with your actual datacenter
$submit_url = "http://us1.api.mailchimp.com/1.3/?method=listSubscribe";
$data = array(
'email_address'=>$email,
'apikey'=>$apiKey,
'id' => $listId,
'double_optin' => $double_optin,
'send_welcome' => $send_welcome,
'email_type' => $email_type
);
$payload = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $submit_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, urlencode($payload));
$result = curl_exec($ch);
curl_close ($ch);
$data = json_decode($result);
if ($data->error){
echo $data->error;
} else {
echo "Thanks! We'll keep you updated on the conference :)";
}
?>
and here is the snippet of code in index.html:
<div class="row">
<div class="col-md-6 col-sm-12 col-md-offset-3 subscribe">
<form class="form-horizontal" role="form" action="subscribe.php" id="subscribeForm" method="POST">
<div class="form-group">
<div class="col-md-7 col-sm-6 col-sm-offset-1 col-md-offset-0">
<input class="form-control input-lg" name="email" type="email" id="address" placeholder="Enter your email" data-validate="validate(required, email)" required="required">
</div>
<div class="col-md-5 col-sm-4">
<button type="submit" class="btn btn-success btn-lg">SIGN UP TO BE NOTIFIED</button>
</div>
</div>
</form>
<span id="result" class="alertMsg"></span> </div>
</div>
For reference, here are the subscribe.php and index.html snippets from the non-mailchimp template:
Subscribe.php
<?php
if ( isset( $_POST['newsletter_submit'] ) ) {
// Initialize error array
$newsletter_errors = array();
// Check email input field
if ( trim( $_POST['newsletter_email'] ) === '' )
$newsletter_errors[] = 'Email address is required';
elseif ( !preg_match( "/^[_\.0-9a-zA-Z-]+#([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z] {2,4}$/i", trim( $_POST['newsletter_email'] ) ) )
$newsletter_errors[] = 'Email address is not valid';
else
$newsletter_email = trim( $_POST['newsletter_email'] );
// Send email if no input errors
if ( empty( $newsletter_errors ) ) {
$email_to = "register#neustep.org"; // Change to your own email address
$subject = "NeuSTEP Subscription";
$body = "Subscriber details: " . $newsletter_email . "\r\n";
mail( $email_to, $subject, $body, $headers );
echo 'Thank you for subscribing!';
} else {
echo 'Please go back and correct the following errors:<br />';
foreach ( $newsletter_errors as $error ) {
echo $error . '<br />';
}}}
?>
Index.html snippet
<div class="newsletter">
<form action="subscribe.php" method="post" id="newsletter-form">
<p class="form-field">
<label for="newsletter_email" class="visually-hidden">Your email address</label>
<i class="icon ion-paper-airplane" aria-hidden="true"></i>
<input type="text" name="newsletter_email" id="newsletter_email" value="" placeholder="Your email address" />
</p>
<p class="form-submit">
<input type="submit" name="newsletter_submit" id="newsletter_submit" value="Get Notified" />
</p>
</form>
</div>
thanks for helping! sorry for the long post. I'm not sure what the etiquette on stackoverflow is, so if i'm asking a crappy question, let me know.
Your form is ok, and you need to implement a handler for subscribing like;
subscribe.php
<?php
if (empty($_POST["newsletter_email"]) {
die("You should provide email!");
} else if (!preg_match( "/^[_\.0-9a-zA-Z-]+#([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z] {2,4}$/i", trim( $_POST['newsletter_email'] ) )) {
die("Email address is not valid!");
} else {
$newsletter_email = trim( $_POST['newsletter_email'] );
}
$apiKey = '';
$listId = '';
$double_optin=true;
$send_welcome=true;
$email_type = 'html';
$email = $newsletter_email;
//replace us2 with your actual datacenter
$submit_url = "http://us1.api.mailchimp.com/1.3/?method=listSubscribe";
$data = array(
'email_address'=>$email,
'apikey'=>$apiKey,
'id' => $listId,
'double_optin' => $double_optin,
'send_welcome' => $send_welcome,
'email_type' => $email_type
);
$payload = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $submit_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, urlencode($payload));
$result = curl_exec($ch);
curl_close ($ch);
$data = json_decode($result);
if ($data->error){
echo $data->error;
} else {
echo "Thanks! We'll keep you updated on the conference :)";
}
?>

Problems sending data to PHP with Curl

I need some advice with this curl script. I am trying to send values from the FORM to the curl script, but seems that the curl script doesn`t receive the info.
Here is the script:
<?php
if($_SERVER['REQUEST_METHOD'] != 'POST') {
$self = $_SERVER['PHP_SELF'];
?>
<form method="post" action="<?php echo $self; ?>" class="form-horizontal">
<fieldset>
<legend>SMS Contact</legend>
<div class="control-group">
<label for="basic" class="control-label">Name and Surname</label>
<div class="controls">
<input type="text" name="name" id="name" disabled class='input-square' value="<?php print $contactname;?> <?php print $contactsurname;?>">
</div>
</div>
<div class="control-group">
<label for="basic" class="control-label">Mobile No</label>
<div class="controls">
<input type="text" name="mobile" id="mobile" disabled class='input-square' value="<?php echo urlencode($contactmobile);?>">
</div>
</div>
<div class="control-group">
<label for="textcounter" class="control-label" id="textcounter">Textarea</label>
<div class="controls">
<textarea name="textcounter" id="textcounter" class='input-square span9 counter' data-max="160" rows='6'></textarea>
</div>
</div>
<div class="form-actions">
<button class="btn btn-primary" type="submit">Send SMS</button>
</div>
</fieldset>
</form>
<?php
} else {
$mobile = $_POST['mobile'];
$text = $_POST['textcounter'];
$username = 'xxxx';
$password = 'xxxx';
// Set Timezone
date_default_timezone_set('Africa/Johannesburg');
$date = date("m/d/y G.i:s", time());
// Create Unique ID
$code = md5(time());
$newid = $code.$clientid;
$sql="INSERT INTO sent_itmes (sent_id, sent_message, sent_date, sent_quantity, client_id, sent_mobile)VALUES('$newid', '$text', '$date', '1', '$clientid', '$mobile')";
$result=mysql_query($sql);
$url = "http://bulksms.2way.co.za/eapi/submission/send_sms/2/2.0"; // URL to calc.cgi
$fields = array(
'site'=>'',
'username'=>($username),
'password'=>($password),
'message'=>urlencode($text),
'msisdn'=>urlencode($mobile)
);
$fields_string="?";
//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string,'&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
curl_setopt($ch,CURLOPT_POST,count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
//execute post
ob_start();
curl_exec($ch);
ob_end_clean();
echo '<div class="alert alert-block alert-success">
<a class="close" data-dismiss="alert" href="#">×</a>
<h4 class="alert-heading">Success!</h4>
Your message has been Sent!
</div><br/><br/>Search Contact';
//close connection
curl_close($ch);
}
?>
When submitting the form, I get the error from response server "No recipients specified", so this means that the form value "mobile" doesnt pass though the value to the curl.
Help please, going off my mind.
Try adding a header that describes the content you post and maybe content you apply
curl_setopt ( $ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/x-www-form-urlencoded',
'Accept: text/html',
'Expect: ',
) );
use this for sending data
//open connection
$ch = curl_init($url);
curl_setopt($ch,CURLOPT_POST,count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS,POSTVARS.$fields_string); // this line is edited..
curl_setopt($ch, CURLOPT_FOLLOWLOCATION ,1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
//execute post
ob_start();
curl_exec($ch);
your order was wrong...
more info http://www.askapache.com/php/sending-post-form-data-php-curl.html
When you submit form with disabled field, that field do not sent:
<input type="text" name="mobile" id="mobile" disabled class='input-square' value="<?php echo urlencode($contactmobile);?>">
If you want to send "mobile", you should add hidden field for it. And maybe replace disabled field name

Categories