You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Gravity Forms的gform_after_submission钩子调用第三方API遇未授权问题

解决Gravity Forms gform_after_submission钩子调用第三方API的问题

问题根源

你的代码存在几个关键错误,导致API请求失败:

  1. 错误使用HTTP请求方法:用wp_remote_get发送POST请求,该函数仅用于GET请求,POST请求必须用wp_remote_post
  2. 请求体格式错误:API要求Content-Type: application/json,但你直接传递PHP数组作为body,WordPress会自动将其转为表单编码字符串(如prospectFirstName=xxx&source=Website),导致API解析JSON时出错
  3. 错误传递参数给HTTP函数:wp_remote_post的第二个参数需要是数组格式的配置,不能传JSON编码后的字符串

修正后的代码

add_action( 'gform_after_submission', 'post_to_third_party', 10, 2 );
function post_to_third_party( $entry, $form ) {
    $endpoint_url = '[Correct API Endpoint]';
    
    // 组装请求体数据
    $body = array(
        'prospectFirstName' => $entry['18'],
        // 'prospectLastName' => $entry['19'],
        // 'prospectEmail' => $entry['2'],
        // 'prospectPhone' => $entry['5'],
        // 'notes' => $entry['3'],
        'source' => 'Website',
        'communityId' => 32
    );
    
    $args = array(
        'headers' => array(
            'accept' => 'text/plain',
            'Authorization' => 'Basic ' . base64_encode( 'Correct-username:Correct-password' ),
            'Content-Type' => 'application/json'
        ),
        'method' => 'POST',
        // 单独对请求体进行JSON编码
        'body' => json_encode($body),
        // 配置请求超时等参数
        'timeout' => 15,
        'redirection' => 5,
        'blocking' => true
    );  
    
    GFCommon::log_debug( 'gform_after_submission: 请求参数 => ' . print_r( $args, true ) );
 
    // 使用wp_remote_post发送POST请求
    $response = wp_remote_post( $endpoint_url, $args );
    
    // 日志输出响应详情
    if ( is_wp_error( $response ) ) {
        GFCommon::log_debug( 'gform_after_submission: 请求错误 => ' . $response->get_error_message() );
    } else {
        GFCommon::log_debug( 'gform_after_submission: 响应状态码 => ' . wp_remote_retrieve_response_code( $response ) );
        GFCommon::log_debug( 'gform_after_submission: 响应内容 => ' . wp_remote_retrieve_body( $response ) );
    }
}

关键修改说明

  1. 替换请求函数:将wp_remote_get改为wp_remote_post,匹配API要求的POST方法
  2. 正确编码请求体:仅对$body数组执行json_encode,确保API收到标准JSON格式的数据
  3. 添加错误处理:通过is_wp_error判断请求是否失败,便于排查网络或API错误
  4. 优化日志输出:调整日志内容,优先输出状态码和响应体,更容易定位问题

验证方式

  • 提交表单后,查看Gravity Forms的调试日志(需在Gravity Forms设置中启用调试模式)
  • 检查响应状态码:200/201表示请求成功,4xx表示客户端错误(如参数缺失、权限问题),5xx表示服务器端错误

内容的提问来源于stack exchange,提问作者rsnyder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 14:40:13