Wordpress:在没有插件的情况下集成 Mailchimp 错误请求 400 Ajax URL

Posted

技术标签:

【中文标题】Wordpress:在没有插件的情况下集成 Mailchimp 错误请求 400 Ajax URL【英文标题】:Wordpress: Integration Mailchimp Without Plugin Bad Request 400 Ajax URL 【发布时间】:2021-07-24 03:44:20 【问题描述】:

我正在尝试在不使用插件的情况下通过 ajax 请求与 mailchimp 集成,但我有错误 400 错误请求。下面的代码是用 vanilla JS 编写的 Ajax 和与 mailchimp 集成的功能。 注意:我不想在 ajax 中使用 jquery,这就是我使用 vanilla javascript 的原因

错误在控制台上显示为:POST http://local.com/wp-admin/admin-ajax.php 400 (Bad Request)

Ajax 原版 JS

// Objeto com todos os campos e propriedades dentro do formulário
const form = 
    email: document.getElementById('email'),
    submit: document.getElementById('btn-submit-newsletter-idinheiro'),
    messages: document.getElementById('newsletter-idinheiro-messages'),


// Evento do submit do formulário
form.submit.addEventListener('click', (event) => 
    event.preventDefault();

    // Instanciando Requisição AJAX
    const request = new XMLHttpRequest();

    request.onload = () => 
        let responseObject = null;

        try 
            responseObject = JSON.parse(request.responseText);
         catch (e) 
            console.error('Could not parse JSON');
        

        if (responseObject) 
            handleResponse(responseObject);
        
    ;

    // Obter valores do formulário digitado pelo usuário
    const requestData = `email=$form.email.value`;

    request.open('POST', object_name.ajax_url); // O object_name é uma variável importada pela função wp_localize_script como array dentro de functions.php
    request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    request.send(requestData);
    
    // Função de retorno das mensagens obtidos dos campos validados pelo PHP a serem inseridas no front
    const handleResponse = (responseObject) => 

        // Limpa elemento atualizando com o novo valor
        while (form.messages.firstChild) 
            form.messages.removeChild(form.messages.firstChild);
        

        // Função de resposta das mensagens
        const responseMessages = () => 
            responseObject.messages.forEach((message) => 
                const element = document.createElement('span');
                element.textContent = message;
                form.messages.appendChild(element);
            );
            
            form.messages.style.display = 'block';
        
        
        // Condicional mensagens
        if (responseObject.ok) 
            responseMessages();
            form.messages.classList.add('newsletter__messages--success');
            form.messages.classList.remove('newsletter__messages--error');

         else 
            responseMessages();
            form.messages.classList.add('newsletter__messages--error');
            form.messages.classList.remove('newsletter__messages--success');
        
    
);

Functions.php - 入队脚本

function idinheiro_scripts() 
    // JS
    wp_enqueue_script( 'all-js', get_template_directory_uri() . '/assets/js/all.min.js', NULL, '', true );
    
    // Localize SCRIPT
    wp_localize_script('all-js', 'object_name', array(
        'ajax_url' => admin_url( 'admin-ajax.php' ),
    ));


Functions.php - 集成 Mailchimp

add_action('wp_ajax_subscribe_user', 'subscribe_user_to_mailchimp');
add_action('wp_ajax_nopriv_subscribe_user', 'subscribe_user_to_mailchimp');
 
function subscribe_user_to_mailchimp() 
    check_ajax_referer('subscribe_user', 'security');
    $email = $_POST['email'];
    $audience_id = getenv('MAIN_LIST_ID_MAILCHIMP');
    $api_key = getenv('API_KEY_MAILCHIMP');
    $data_center = substr($api_key,strpos($api_key,'-')+1);
    $url = 'https://'. $data_center .'.api.mailchimp.com/3.0/lists/'. $audience_id .'/members';
    $auth = base64_encode( 'user:' . $api_key );
    $arr_data = json_encode(array(
        'email_address' => $email,
        'status' => 'subscribed' //pass 'subscribed' or 'pending'
    ));
 
    $response = wp_remote_post( $url, array(
            'method' => 'POST',
            'headers' => array(
                'Content-Type' => 'application/json',
                'Authorization' => "Basic $auth"
            ),
            'body' => $arr_data,
        )
    );
 
    if ( is_wp_error( $response ) ) 
       $error_message = $response->get_error_message();
       echo "Something went wrong: $error_message";
     else 
        $status_code = wp_remote_retrieve_response_code( $response );
        switch ($status_code) 
            case '200':
                echo $status_code;
                break;
            case '400':
                $api_response = json_decode( wp_remote_retrieve_body( $response ), true );
                echo $api_response['title'];
                break;
            default:
                echo 'Something went wrong. Please try again.';
                break;
        
    
    wp_die();


【问题讨论】:

【参考方案1】:

您需要通过action 调用WordPress ajax 在您的情况下操作应该是subscribe_user

const requestData = `action=subscribe_user&email=$form.email.value`;

request.open('POST', object_name.ajax_url); // O object_name é uma variável importada pela função wp_localize_script como array dentro de functions.php
request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
request.send(requestData);

【讨论】:

你能分享一张显示requestData如何传递给ajax的ajax调用截图吗? 首先,你得到的是403 forbidden,而不是你在cmets中所说的404 forbidden!。你能和我分享一下网络选项卡的屏幕截图,而不是带有 requestData 的控制台正在传递给 ajax。 我刚刚在本地测试过,效果很好。 按照你原来的问题,我回答了。你应该通过搜索更多检查wordpress ajax 403 forbidden @RenanBessa 欢迎...很高兴能提供帮助。如果你喜欢/想要你也可以upvote回答,谢谢。

以上是关于Wordpress:在没有插件的情况下集成 Mailchimp 错误请求 400 Ajax URL的主要内容,如果未能解决你的问题,请参考以下文章

如何在没有 xib 文件的情况下集成 iAD

在没有插件的情况下在 WordPress 中集成 Bootstrap 轮播

Microsoft Cognitive Services Face API - 如何在没有可可豆荚的情况下集成 iOS 框架?

如何在没有YoutubeBaseActivity的情况下集成Youtube视频集成Android的

eclipse开发环境下集成activiti插件

是否可以在不使用 iOS SDK 的情况下集成 Facebook 登录?