草庐IT

php - api调用后Wordpress使cf7无效

coder 2024-04-18 原文

这是我的问题,我安装了用于 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/

有关php - api调用后Wordpress使cf7无效的更多相关文章

  1. 使用 ACL 调用 upload_file 时出现 Ruby S3 "Access Denied"错误 - 2

    我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file

  2. ruby-on-rails - ActionController::RoutingError: 未初始化常量 Api::V1::ApiController - 2

    我有用于控制用户任务的Rails5API项目,我有以下错误,但并非总是针对相同的Controller和路由。ActionController::RoutingError:uninitializedconstantApi::V1::ApiController我向您描述了一些我的项目,以更详细地解释错误。应用结构路线scopemodule:'api'donamespace:v1do#=>Loginroutesscopemodule:'login'domatch'login',to:'sessions#login',as:'login',via::postend#=>Teamroutessc

  3. ruby-on-rails - Rails 5 Active Record 记录无效错误 - 2

    我有两个Rails模型,即Invoice和Invoice_details。一个Invoice_details属于Invoice,一个Invoice有多个Invoice_details。我无法使用accepts_nested_attributes_forinInvoice通过Invoice模型保存Invoice_details。我收到以下错误:(0.2ms)BEGIN(0.2ms)ROLLBACKCompleted422UnprocessableEntityin25ms(ActiveRecord:4.0ms)ActiveRecord::RecordInvalid(Validationfa

  4. c# - 如何在 ruby​​ 中调用 C# dll? - 2

    如何在ruby​​中调用C#dll? 最佳答案 我能想到几种可能性:为您的DLL编写(或找人编写)一个COM包装器,如果它还没有,则使用Ruby的WIN32OLE库来调用它;看看RubyCLR,其中一位作者是JohnLam,他继续在Microsoft从事IronRuby方面的工作。(估计不会再维护了,可能不支持.Net2.0以上的版本);正如其他地方已经提到的,看看使用IronRuby,如果这是您的技术选择。有一个主题是here.请注意,最后一篇文章实际上来自JohnLam(看起来像是2009年3月),他似乎很自在地断言RubyCL

  5. java - 从 JRuby 调用 Java 类的问题 - 2

    我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www

  6. ruby - 调用其他方法的 TDD 方法的正确方法 - 2

    我需要一些关于TDD概念的帮助。假设我有以下代码defexecute(command)casecommandwhen"c"create_new_characterwhen"i"display_inventoryendenddefcreate_new_character#dostufftocreatenewcharacterenddefdisplay_inventory#dostufftodisplayinventoryend现在我不确定要为什么编写单元测试。如果我为execute方法编写单元测试,那不是几乎涵盖了我对create_new_character和display_invent

  7. 【鸿蒙应用开发系列】- 获取系统设备信息以及版本API兼容调用方式 - 2

    在应用开发中,有时候我们需要获取系统的设备信息,用于数据上报和行为分析。那在鸿蒙系统中,我们应该怎么去获取设备的系统信息呢,比如说获取手机的系统版本号、手机的制造商、手机型号等数据。1、获取方式这里分为两种情况,一种是设备信息的获取,一种是系统信息的获取。1.1、获取设备信息获取设备信息,鸿蒙的SDK包为我们提供了DeviceInfo类,通过该类的一些静态方法,可以获取设备信息,DeviceInfo类的包路径为:ohos.system.DeviceInfo.具体的方法如下:ModifierandTypeMethodDescriptionstatic StringgetAbiList​()Obt

  8. ruby-on-rails - Mandrill API 模板 - 2

    我正在使用Mandrill的RubyAPIGem并使用以下简单的测试模板:testastic按照Heroku指南中的示例,我有以下Ruby代码:require'mandrill'm=Mandrill::API.newrendered=m.templates.render'test-template',[{:header=>'someheadertext',:main_section=>'Themaincontentblock',:footer=>'asdf'}]mail(:to=>"JaysonLane",:subject=>"TestEmail")do|format|format.h

  9. C51单片机——实现用独立按键控制LED亮灭(调用函数篇) - 2

    说在前面这部分我本来是合为一篇来写的,因为目的是一样的,都是通过独立按键来控制LED闪灭本质上是起到开关的作用,即调用函数和中断函数。但是写一篇太累了,我还是决定分为两篇写,这篇是调用函数篇。在本篇中你主要看到这些东西!!!1.调用函数的方法(主要讲语法和格式)2.独立按键如何控制LED亮灭3.程序中的一些细节(软件消抖等)1.调用函数的方法思路还是比较清晰地,就是通过按下按键来控制LED闪灭,即每按下一次,LED取反一次。重要的是,把按键与LED联系在一起。我打算用K1来作为开关,看了一下开发板原理图,K1连接的是单片机的P31口,当按下K1时,P31是与GND相连的,也就是说,当我按下去时

  10. ruby-on-rails - 在 Ruby (on Rails) 中使用 imgur API 获取图像 - 2

    我正在尝试使用Ruby2.0.0和Rails4.0.0提供的API从imgur中提取图像。我已尝试按照Ruby2.0.0文档中列出的各种方式构建http请求,但均无济于事。代码如下:require'net/http'require'net/https'defimgurheaders={"Authorization"=>"Client-ID"+my_client_id}path="/3/gallery/image/#{img_id}.json"uri=URI("https://api.imgur.com"+path)request,data=Net::HTTP::Get.new(path

随机推荐