Mailchimp Error: Bad Request - Your Campaign is not ready to send - php

I am using following tutorial to create campaign and send email in MailChimp using Php.
https://isabelcastillo.com/create-send-mailchimp-campaign-api-3
My Code piece are
require_once('../wp-load.php');
function isa_mailchimp_api_request( $endpoint, $type = 'POST', $body = '' )
{
// Configure --------------------------------------
$api_key = 'API KEY HERE'; // Changed API Key here
// STOP Configuring -------------------------------
$core_api_endpoint = 'https://<dc>.api.mailchimp.com/3.0/';
list(, $datacenter) = explode( '-', $api_key );
$core_api_endpoint = str_replace( '<dc>', $datacenter, $core_api_endpoint );
$url = $core_api_endpoint . $endpoint;
//print_r($url );
$request_args = array(
'method' => $type,
'timeout' => 20,
'headers' => array(
'Content-Type' => 'application/json',
'Authorization' => 'apikey ' . $api_key
)
);
if ( $body ) {
$request_args['body'] = json_encode( $body );
}
$request = wp_remote_post( $url, $request_args );
$response = is_wp_error( $request ) ? false : json_decode( wp_remote_retrieve_body( $request ) );
echo '<pre>';
print_r($response);
return $response;
}
function isa_create_mailchimp_campaign( $list_id, $subject ) {
$reply_to = 'info#newslume.com';
$from_name = 'NewsLume';
$subject= 'Another new test message 14 17';
$campaign_id = '';
$body = array(
'recipients' => array('list_id' => $list_id),
'type' => 'regular',
'settings' => array('subject_line' => $subject,
'title' => 'a test title NewsLUme',
'reply_to' => $reply_to,
'from_name' => $from_name,
'use_conversation'=> false,
'to_name'=> 'sajid',
'auto_footer'=> false,
'inline_css'=> false,
'auto_tweet'=> false,
'drag_and_drop'=> false
)
);
$create_campaign = isa_mailchimp_api_request( 'campaigns', 'POST', $body );
if ( $create_campaign ) {
if ( ! empty( $create_campaign->id ) && isset( $create_campaign->status ) && 'save' == $create_campaign->status ) {
// The campaign id:
$campaign_id = $create_campaign->id;
}
}
return $campaign_id ? $campaign_id : false;
}
function isa_set_mail_campaign_content( $campaign_id, $template_content ) {
$set_content = '';
$set_campaign_content = isa_mailchimp_api_request( "campaigns/$campaign_id/content", 'PUT', $template_content );
if ( $set_campaign_content ) {
if ( ! empty( $set_campaign_content->html ) ) {
$set_content = true;
}
}
return $set_content ? true : false;
}
$list_id='my_list_id_here'; // LIST HERE
$campaign_id = isa_create_mailchimp_campaign( $list_id, $subject );
if ( $campaign_id ) {
// Set the content for this campaign
$template_content = array(
'template' => array(
// The id of the template to use.
'id' => 47615, // INTEGER
'sections' => array(
'tst_content' => 'THIS IS THE CONTENT BODY OF MY EMAIL MESSAGE.'
)
)
);
$set_campaign_content = isa_set_mail_campaign_content( $campaign_id, $template_content );
if ( $set_campaign_content ) {
$send_campaign = isa_mailchimp_api_request( "campaigns/$campaign_id/actions/send", 'POST' );
if ( empty( $send_campaign ) ) {
// Campaign was sent!
} elseif( isset( $send_campaign->detail ) ) {
$error_detail = $send_campaign->detail;
}
}
}
I have updated all values, including API KEY, List ID, template ID etc. but still i am getting errors
Here is Error object
stdClass Object
(
[type] => http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/
[title] => Bad Request
[status] => 400
[detail] => Your Campaign is not ready to send.
[instance] => 89dc8734-2611-4f3b-a4f7-d18bd181bded
)
I checked in Mail Chimp, campaigns are created there but they are saved as Draft.
Here are my API Logs
API Logs can be seen by clicking link below
https://drive.google.com/file/d/0BwIWuJmCDI1vNHgtVm9TQm1FMVU/view?usp=drivesdk
I am able to create campaign, set a template to campaign but i cannot send emails. My Domain is also verified and authenticated with Mailchimp using guidelines.
Please check and suggest a solution

While the "Your Campaign is not ready to send" message isn't very helpful, you can check for a more detailed message in MailChimp itself. Edit the draft that the API created, and navigate to the final Confirm step. You'll see a checklist where most of the items passed, but there will also be an item that explains why the campaign failed.
When I attempted to replicate the issue, the campaign failed to send because there was some default placeholder text left unchanged in the template. Since the code you posted only sets the content for one block, this is probably the same issue you're having.
Hope this helps!

