Как эффективно отправить список электронных писем участников WooCommerce на внешнюю конечную точку API?Php

Кемеровские программисты php общаются здесь
Ответить
Anonymous
 Как эффективно отправить список электронных писем участников WooCommerce на внешнюю конечную точку API?

Сообщение Anonymous »

Я использую подписки WooCommerce. Недавно я экспериментировал, пытаясь отправить своих активных, ожидающих отмены и дополнительных участников WooCommerce на внешнюю конечную точку API с одним из наших партнеров, но, к сожалению, код, который я использую в фрагменте кода WordPress, похоже, не работает и не работает. Я не выдаю никаких ошибок, поэтому в журналах нет ничего для отладки, несмотря на то, что у меня включены параметры для отладки.
Также важно отметить, что я протестировал API конечная точка и аутентификация напрямую с помощью Postmaster, и он отправляет данные абсолютно нормально, поэтому это должно быть связано с недостатком моего кода или с тем, как настроен мой WordPress/WooCommerce.
Вот связанный код (URL конечной точки и токен аутентификации удалены в целях конфиденциальности):
// Hook into the WooCommerce Memberships event when a user membership is updated or created.
add_action('wc_memberships_user_membership_saved', 'send_membership_email_to_external', 10, 1);

// Function to handle real-time sync when membership is saved
function send_membership_email_to_external($user_membership) {
// Ensure the passed object is of the correct type
if (!($user_membership instanceof WC_Memberships_User_Membership)) {
error_log('Unexpected object type in send_membership_email_to_external');
return;
}
// Get user details
$user_id = $user_membership->get_user_id();
$user_info = get_userdata($user_id);
$user_email = $user_info->user_email;

// Get the membership status
$membership_status = $user_membership->get_status();

// Check if the membership is 'wc-active', 'wc-pending-cancel', or 'wc-complementary'
if (in_array($membership_status, array('wc-active', 'wc-pending-cancel', 'wc-complementary'))) {
// Proceed to sync the email to the API
sync_emails_to_api(array($user_email));
}
}

// Function to sync emails to the API
function sync_emails_to_api($email_array) {
// Set the API endpoint and auth token
$api_url = 'exampleurl.php';
$auth_token = 'exampleauthtoken'; // Your provided auth token

// Prepare the data to send
$api_body = array(
'action' => 'departmentEmails', // As specified by the API docs
'arrayEmails' => $email_array, // Emails to sync
);

// Set up the request arguments
$args = array(
'method' => 'POST',
'headers' => array(
'Authorization' => $auth_token,
'Content-Type' => 'application/json',
),
'body' => json_encode($api_body),
'timeout' => 45,
);

// Send the request using wp_remote_post()
$response = wp_remote_post($api_url, $args);

// Check for errors
if (is_wp_error($response)) {
// Log the error for debugging purposes
error_log('API Sync Error: ' . $response->get_error_message());
} else {
// Optionally, handle the API response
$api_response = json_decode(wp_remote_retrieve_body($response), true);
if (isset($api_response['success']) && $api_response['success']) {
// Successful sync (you can log this if needed)
error_log('API Sync Success');
} else {
// Handle an unsuccessful response from the API
error_log('API Sync Failed: ' . wp_remote_retrieve_body($response));
}
}
}


Подробнее здесь: https://stackoverflow.com/questions/791 ... rnal-api-e
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Php»