Mailchimp double_optin option not working - php

I've followed this tutorial to implement mailchimp API v2.0 on my website.
It works great, however the double_optin option that I wanted to add and set to false (so that users don't need to validate their registration via e-mail) doesn't seem to be working. It's like if it was not taken into consideration at all, users still need to validate the registration via e-mail.
Is 'double_optin' => false placed at the wrong place? I had a look at mailchimp documentation but my level in programmation is not good enough to identify what is wrong.
Thanks for your help
<?php
$api_key = "12345486-us8";
$list_id = "123";
require('Mailchimp.php');
$Mailchimp = new Mailchimp( $api_key );
$Mailchimp_Lists = new Mailchimp_Lists( $Mailchimp );
$subscriber = $Mailchimp_Lists->subscribe( $list_id, array( 'email' => htmlentities($_POST['email']),'double_optin' => false ) );
if ( ! empty( $subscriber['leid'] ) ) {
echo "success";
}
else
{
echo "fail";
}
?>

According to this (admittedly unofficial-looking) Mailchip_Lists documentation, you'll want to pass FALSE as the 5th parameter to subscribe().
Example:
$double_optin = FALSE;
$subscriber = $Mailchimp_Lists->subscribe(
$list_id,
array('email' => htmlentities($_POST['email'])),
NULL, // merge_vars
'html', // email_type
$double_optin
);

Related

WPallimport function to create user from csv column

My goal is to import a csv file with houses for sale and generate realtors as wordpress/buddypress user if they don't exist yet. I want to do so by using a custom function in WP all import. Addtitionally i would like to set the buddypress membertype to "realtor" for internal user
I will map the source field to a custom field in the import config
[create_realtor{realtor_column}]
in my case that is [create_realtor{properties[1]/property[2]/value[1]}]
As it is a user for internal purposes, i don't need the actual realtor contact details, so the user email will be realtor#mydomain.com, pass can generated, email to realtor not needed.
I found that a user can be generated as below source:
if( null == username_exists( $email_address ) ) {
// Generate the password and create the user
$password = wp_generate_password( 12, false );
$user_id = wp_create_user( $email_address, $password, $email_address );
// Set the nickname
wp_update_user(
array(
'ID' => $user_id,
'nickname' => $email_address
)
);
// Set the role
$user = new WP_User( $user_id );
$user->set_role( 'subscriber' );
} // end if
How can i wrap all in a function that will generate the user based on the realtor name in my feed
would it be like below?
function create_realtor($realtor) {
$emailadress = $realtor . '#mydomain.com' ;
if( null == username_exists( $email_address ) ) {
// Generate the password and create the user
$password = wp_generate_password( 12, false );
$user_id = wp_create_user( $email_address, $password, $email_address );
// Set the nickname
wp_update_user(
array(
'ID' => $user_id,
'nicename' => $nicename, //realtor
'nickname' => $email_address //realtor#mydomain.com
)
);
// Set the role
$user = new WP_User( $user_id );
$user->set_role( 'subscriber' );
// Set the member type of user to 'realtor'.
$member_type = bp_set_member_type( $user_id, 'realtor' );
} // end if
}
I tried above, but it results in a message saying "Custom Field Value template is invalid: Unexpected token XPATH, statement was expected."
I am a bit lost here on how to procede
You issue is that you're not calling your custom function correctly. The function call should have round brackets like this:
[create_realtor({properties[1]/property[2]/value[1]})]
Always start simple:
Read through Example 2 below
Get a simple function working first
Then build on it and insert your custom logic
https://www.wpallimport.com/documentation/developers/custom-code/inline-php/

Mailchimp PHP api v.2, User already exists or unsubscribe returns error

I'm using the Mailchimp v.2 API PHP wrapper to handle subscriptions... https://bitbucket.org/mailchimp/mailchimp-api-php however if a subscriber already exists on the list or the subscriber was unsubscribed, it returns an error, and I want to know a way I can code this to where if either of those cases exist, it will continue running the code without displaying an error. I apologize if this is a simple question.
$api_key = "XXXXXXXXX";
$list_id = "XXXXXX";
require('Mailchimp.php');
$Mailchimp = new Mailchimp( $api_key );
$Mailchimp_Lists = new Mailchimp_Lists( $Mailchimp );
$merge_vars = array('FNAME'=>htmlentities($_POST['stripeFirstName']), 'LNAME'=>htmlentities($_POST['stripeLastName']) );
$subscriber = $Mailchimp_Lists->subscribe( $list_id, array( 'email' => htmlentities($_POST['stripeEmail']) ), $merge_vars );
You'll want to make use of try and catch. Mailchimp is pretty verbose about what goes wrong.
try {
$result = $Mailchimp_Lists->subscribe(
$list_id,
array(/* ... */), // primary subscriber data
array(/* ... */), // merge fields
'html', // email-type preference
false // double-opt-in
);
// Action for successful subscribe attempt.
} catch (\Exception $e) {
if ($e instanceof \Mailchimp_List_AlreadySubscribed) {
// In case they are already subscribed:
$errors[] = $e->getMessage();
} else {
// In case something else went wrong.
$errors[] = 'There was an error adding your email to the list. Would you mind trying again?';
}
// Debug time!
var_dump($errors);
}

Wordpress invalidate cf7 after api call

Here's my issue, I have contact form 7 for wordpress installed and during the wpcf7_before_send_mail I make a call to an API, I need to invalidate the form if the API returns an error then I need to invalidate the request and return the error passed back from the API call.
I set a flag to false on API failure and the error message is also stored but my form is going through as success despite the failure I induce.
add_action("wpcf7_before_send_mail", "wpcf7_send_contact_builder");
function wpcf7_send_contact_builder($form) {
$submission = WPCF7_Submission::get_instance();
$wpcf7_data = $submission->get_posted_data();
... api call and set $success to true if ok and false if not ...
if (!$success) {
$form->status = 'validation_failed (statuscode:' . $xml->status->statuscode[0] . ').';
$form->valid = false;
$form->response = $xml->status->statusdesc[0];
return $forml
}
}
I've also tried using:
$form->invalidate('validation_failed (statuscode:' . $xml->status->statuscode[0] . ').', $xml->status->statusdesc[0]);
But whichever way I am unable to prevent the success email being sent and the form validates as successful. Debugging proved that the !success in the if statement is working and the code contained is added to the variable. I also tried as if form was an array ($form['valid'] = false) but this also didn't work and the form submits as successful. Any ideas of what I'm missing here? I've omitted the code for the API call itself and the determining of the correct form id, both of these work correctly, only the form I'm after is parsed and the API call is returning the expected data.
I needed the same. After going through the CF7 plugin files, I found the following solution:
//To make it working, we must need at least CF7-v5.0;
add_action( 'wpcf7_before_send_mail', 'cf7_validate_api', 15, 3 );
function cf7_validate_api($cf7, &$abort, $submission){
if ( $cf7->id() !== 789 ) //CF7 post-id from admin settings;
return;
$errMsg = '';
//$submission = WPCF7_Submission::get_instance();
$postedData = $submission->get_posted_data();
//$postedData['more-data'] = 'something';
unset($postedData['not-sending-data']);
//-----API posting------
$url = "http://my-web.com/wp-admin/admin-ajax.php?action=get-something";
$username = 'apiUserName';
$password = 'apiUserPass';
$args = [
'headers' => [
'Authorization' => "Basic ".base64_encode( $username . ':' . $password ),
'Accept' => 'application/json; charset=utf-8', // The API returns JSON
//'Content-Type' => 'application/json; charset=utf-8'
],
'body' => $postedData
];
$response = wp_remote_post( $url, $args );
//------------------
if( is_wp_error( $response ) ){
$error_message = $response->get_error_message();
$errMsg = "Something went wrong:\n{$error_message}";
} else {
$response_body = wp_remote_retrieve_body( $response );
$data = json_decode( $response_body );
if( empty($data) || $data->status==0 ){ //API validation error!
$errMsg = $data->msg->title."\n".$data->msg->description;
}
}
if( $errMsg ){ //do not send mail;
//$cf7->skip_mail = true; //for older versions!
$abort = true; //==> Here, it is with 'called by reference' since CF7-v5.0 :)
$submission->set_status( 'validation_failed' );
//$submission->set_response( $cf7->message( 'validation_error' ) ); //msg from admin settings;
$submission->set_response( $cf7->filter_message($errMsg) ); //custom msg;
}
}
Hopefully, it will help someone. Happy Coding :)

