I'm trying to connect my contact 7 form to post also to an external CRM by using wp_remote_post. I found a tutorial and came up with this code:
function on_submit( $form, &$abort, $submission ) {
if ( $abort === TRUE ) {
return;
}
//tried seeing what my datafile was but nothing is being posted to my errorlog
$data = $submission->get_posted_data();
ob_start();
var_dump($posted_data);
error_log(ob_get_clean());
$email = sanitize_text_field($data['your-email']);
$name = sanitize_text_field($data['your-name']);
$phone = sanitize_text_field($data['your-phone']);
$message = sanitize_textarea_field($data['your-message']);
$apiurl = 'https://coolapi.com';
$apiheaders = array(
'Authorization' => 'Token token=NotMyRealToken'
);
$apibody = array( 'marketing_form' => array (
'email' => $email,
'first_name' => $name,
'phone_number' => $phone,
'notes' => $message,
'relationship' => 'self',
'community_id' => 19019,
'lead_source_id' => 60725
));
$args_for_push = array (
'headers' => $apiheaders,
'body' => json_encode($apibody)
);
$response = wp_safe_remote_post( $apiurl, $args_for_push );
$response_code = wp_remote_retrieve_response_code($response);
if ( is_wp_error($response) ) {
$abort = TRUE;
//$body = wp_remote_retrieve_body($response);
//$result = json_decode($body);
$submission->set_response($response->get_error_message() );
$submission->set_status('api_failed');
}
if($response_code != 200) {
$submission->set_status('api_failed'.$response_code);
$submission->set_response('Something went wrong: '.$response_code);
} else {
$submission->set_status('api_success'.$response_code);
$submission->set_response('Thank you! we will get back to you shortly. confirm: '.$response_code);
}
//tried getting my debug info because nothing is reported to my error log. (this did not work)
$debug="1";
$mail = $form->prop( 'mail' );
$new_mail = str_replace( '[your-name]', $debug, $mail );
$form->set_properties( array( 'mail' => $new_mail ) );
return $form;
}
add_action('wpcf7_before_send_mail', 'on_submit', 10, 3);
When I run this code without Cf7 the API returns a success code. But here no matter what I do CF7 submits the form and I receive an email but I'm not getting a submission to the CRM nor any errors. the message at the bottom of the form says: Thank you for your message. It has been sent.
and no class changes are made to the form.
How can I better dump the log (or response) or have my submissions errors show up on the front so I can see what is wrong? Or better yet, get this thing working!
source https://stackoverflow.com/questions/77091293/connect-contact-form-7-cf7-to-an-external-api
No comments:
Post a Comment