这是我的问题,我安装了用于 wordpress 的联系表 7,在 wpcf7_before_send_mail 期间我调用了 API,如果 API 返回错误,我需要使表单无效,然后我需要使请求无效并返回错误从 API 调用返回。
我在 API 失败时将标志设置为 false,错误消息也被存储,但尽管我导致失败,但我的表单正在成功通过。
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
}
}
我也尝试过使用:
$form->invalidate('validation_failed (statuscode:' . $xml->status->statuscode[0] . ').', $xml->status->statusdesc[0]);
但无论哪种方式,我都无法阻止成功电子邮件的发送以及表单验证成功。调试证明 if 语句中的 !success 有效,包含的代码被添加到变量中。我也试过,就好像表单是一个数组($form['valid'] = false),但这也没有用,表单提交成功。对我在这里缺少的东西有什么想法吗?我省略了 API 调用本身的代码和正确表单 ID 的确定,这两者都正常工作,只有我之后的表单被解析并且 API 调用返回了预期的数据。
最佳答案
我也需要。在浏览了 CF7 插件文件后,我找到了以下解决方案:
//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;
}
}
希望它能对某人有所帮助。快乐编码:)
关于php - api调用后Wordpress使cf7无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36774134/