Why am I getting "Failed to request resource" when posting to a users wall on Facebook?

I'm using artdarek/oauth-4-laravel so the user can login via Facebook and post to their feed. I'm able to login in via Facebook using the following bit of code
// get data from input
$code = Input::get( 'code' );
// get fb service
$fb = OAuth::consumer( 'Facebook' );
// check if code is valid
// if code is provided get user data and sign in
if ( !empty( $code ) ) {
$token = $fb->requestAccessToken( $code );
$_SESSION['facebook_access_token'] = $token->getAccessToken();
// Send a request with it
$user = json_decode( $fb->request( '/me' ), true );
...
And everything works as expected. In the App I also have a share button, but when I try and share I get the following error
{"error":{"type":"OAuth\\Common\\Http\\Exception\\TokenResponseException","message":"Failed to request resource.","file":"\/var\/www\/html\/myApp\/vendor\/lusitanian\/oauth\/src\/OAuth\/Common\/Http\/Client\/StreamClient.php","line":68}}
Here is the code that I'm using for posting
if ( isset($_SESSION['facebook_access_token']) ) {
$fb = OAuth::consumer( 'Facebook' );
// $user = json_decode( $fb->request( "/me?access_token={$_SESSION['facebook_access_token']}" ), true );
$postMessage = json_decode( $fb->request
(
'POST',
"/me/feed?access_token={$_SESSION['facebook_access_token']}",
array (
'message' => 'This is a test message'
)
),
true );
return $postMessage;
}
I know that the $_SESSION[] is set because I ran the commented out line first and it was returning what I expected. But the code for posting on the wall is giving me that error mentioned earlier.
Please help.
Thanks
I found the mistake ... The call is supposed to be as follows
$postMessage = json_decode( $fb->request
(
"/me/feed?access_token={$_SESSION['facebook_access_token']}",
'POST',
array (
'message' => 'This is a test message'
)
),
true );
The route is supposed to be first and then the POST.

cannot get subscribers email to mailchimp2.0

this seems pretty straightforward but i just can't get mailchimp to get the emails. I have a checkbox and all I want to do is say, if check then subscribe.
I get an error 500 and I have no idea where to go with this.
<?php echo CHtml::CheckBox('[subscribe]',true, array ( 'value'=>'yes',)); ?>
if ( $_POST['subscribe'])
{
Yii::import('application.vendors.mailchimp');
$mailchimp = new Mailchimp(Yii::app()->params['mailchimp']['key']);
$listId = '*******';
$email = array(
'email' => trim($_POST['User']['email']));
$subscriber = $mailchimp->list->subscribe(
$listId,
$email,
$merge_vars=null,
false,
false
);
}

Categories