Related

How do you create an API that connects a form on a site to a CRM using PHP

I'm rather new to Gravity Forms and building API's using PHP. I need to create a script that whenever a Gravity Form is completed the API sends this as JSON data to a POST URL. They gave me the security key name and value, how do I do this using PHP? Do I need Jquery and/or AJAX?
EDIT:
This is what I have so far but I have no idea if I'm on the right path: (I omitted some fields with "X's" due to obvious potential security reasons)
<?php
function calculate_signature( $string, $private_key ) {
$hash = hash_hmac( 'sha1', $string, $private_key, true );
$sig = rawurlencode( base64_encode( $hash ) );
return $sig;
}
//set API keys
$api_key = 'XXXXXXX';
$private_key = 'XXXXXXXXXX';
//set route
$route = '/XXXXXXX.php';
//creating request URL
$expires = strtotime( '+60 mins' );
$string_to_sign = sprintf( '%s:%s:%s:%s', $api_key, 'POST', $route, $expires );
$sig = calculate_signature( $string_to_sign, $private_key );
$url = 'XXXXXXX.com' . $route . '?api_key=' . $api_key . '&signature=' . $sig . '&expires=' . $expires;
// $form = array(
// array(
// 'title' => 'API Generated Form',
// 'description' => 'This is the description for the form generated by the API',
// 'labelPlacement' => 'top_label',
// 'button' => array(
// 'type' => 'text'
// ),
// 'confirmations' => array(
// array(
// 'id' => 0,
// 'name' => 'Default Confirmation',
// 'type' => 'message',
// 'message' => 'Thanks for contacting us! We will get in touch with you shortly.',
// 'isDefault' => true,
// ),
// ),
// 'fields' => array(
// array(
// 'id' => '1',
// 'label' => 'My Text',
// 'type' => 'text'
// )
// ),
// ),
// );
$form = array(
'age' => NULL
);
//json encode array
$form_json = json_encode( $form );
//retrieve data
$response = wp_remote_request( $url, array( 'method' => 'POST', 'body' => $form_json ) );
if ( wp_remote_retrieve_response_code( $response ) != 200 || ( empty( wp_remote_retrieve_body( $response ) ) ) ){
//http request failed
die( 'There was an error attempting to access the API.' );
}
//result is in the response "body" and is json encoded.
$body = json_decode( wp_remote_retrieve_body( $response ), true );
if( $body['status'] > 202 ){
$error = $body['response'];
//form insert failed, get error information
$error_code = $error['code'];
$error_message = $error['message'];
$error_data = isset( $error['data'] ) ? $error['data'] : '';
$status = "Code: {$error_code}. Message: {$error_message}. Data: {$error_data}.";
die( "Could not post forms. {$status}" );
}
$form_id = $body['response'][0];
echo 'The following form id was created: ' . $form_id . '</br>';
?>

How to send newly created campaign with mailchimp api v2?

I am using mailchimp api v2. I am using the mailchimp recommended full api v2 php wrapper. I am able to create a campaign, but not sure how to send it. With the send method, It wants the campaign id, but I am letting mailchimp create the campaign id when creating the campaign.
My create campaign code looks like this:
$api_key = "my_api_key";
require('Mailchimp.php');
//Create Campaign
$Mailchimp = new Mailchimp($api_key);
$result = $Mailchimp->campaigns->create('regular',
array('list_id' => 'my_list_id',
'subject' => 'This is a test subject',
'from_email' => 'test#test.com',
'from_name' => 'From Name'),
array('html' => '<div>test html email</div>',
'text' => 'This is plain text.')
);
if( $result === false ) {
// response wasn't even json
echo 'didnt work';
}
else if( isset($result->status) && $result->status == 'error' ) {
echo 'Error info: '.$result->status.', '.$result->code.', '.$result->name.', '.$result->error;
} else {
echo 'worked';
}
This seems to be working for me.
$Mailchimp = new Mailchimp($api_key);
$result = $Mailchimp->campaigns->create('regular',
array('list_id' => 'my_list_id',
'subject' => 'This is a test subjects',
'from_email' => 'test#test.com',
'from_name' => 'From_Name'),
array('html' => '<div>test html email</div>',
'text' => 'This is plain text.')
);
if( $result === false ) {
// response wasn't even json
echo 'sorry';
}
else if( isset($result->status) && $result->status == 'error' ) {
echo 'Error info: '.$result->status.', '.$result->code.', '.$result->name.', '.$result->error;
} else {
echo 'worked';
$mySend = $Mailchimp->campaigns->send($result['id']);
}

