AtelliTech / postal-php

This library is forked by postalserver/postal-php, it helps you send e-mails through [Postal](https://github.com/atech/postal) in PHP 8.0 and above.
MIT License
0 stars 0 forks source link

Some wordpress issues #3

Open uhlhosting opened 1 year ago

uhlhosting commented 1 year ago

Trying to build a WordPress plugin with the library, I am getting some errors:

<?php

/**
 * Plugin Name: Postal Mail
 * Plugin URI: https://uhlhosting.ch/postal-mail
 * Description: A plugin to send emails through Postal Mail API
 * Version: 1.0.0
 * Author: Viorel-Cosmin Miron
 * Author URI: https://uhlhosting.ch
 * Text Domain: postal-mail
 */

namespace PostalWp;

use AtelliTech\Postal\Client;
use AtelliTech\Postal\SendMessage;
use AtelliTech\Postal\Exception\PostalException;

// Require the Postal API library
require_once 'vendor/autoload.php';
define('PostalWp\FILE', __FILE__);
// Check if the library is installed
if (!class_exists('AtelliTech\Postal\Client')) {
    // Show an error message in the admin panel if the library is not installed
    add_action('admin_notices', function () {
        echo '<div class="error"><p>The Postal API library is not installed. Please install it by running composer install in the plugin directory.</p></div>';
    });
    return;
}

// Create a new Postal client using the server key and URL from the options
$host = get_option('postal_wp_host');
$secretKey = get_option('postal_wp_secret_key');
$client = new Client($host, $secretKey);

/**
 * Send an email using the Postal API
 *
 * @param string|array $to Recipient email address(es)
 * @param string $subject Email subject
 * @param string $message Email message
 * @param string $headers Email headers
 * @param array $attachments Email attachments
 * @return bool Whether the email was sent successfully
 */
function postal_mail($to, $subject, $message, $headers = '', $attachments = [])
{
    global $client;

    // Check if email sending is enabled or disabled
    $postal_wp_switch = get_option('postal_wp_switch');
    if (!$postal_wp_switch) {
        // If it's disabled, use the default WordPress email function
        return wp_mail($to, $subject, $message, $headers, $attachments);
    }

    // Create the email parameters
    $params = ['subject' => $subject, 'to' => is_array($to) ? $to : [$to], 'from' => get_option('postal_wp_from_address'), 'html_body' => $message,];

    // Check if there are any headers and add them to the parameters
    if (!empty($headers)) {
        $headers = explode("\n", $headers);
        foreach ($headers as $header) {
            if (strpos($header, ':') !== false) {
                list($key, $value) = explode(':', $header);
                $key = trim($key);
                $value = trim($value);
                switch ($key) {
                    case 'From':
                        $params['from'] = $value;
                        break;
                    case 'Reply-To':
                        $params['reply_to'] = $value;
                        break;
                    case 'CC':
                        $params['cc'] = explode(',', $value);
                        break;
                    case 'BCC':
                        $params['bcc'] = explode(',', $value);
                        break;
                }
            }
        }
    }

    // Check if there are any attachments and add them to the parameters
    if (!empty($attachments)) {
        $params['attachments'] = [];
        foreach ($attachments as $attachment) {
            if (file_exists($attachment)) {
                $params['attachments'][] = ['name' => basename($attachment), 'data' => base64_encode(file_get_contents($attachment)),];
            }
        }
    }

    try {
        // Send the email using the Postal API

        $sendMessage = new SendMessage($params);
        $result = $client->sendMessage($sendMessage);
        //$result = $message->send($client);
        return true;
    } catch (PostalException $e) {
        // If there was an error, log it and return false
        error_log($e->getMessage());
        return false;
    }
}

// Override the default WordPress email function
add_filter('wp_mail', function ($args) {
    return postal_mail($args['to'], $args['subject'], $args['message'], $args['headers'], $args['attachments']);
});

// Add a setting page for the plugin in the WordPress admin panel

// Register the plugin options in the WordPress database
add_action('admin_init', function () {
    register_setting('postal_mail', 'postal_wp_host');
    register_setting('postal_mail', 'postal_wp_secret_key');
    register_setting('postal_mail', 'postal_wp_from_address');
    register_setting('postal_mail', 'postal_wp_switch');
});

// Load the plugin text domain for translation
add_action('plugins_loaded', function () {
    load_plugin_textdomain('postal-mail', false, dirname(plugin_basename(FILE)) . '/languages/');
});

// Add a plugin action link to the plugin page
add_filter('plugin_action_links_' . plugin_basename(FILE), function ($links) {
    $links[] = '<a href="' . admin_url('options-general.php?page=postal_mail') . '">' . __('Settings', 'postal-mail') . '</a>';
    return $links;
});

// Add a setting page for the plugin in the WordPress admin panel
add_action('admin_menu', function () {
    if (!current_user_can('manage_options')) {
        return;
    }
    add_options_page(__('Postal Mail', 'postal-mail'), __('Postal Mail', 'postal-mail'), 'manage_options', 'postal_mail', function () {
?>
        <div class="wrap">
            <h1><?php _e('Postal Mail', 'postal-mail'); ?></h1>
            <form method="post" action="options.php">
                <?php settings_fields('postal_mail'); ?>
                <table class="form-table">
                    <tr>
                        <th scope="row"><label for="postal_wp_host"><?php _e('Postal Host', 'postal-mail'); ?></label></th>
                        <td><input type="text" id="postal_wp_host" name="postal_wp_host" value="<?php echo esc_attr(get_option('postal_wp_host')); ?>" class="regular-text" /></td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="postal_wp_secret_key"><?php _e('Postal Secret Key', 'postal-mail'); ?></label></th>
                        <td><input type="text" id="postal_wp_secret_key" name="postal_wp_secret_key" value="<?php echo esc_attr(get_option('postal_wp_secret_key')); ?>" class="regular-text" /></td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="postal_wp_from_address"><?php _e('From Address', 'postal-mail'); ?></label></th>
                        <td><input type="text" id="postal_wp_from_address" name="postal_wp_from_address" value="<?php echo esc_attr(get_option('postal_wp_from_address')); ?>" class="regular-text" /></td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="postal_wp_switch"><?php _e('Enable Email Sending', 'postal-mail'); ?></label></th>
                        <td><input type="checkbox" id="postal_wp_switch" name="postal_wp_switch" value="1" <?php checked(get_option('postal_wp_switch'), 1); ?> /></td>
                    </tr>
                </table>
                <?php submit_button(); ?>
            </form>
        </div>
<?php
    });
});

This is the code I use, and this is what I receive from wordpress:

[01-Feb-2023 23:36:03 UTC] PHP Fatal error:  Uncaught Error: Call to undefined method AtelliTech\Postal\Client::sendMessage() in /var/www/html/wp-content/plugins/postal/postal.php:100
Stack trace:
#0 /var/www/html/wp-content/plugins/postal/postal.php(112): PostalWp\postal_mail('cosmin@uhlhost....', '[A Random Blog ...', '<!DOCTYPE html>...', Array, Array)
#1 /var/www/html/wp-includes/class-wp-hook.php(308): PostalWp\{closure}(Array)
#2 /var/www/html/wp-includes/plugin.php(205): WP_Hook->apply_filters(Array, Array)
#3 /var/www/html/wp-includes/pluggable.php(192): apply_filters('wp_mail', Array)
#4 /var/www/html/wp-content/plugins/woocommerce/includes/emails/class-wc-email.php(688): wp_mail('cosmin@uhlhost....', '[A Random Blog ...', '<!DOCTYPE html>...', 'Content-Type: t...', Array)
#5 /var/www/html/wp-content/plugins/woocommerce/includes/emails/class-wc-email-new-order.php(111): WC_Email->send('cosmin@uhlhost....', '[A Random Blog ...', '<!DOCTYPE html>...', 'Content-Type: t...', Array)
#6 /var/www/html/wp-includes/class-wp-hook.php(308): WC_Email_New_Order->trigger(442, Object(Automattic\WooCommerce\Admin\Overrides\Order))
#7 /var/www/html/wp-includes/class-wp-hook.php(332): WP_Hook->apply_filters('', Array)
#8 /var/www/html/wp-includes/plugin.php(565): WP_Hook->do_action(Array)
#9 /var/www/html/wp-content/plugins/woocommerce/includes/class-wc-emails.php(170): do_action_ref_array('woocommerce_ord...', Array)
#10 /var/www/html/wp-includes/class-wp-hook.php(308): WC_Emails::send_transactional_email(Array, Object(Automattic\WooCommerce\Admin\Overrides\Order))
#11 /var/www/html/wp-includes/class-wp-hook.php(332): WP_Hook->apply_filters('', Array)
#12 /var/www/html/wp-includes/plugin.php(517): WP_Hook->do_action(Array)
#13 /var/www/html/wp-content/plugins/woocommerce/includes/class-wc-order.php(396): do_action('woocommerce_ord...', 442, Object(Automattic\WooCommerce\Admin\Overrides\Order))
#14 /var/www/html/wp-content/plugins/woocommerce/includes/class-wc-order.php(245): WC_Order->status_transition()
#15 /var/www/html/wp-content/plugins/woocommerce/includes/class-wc-order.php(357): WC_Order->save()
#16 /var/www/html/wp-content/plugins/woocommerce/includes/gateways/cheque/class-wc-gateway-cheque.php(122): WC_Order->update_status('on-hold', 'Awaiting check ...')
#17 /var/www/html/wp-content/plugins/woocommerce/includes/class-wc-checkout.php(1050): WC_Gateway_Cheque->process_payment(442)
#18 /var/www/html/wp-content/plugins/woocommerce/includes/class-wc-checkout.php(1279): WC_Checkout->process_order_payment(442, 'cheque')
#19 /var/www/html/wp-content/plugins/woocommerce/includes/class-wc-ajax.php(481): WC_Checkout->process_checkout()
#20 /var/www/html/wp-includes/class-wp-hook.php(308): WC_AJAX::checkout('')
#21 /var/www/html/wp-includes/class-wp-hook.php(332): WP_Hook->apply_filters('', Array)
#22 /var/www/html/wp-includes/plugin.php(517): WP_Hook->do_action(Array)
#23 /var/www/html/wp-content/plugins/woocommerce/includes/class-wc-ajax.php(94): do_action('wc_ajax_checkou...')
#24 /var/www/html/wp-includes/class-wp-hook.php(308): WC_AJAX::do_wc_ajax('')
#25 /var/www/html/wp-includes/class-wp-hook.php(332): WP_Hook->apply_filters(false, Array)
#26 /var/www/html/wp-includes/plugin.php(517): WP_Hook->do_action(Array)
#27 /var/www/html/wp-includes/template-loader.php(13): do_action('template_redire...')
#28 /var/www/html/wp-blog-header.php(19): require_once('/var/www/html/w...')
#29 /var/www/html/index.php(17): require('/var/www/html/w...')
#30 {main}
  thrown in /var/www/html/wp-content/plugins/postal/postal.php on line 100

any idea why it says call to undefined method?

iamgold commented 1 year ago

According to your description, you need to use $message->send($client); instead of $client->sendMessage($message); on /var/www/html/wp-includes/class-wp-hook.php(line: 308)