PHP Header Redirect on Form Submission Not Working

I would like to let the script do a redirection on click of the submit button by using the PHP header function. However, it doesn't seem to work. Any idea how i could get it to work with PHP header function?
Here's part of the function that i thought is relevant:-
switch ( $service ) {
case 'mailchimp' :
$lastname = sanitize_text_field( $_POST['et_lastname'] );
$email = array( 'email' => $email );
if ( ! class_exists( 'MailChimp' ) )
require_once( get_template_directory() . '/includes/subscription/mailchimp/mailchimp.php' );
$mailchimp_api_key = et_get_option( 'divi_mailchimp_api_key' );
if ( '' === $mailchimp_api_key ) die( json_encode( array( 'error' => __( 'Configuration error: api key is not defined', 'Divi' ) ) ) );
$mailchimp = new MailChimp( $mailchimp_api_key );
$merge_vars = array(
'FNAME' => $firstname,
'LNAME' => $lastname,
);
$retval = $mailchimp->call('lists/subscribe', array(
'id' => $list_id,
'email' => $email,
'merge_vars' => $merge_vars,
));
if ( isset($retval['error']) ) {
if ( '214' == $retval['code'] ){
$error_message = str_replace( 'Click here to update your profile.', '', $retval['error'] );
$result = json_encode( array( 'success' => $error_message ) );
} else {
$result = json_encode( array( 'success' => $retval['error'] ) );
}
} else {
$result = json_encode( array( 'success' => $success_message ) );
}
die( $result );
break;
I tried to replace the $result with header("Location: http://www.example.com/"); but it didn't work.
The reason that you can't just change the code to $result = header('Location: ...') is actually quite simple. With this javascript call as an example:
$.post('/myscript.php', { et_lastname: 'Doe', email: 'j.doe#example.com' }, function(data) {
// do something
});
What happens:
An HTTP-POST call is made via AJAX to /myscript.php
Your code is executed, subscribing the given email address.
The PHP code returns a 301
The AJAX call will follow the redirect, but your browser will stay on the same page.
What you actually want is that when the AJAX call was successful, the browser redirects to another page. To achieve that, you'll need to update both your PHP and Javascript.
In your PHP, you'll have to return the location you want the browser to redirect to, for example:
<?php
$result = json_encode(array('location' => 'https://example.com/path/to/page'));
Right now, the PHP script just returns an json-response with a location key. The browser, nor the javascript doesn't do anything with that information unless we tell it to do so:
$.post('/myscript.php', { et_lastname: 'Doe', email: 'j.doe#example.com' }, null, 'json').done(function(data) {
// do something ...
// redirect browser to page we provided in the ajax response
window.location = data.location;
}).fail(function(data) {
// handle the error
});

Mailchimp API Integration in PHP, FNAME and LNAME not passing

I've been trying to integrate the Mailchimp API in PHP on our website, and I cannot seem to get mailchimp to take the FNAME and the LNAME.
The email always gets passed through to mailchimp and they are added to the list but the names simply don't and are always blank.
Things I have tried:
Using static names such as Dave in place of $_POST[FirstNAME] etc. but still no luck
Using MERGE1 and MERGE2 which are the alternate names for FNAME and LNAME.
Sending the email along with the FNAME and LNAME in the array for merge_vars
Putting the array in directly or as it is below within a variable ($Merge).
require('../MailCHIMP_API_PHP/Mailchimp.php');
$Mailchimp = new Mailchimp( $api_key );
$Mailchimp_Lists = new Mailchimp_Lists( $Mailchimp );
$Merge = array('FNAME' => $_POST[FirstNAME], 'LNAME' => $_POST[LastNAME]);
$subscriber = $Mailchimp_Lists->subscribe( $list_id, array(
'email' => htmlentities($_POST[Email]),
'merge_vars' => $Merge
));
if ( ! empty( $subscriber['leid'] ) ) {
//echo "success";
} else {
//echo "fail";
}
As always there is probably something simple I am missing but I have been staring at this code for so long I obviously can't see it!
This issue was solved so thought I might as well post an answer. Here is the code that works.
require('../MailCHIMP_API_PHP/Mailchimp.php');
$Mailchimp = new Mailchimp( $api_key );
$subscriber = $Mailchimp->call('lists/subscribe',
array(
'id' => $list_id,
'email' => array('email' => htmlentities($_POST[Email])),
'merge_vars' => array('FNAME' => htmlentities($_POST[FirstNAME]), 'LNAME' => htmlentities($_POST[LastNAME])),
'double_optin' => false
));
if ( ! empty( $subscriber['leid'] ) ) {
//echo "success";
} else {
//echo "fail";
}

REST API connected to Facebook

I'm currently developing a REST API on my webserver for handling calls towards a Facebook application. This way I can check if the user has a valid license in our license database before allowing him/her to post to Facebook.
I'm using two separate calls at the moment, one to authorize the client with Facebook and store his/her access token in our license database. And another to actually publish to Facebook (and also other social platforms).
The Authorization seems to work. But the publishing always returns
{
"success": false,
"error": {
"message": "(#200) User must have accepted TOS",
"type": "FacebookRequestAppException",
"code": 200
}
}
I am currently working with a development app (on Facebook), without the proper permissions submitted, would this be the issue? And if so, how can I test it if I'm not allowed to use it?
The PHP code that triggers the Exception:
try {
$app = ( new FacebookRequest($app_session, 'POST', $post_url, array( 'appsecret_proof' => $appsecret_proof ) ) )->execute()->getGraphObject();
$output = array_merge( array( 'success' => true ), $output );
} catch(FacebookRequestException $e) {
$output = array_merge( $output, array( 'success' => false, 'error' => array( 'message' => $e->getMessage(), 'type'=> 'FacebookRequestAppException', 'code' => $e->getCode() ) ) );
}
Edit:
The call:
$app_id = '1503912413161954';
$app_secret = '<app_secret_censored>';
$user_access_token = (string)$this->getIdentity()->facebook_token;
$app_access_token = (string)$this->getIdentity()->facebook_app_token;
$license_id = (int)$this->getIdentity()->license_id;
$user_account_type = (string)$this->getIdentity()->user_account_type;
$redirect_url = 'http://api.example.com/authorize';
include 'lib/fb_authorize.php';
The authorization code - have in mind that it's not yet complete, and that I'm using Yii Framwork as well to add connectivity to our database:
<?php
$http_session = new CHttpSession;
$http_session->setTimeout(60);
$http_session->setSessionName('fb_session');
$http_session->open();
require( 'vendor/autoload.php' );
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\GraphUser;
use Facebook\FacebookHttpable;
use Facebook\FacebookCurl;
use Facebook\FacebookCurlHttpClient;
FacebookSession::setDefaultApplication($app_id, $app_secret);
$helper = new FacebookRedirectLoginHelper($redirect_url, $app_id, $app_secret);
if ( isset( $user_access_token ) ) {
$user_session = new FacebookSession( $user_access_token );
try {
if ( !$user_session->validate() ) {
$user_session = null;
}
} catch ( Exception $e ) {
$user_session = null;
$output = array_merge( $output, array( 'success' => false, 'error' => array( 'message' => $e->getMessage(), 'type'=> 'ExxicaUserSessionException', 'code' => $e->getCode() ) ) );
}
} else {
try {
$user_session = $helper->getSessionFromRedirect();
} catch( Exception $e ) {
$user_session = null;
$output = array_merge( $output, array( 'success' => false, 'error' => array( 'message' => $e->getMessage(), 'type'=> 'ExxicaUserSessionException', 'code' => $e->getCode() ) ) );
}
}
if( isset( $user_session ) ) {
$appsecret_proof= hash_hmac('sha256', $user_session->getToken(), $app_secret);
if( isset( $http_session['getpages'] ) ) {
try {
// Get Page ID
$user = ( new FacebookRequest($user_session, 'GET', '/me/accounts', array( 'appsecret_proof' => $appsecret_proof ) ) )->execute()->getGraphObject();
$output = array( 'success' => true, 'user' => $user );
} catch(FacebookRequestException $e) {
$output = array( 'success' => false, 'error' => array( 'message' => $e->getMessage(), 'type'=> 'FacebookRequestUserException', 'code' => $e->getCode() ) );
}
}
try {
$app_session = new FacebookSession( $app_access_token );
} catch ( Exception $e ) {
$app_session = null;
$output = array_merge( $output, array( 'success' => false, 'error' => array( 'message' => $e->getMessage(), 'type'=> 'ExxicaAppSessionException', 'code' => $e->getCode() ) ) );
}
$c = new CDbCriteria();
$c->compare( 'id', $license_id );
$l = _Licenses::model()->find( $c );
$l->facebook_token = $user_session->getToken();
$l->facebook_app_token = $app_session->getToken();
$l->save();
$output = array_merge( $output, array( 'success' => true, 'user_token' => $l->facebook_token ) );
} else {
header( 'Location: '.$helper->getLoginUrl( array( 'manage_pages','publish_actions','public_profile' ) ) );
}
?>

Categories