WordPress/WooCommerce: Save custom payment post meta - php

I am using a plugin that is creating a custom payment type where the user can fill in a custom payment ID. The thing is, I want that custom payment ID stored in an ACF field as post meta on the WooCommerce order edit page. I have created an ACF field named 'kkpayment' for this task. I figured the rest should be done using update_field($selector, $value, [$post_id]);. I have created a PHP function for this task. However, my code doesn't seem to work. Am I missing something obvious?
My function for updating the ACF field:
add_action( 'woocommerce_checkout_update_order_meta', 'custom_payment_update_order_meta_acf' );
function custom_payment_update_order_meta_acf( $order_id ) {
$transaction = get_post_meta( $order->id, 'transaction', true );
if($_POST['payment_method'] = 'custom')
return $transaction;
update_field('kkpayment', $transaction, $order_id);
}
The custom payment is made with this code:
<?php
/*
Plugin Name: KK Payment Gateway
Description: Modtag betaling med kontostreng
Author: Arvin Aliari & Tobias Hyrup
Author URI: https://aliari.dk
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}
/**
* Baseret på StackOverlow: https://stackoverflow.com/questions/17081483/custom-payment-method-in-woocommerce
*
* Tilpasninger til dette projekt, se linje 135 - 161
*
*
*
* Custom Payment Gateway.
*
* Provides a Custom Payment Gateway.
*/
add_action('plugins_loaded', 'init_custom_gateway_class');
function init_custom_gateway_class(){
class WC_Gateway_Custom extends WC_Payment_Gateway {
public $domain;
/**
* Constructor for the gateway.e Number
*/
public function __construct() {
$this->domain = 'custom_payment';
$this->id = 'custom';
$this->icon = apply_filters('woocommerce_custom_gateway_icon', '');
$this->has_fields = false;
$this->method_title = __( 'Prisme', $this->domain );
$this->method_description = __( 'Tag i mod betaling fra Prisme.', $this->domain );
// Load the settings.
$this->init_form_fields();
$this->init_settings();
// Define user set variables
$this->title = $this->get_option( 'title' );
$this->description = $this->get_option( 'description' );
$this->instructions = $this->get_option( 'instructions', $this->description );
$this->order_status = $this->get_option( 'order_status', 'completed' );
// Actions
add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) );
add_action( 'woocommerce_thankyou_' . $this->id, array( $this, 'thankyou_page' ) );
// Customer Emails
add_action( 'woocommerce_email_before_order_table', array( $this, 'email_instructions' ), 10, 3 );
}
/**
* Initialise Gateway Settings Form Fields.
*/
public function init_form_fields() {
$this->form_fields = array(
'enabled' => array(
'title' => __( 'Aktiver/Deaktiver', $this->domain ),
'type' => 'checkbox',
'label' => __( 'Tillad betaling med kontostreng', $this->domain ),
'default' => 'yes'
),
'title' => array(
'title' => __( 'Titel', $this->domain ),
'type' => 'text',
'description' => __( 'Angiver den titel som brugeren ser under checkout.', $this->domain ),
'default' => __( 'Betaling med kontostreng', $this->domain ),
'desc_tip' => true,
),
'order_status' => array(
'title' => __( 'Ordrestatus', $this->domain ),
'type' => 'select',
'class' => 'wc-enhanced-select',
'description' => __( 'Vælg hvilken status du ønsker efter chekout.', $this->domain ),
'default' => 'wc-completed',
'desc_tip' => true,
'options' => wc_get_order_statuses()
),
'description' => array(
'title' => __( 'Beskrivelse', $this->domain ),
'type' => 'textarea',
'description' => __( 'Beskrivelse af betalingsmetoden som brugerene ser under chekout.', $this->domain ),
'default' => __('Payment Information', $this->domain),
'desc_tip' => true,
),
'instructions' => array(
'title' => __( 'Instruktioner', $this->domain ),
'type' => 'textarea',
'description' => __( 'Besked som brugerene vil se på efter gennemført ordre.', $this->domain ),
'default' => '',
'desc_tip' => true,
),
);
}
/**
* Output for the order received page.
*/
public function thankyou_page() {
if ( $this->instructions )
echo wpautop( wptexturize( $this->instructions ) );
}
/**
* Add content to the WC emails.
*
* #access public
* #param WC_Order $order
* #param bool $sent_to_admin
* #param bool $plain_text
*/
public function email_instructions( $order, $sent_to_admin, $plain_text = false ) {
if ( $this->instructions && ! $sent_to_admin && 'custom' === $order->payment_method && $order->has_status( 'on-hold' ) ) {
echo wpautop( wptexturize( $this->instructions ) ) . PHP_EOL;
}
}
public function payment_fields(){
if ( $description = $this->get_description() ) {
echo wpautop( wptexturize( $description ) );
}
?>
<div id="custom_input">
<p class="form-row form-row-wide">
<label for="transaction" class=""><?php _e('26-cifret kontostreng:', $this->domain); ?></label>
<input type="text" class="" name="transaction" id="transaction" placeholder="12345-1234-123-123456789-123-12" value="" style="width: 225px;">
</p>
<p style="opacity: 0.75; margin-top:-10px; font-size: 13.5px;">Eks: 12345-1234-123-123456789-123-12</p>
<p>Hvis du ikke har en kontostreng, så kontakt din nærmeste leder eller økonomimedarbejder.</p>
</div>
<?php
}
public function validate_fields(){
$paymentString = $_POST['transaction'];
$strLength = strlen($paymentString);
/*$stringContains = preg_match("/^\d{5}[-]\d{4}[-]\d{3}[-]\d{7}[-]\d{3}[-]\d{2}$/", $paymentString);*/
$stringContains = preg_match("/^\d{5}[-]\d{4}[-]\d{3}[-]\d{9}[-]\d{3}[-]\d{2}$/", $paymentString);
if($stringContains && !empty($_POST['transaction']) && $_POST['transaction'] != "") {
return true;
} else {
$stringOldPattern = preg_match("/^\d{5}[-]\d{4}[-]\d{3}[-]\d{7}[-]\d{3}[-]\d{2}$/", $paymentString);
if($stringOldPattern){
wc_add_notice( "Ugyldig kontostreng - Husk at bruge det nye format på 26 cifre der inkluderer funktionskode. Tjek at du har indtastet kontostrengen korrekt. Eksempel: 12345-1234-123-123456789-123-12", 'error' );
} else {
wc_add_notice( "Ugyldig kontostreng - Tjek at du har indtastet kontostrengen korrekt. Eksempel: 12345-1234-123-123456789-123-12", 'error' );
}
return false;
}
}
/**
* Process the payment and return the result.
*
* #param int $order_id
* #return array
*/
public function process_payment( $order_id ) {
$order = wc_get_order( $order_id );
$status = 'wc-' === substr( $this->order_status, 0, 3 ) ? substr( $this->order_status, 3 ) : $this->order_status;
// Set order status
$order->update_status( $status, __( 'Checkout with custom payment. ', $this->domain ) );
// Reduce stock levels
$order->reduce_order_stock();
// Remove cart
WC()->cart->empty_cart();
// Return thankyou redirect
return array(
'result' => 'success',
'redirect' => $this->get_return_url( $order )
);
}
}
}
add_filter( 'woocommerce_payment_gateways', 'add_custom_gateway_class' );
function add_custom_gateway_class( $methods ) {
$methods[] = 'WC_Gateway_Custom';
return $methods;
}
add_action('woocommerce_checkout_process', 'process_custom_payment');
function process_custom_payment(){
if($_POST['payment_method'] != 'custom')
return;
if( !isset($_POST['transaction']) || empty($_POST['transaction']) )
//wc_add_notice( __( 'Angiv venligst dit 26-cifret kontostreng til Prisme', $this->domain ), 'error' );
wc_add_notice( __( 'Angiv venligst dit 26-cifret kontostreng til Prisme', ), 'error' );
}
/**
* Update the order meta with field value
*/
add_action( 'woocommerce_checkout_update_order_meta', 'custom_payment_update_order_meta' );
function custom_payment_update_order_meta( $order_id ) {
if($_POST['payment_method'] != 'custom')
return;
// echo "<pre>";
// print_r($_POST);
// echo "</pre>";
// exit();
update_post_meta( $order_id, 'transaction', $_POST['transaction'] );
}
/**
* Display field value on the order edit page
*/
add_action( 'woocommerce_admin_order_data_after_billing_address', 'custom_checkout_field_display_admin_order_meta', 10, 1 );
function custom_checkout_field_display_admin_order_meta($order){
$method = get_post_meta( $order->id, '_payment_method', true );
if($method != 'custom')
return;
$transaction = get_post_meta( $order->id, 'transaction', true );
echo '<p><strong>'.__( '26 cifret kontostreng').':</strong> ' . $transaction . '</p>';
}
/**
* Add payment to metadata
*/
add_action( 'woocommerce_checkout_update_order_meta', 'custom_payment_update_order_meta_acf' );
function custom_payment_update_order_meta_acf( $order_id ) {
$transaction = get_post_meta( $order->id, 'transaction', true );
if($_POST['payment_method'] = 'custom')
return $transaction;
update_field('kkpayment', $transaction, $order_id);
}

Use this code to update acf field on successful transaction.
add_action( 'woocommerce_thankyou', 'bks_post_transaction_after_order_completion', 10, 1 );
function bks_post_transaction_after_order_completion( $order_id ) {
$order = wc_get_order( $order_id ); // phpcs:ignore.
$status = $order->get_status();
// Try to post only when order status is completed or processing.
if ( ! ( 'completed' === $status || 'processing' === $status ) ) {
return;
}
// get transaction.
$transaction = get_post_meta( $order->id, 'transaction', true );
update_field('kkpayment', $transaction, $order_id);
$order->update_meta_data( 'kkpayment', $transaction ); // phpcs:ignore
$order->save();
}

Related

Woocommerce function to display this custom field value on the order edit page

we add option to add VAT number to checkout page, it shows ok on checkout page, in admin and in emails, but it don't save to custom fields.
Here is code:
/**
* VAT Number in WooCommerce Checkout
*/
function wpdesk_vat_field( $checkout ) {
echo '<div id="wpdesk_vat_field"><h2>' . __('Nakup na podjetje') . '</h2>';
woocommerce_form_field( 'vat_number', array(
'type' => 'text',
'class' => array( 'vat-number-field form-row-wide') ,
'label' => __( 'V kolikor nakupujete kot podjetje, vnesite ID za DDV' ),
'placeholder' => __( 'Vnesite ID za DDV' ),
), $checkout->get_value( 'vat_number' ));
echo '</div>';
}
add_action( 'woocommerce_checkout_update_order_meta', 'wpdesk_checkout_vat_number_update_order_meta' );
/**
* Save VAT Number in the order meta
*/
function wpdesk_checkout_vat_number_update_order_meta( $order_id ) {
if ( ! empty( $_POST['vat_number'] ) ) {
update_post_meta( $order_id, '_vat_number', sanitize_text_field( $_POST['vat_number'] ) );
}
}
add_action( 'woocommerce_admin_order_data_after_billing_address', 'wpdesk_vat_number_display_admin_order_meta', 10, 1 );
/**
* Display VAT Number in order edit screen
*/
function wpdesk_vat_number_display_admin_order_meta( $order ) {
echo '<p><strong>' . __( 'ID za DDV', 'woocommerce' ) . ':</strong> ' . get_post_meta( $order->id, '_vat_number', true ) . '</p>';
}
add_filter( 'woocommerce_email_order_meta_keys', 'wpdesk_vat_number_display_email' );
/**
* VAT Number in emails
*/
function wpdesk_vat_number_display_email( $keys ) {
$keys['ID za DDV'] = '_vat_number';
return $keys;
}
I add this code to functions.php, but VAT number is not saved to custom fields on order page.
/**
* VAT Number in WooCommerce Checkout
*/
function wpdesk_vat_field( $checkout ) {
echo '<div id="wpdesk_vat_field"><h2>' . __('Nakup na podjetje') . '</h2>';
woocommerce_form_field( 'vat_number', array(
'type' => 'text',
'class' => array( 'vat-number-field form-row-wide') ,
'label' => __( 'V kolikor nakupujete kot podjetje, vnesite ID za DDV' ),
'placeholder' => __( 'Vnesite ID za DDV' ),
), $checkout->get_value( 'vat_number' ));
echo '</div>';
}
add_action( 'woocommerce_checkout_update_order_meta', 'wpdesk_checkout_vat_number_update_order_meta' );
/**
* Save VAT Number in the order meta
*/
function wpdesk_checkout_vat_number_update_order_meta( $order_id ) {
if ( ! empty( $_POST['vat_number'] ) ) {
update_post_meta( $order_id, '_vat_number', sanitize_text_field( $_POST['vat_number'] ) );
}
}
add_action( 'woocommerce_admin_order_data_after_billing_address', 'wpdesk_vat_number_display_admin_order_meta', 10, 1 );
/**
* Display VAT Number in order edit screen
*/
function wpdesk_vat_number_display_admin_order_meta( $order ) {
echo '<p><strong>' . __( 'ID za DDV', 'woocommerce' ) . ':</strong> ' . get_post_meta( $order->id, '_vat_number', true ) . '</p>';
}
add_filter( 'woocommerce_email_order_meta_keys', 'wpdesk_vat_number_display_email' );
/**
* VAT Number in emails
*/
function wpdesk_vat_number_display_email( $keys ) {
$keys['ID za DDV'] = '_vat_number';
return $keys;
}
I am using your code in addition I used the woocommerce_before_order_notes hook to add files and working fine for me.
/**
*
* VAT Number in WooCommerce Checkout
*/
add_action( 'woocommerce_before_order_notes', 'wpdesk_vat_field' );
function wpdesk_vat_field( $checkout ) {
echo '<div id="wpdesk_vat_field"><h2>' . __('Nakup na podjetje') . '</h2>';
woocommerce_form_field( 'vat_number', array(
'type' => 'text',
'class' => array( 'vat-number-field form-row-wide') ,
'label' => __( 'V kolikor nakupujete kot podjetje, vnesite ID za DDV' ),
'placeholder' => __( 'Vnesite ID za DDV' ),
), $checkout->get_value( 'vat_number' ));
echo '</div>';
}
add_action( 'woocommerce_checkout_update_order_meta', 'wpdesk_checkout_vat_number_update_order_meta' );
/**
* Save VAT Number in the order meta
*/
function wpdesk_checkout_vat_number_update_order_meta( $order_id ) {
if ( ! empty( $_POST['vat_number'] ) ) {
update_post_meta( $order_id, '_vat_number', sanitize_text_field( $_POST['vat_number'] ) );
}
}
add_action( 'woocommerce_admin_order_data_after_billing_address', 'wpdesk_vat_number_display_admin_order_meta', 10, 1 );
/**
* Display VAT Number in order edit screen
*/
function wpdesk_vat_number_display_admin_order_meta( $order ) {
echo '<p><strong>' . __( 'ID za DDV', 'woocommerce' ) . ':</strong> ' . get_post_meta( $order->id, '_vat_number', true ) . '</p>';
}
add_filter( 'woocommerce_email_order_meta_keys', 'wpdesk_vat_number_display_email' );
/**
* VAT Number in emails
*/
function wpdesk_vat_number_display_email( $keys ) {
$keys['ID za DDV'] = '_vat_number';
return $keys;
}
Tested and works.
Checkout
Edit Order
Mail

optimizing functions php file

for some extra needs i had to add some extra codes in fucnctions.php i notice slowing in my site i dont know if it has connection functions.php with jquery.js ,is there a anyway to optimize it ? its ok if i remove the entering space between the lines in fucntions.php id like to make as light as i can
/**
* Adding Custom GTIN Meta Field
* Save meta data to DB
*/
// add GTIN input field
add_action('woocommerce_product_options_inventory_product_data','woocom_simple_product_gtin_field', 10, 1 );
function woocom_simple_product_gtin_field(){
global $woocommerce, $post;
$product = new WC_Product(get_the_ID());
echo '<div id="gtin_attr" class="options_group">';
//add GTIN field for simple product
woocommerce_wp_text_input(
array(
'id' => '_gtin',
'label' => __( 'GTIN', 'textdomain' ),
'placeholder' => '01234567891231',
'desc_tip' => 'true',
'description' => __( 'Enter the Global Trade Item Number (UPC,EAN,ISBN)', 'textdomain' )
)
);
echo '</div>';
}
// save simple product GTIN
add_action('woocommerce_process_product_meta','woocom_simple_product_gtin_save');
function woocom_simple_product_gtin_save($post_id){
$gtin_post = $_POST['_gtin'];
// save the gtin
if(isset($gtin_post)){
update_post_meta($post_id,'_gtin', esc_attr($gtin_post));
}
// remove if GTIN meta is empty
$gtin_data = get_post_meta($post_id,'_gtin', true);
if (empty($gtin_data)){
delete_post_meta($post_id,'_gtin', '');
}
}
add_filter( 'rank_math/snippet/rich_snippet_product_entity', function( $entity ) {
global $post;
$entity['gtin8'] = get_post_meta( $post->ID,'_gtin', true );
return $entity;
});
/*
Tracking Info to WooCommerce order
Version: 0.4
$Id: tracking-info-to-wc-order.php 5168 2020-07-15 14:48:44Z damien $
*/
// Add the metabox to allow for manual entering (or editing) of tracking information.
add_action( 'cmb2_admin_init', 'dcwd_order_metabox' );
function dcwd_order_metabox() {
$cmb = new_cmb2_box( array(
'id' => 'order_tracking_info',
'title' => 'Tracking Information',
'object_types' => array( 'shop_order', ), // Post type
'context' => 'side',
'priority' => 'high',
'show_names' => true, // Show field names on the left
) );
$cmb->add_field( array(
'name' => 'Tracking number',
'id' => 'tracking_number',
'type' => 'text',
) );
$cmb->add_field( array(
'name' => 'Tracking URL',
'id' => 'tracking_url',
'type' => 'text_url',
'protocols' => array( 'http', 'https' ),
) );
}
// Examine the tracking url and return a provider name.
function dcwd_get_tracking_provider_from_url( $url ) {
if ( strpos( $url, 'usps.com' ) !== false ) {
return 'USPS';
}
if ( strpos( $url, 'fedex.com' ) !== false ) {
return 'FexEd';
}
if ( strpos( $url, 'ups.com' ) !== false ) {
return 'UPS';
}
// Add more as necessary.
// Unknown provider.
return null;
}
// If available, include the tracking information in the Completed Order email.
add_action( 'woocommerce_email_order_details', 'dcwd_add_tracking_info_to_order_completed_email', 5, 4 );
function dcwd_add_tracking_info_to_order_completed_email( $order, $sent_to_admin, $plain_text, $email ) {
/* // Only customers need to know about the tracking information.
if ( ! $sent_to_admin ) {
return;
}
*/
if ( 'customer_completed_order' == $email->id ) {
$order_id = $order->get_id();
$tracking_number = get_post_meta( $order_id, 'tracking_number', true );
$tracking_url = get_post_meta( $order_id, 'tracking_url', true );
// Quit if either tracking field is empty.
if ( empty( $tracking_number ) || empty( $tracking_url ) ) {
// Debugging code.
//error_log( sprintf( 'Order %d does not have both tracking number (%s) and url (%s)', $order_id, $tracking_number, $tracking_url ) );
//echo '<p>Ne pare rău, informațiile de urmărire nu sunt disponibile în acest moment.</p>';
return;
}
$tracking_provider = dcwd_get_tracking_provider_from_url( $tracking_url );
if ( $plain_text ) {
if ( ! empty( $tracking_provider ) ) {
printf( "\nComanda dumneavoastra a fost expediata. %s. Numărul de urmărire este %s și îl poți urmări la %s.\n", $tracking_provider, esc_html( $tracking_number ), esc_url( $tracking_url, array( 'http', 'https' ) ) );
}
else {
printf( "\nComanda dumneavoastra a fost expediata. Numărul de urmărire este %s și îl poți urmări la %s.\n", esc_html( $tracking_number ), esc_url( $tracking_url, array( 'http', 'https' ) ) );
}
}
else {
if ( ! empty( $tracking_provider ) ) {
printf( '<p>Your order has been shipped with <strong>%s</strong>. The tracking number is <strong>%s</strong>.</p>', $tracking_provider, esc_url( $tracking_url, array( 'http', 'https' ) ), esc_html( $tracking_number ) );
}
else {
printf( '<p>Comanda dumneavoastra a fost expediata. Numărul de urmărire este <strong>%s</strong>.</p>', esc_url( $tracking_url, array( 'http', 'https' ) ), esc_html( $tracking_number ) );
}
}
}
}
// Display tracking information in My Account area.
add_action( 'woocommerce_view_order', 'dcwd_add_tracking_info_to_view_order_page', 5 );
function dcwd_add_tracking_info_to_view_order_page( $order_id ) {
$tracking_number = get_post_meta( $order_id, 'tracking_number', true );
$tracking_url = get_post_meta( $order_id, 'tracking_url', true );
// Quit if either tracking field is empty.
if ( empty( $tracking_number ) || empty( $tracking_url ) ) {
// Debugging code.
error_log( sprintf( 'Order %d does not have both tracking number (%s) and url (%s)', $order_id, $tracking_number, $tracking_url ) );
echo '<p>Ne pare rău, informațiile de urmărire nu sunt disponibile în acest moment.</p>';
return;
}
$tracking_provider = dcwd_get_tracking_provider_from_url( $tracking_url );
if ( ! empty( $tracking_provider ) ) {
printf( '<p>Comanda dvs. a fost expediată cu <strong>%s</strong>. Numărul de urmărire este <strong>%s</strong>.</p>', $tracking_provider, esc_url( $tracking_url, array( 'http', 'https' ) ), esc_html( $tracking_number ) );
}
else {
printf( '<p>Comanda dumneavoastra a fost expediata. Numărul de urmărire este <strong>%s</strong>.</p>', esc_url( $tracking_url, array( 'http', 'https' ) ), esc_html( $tracking_number ) );
}
}
function add_file_types_to_uploads($file_types){
$new_filetypes = array();
$new_filetypes['svg'] = 'image/svg+xml';
$file_types = array_merge($file_types, $new_filetypes );
return $file_types;
}
add_filter('upload_mimes', 'add_file_types_to_uploads');
function flatsome_result_count_and_catalog_ordering_remover() {
remove_action( 'flatsome_category_title_alt', 'woocommerce_result_count', 20);
}
add_action('template_redirect','flatsome_result_count_and_catalog_ordering_remover');
add_filter( 'wc_add_to_cart_message_html', '__return_false' );
add_action( 'wp_print_scripts', 'de_script', 100 );
function de_script() {
wp_dequeue_script( 'wc-cart-fragments' );
return true;
}
/**
* #snippet Remove Additional Information Tab # WooCommerce Single Product Page
* #how-to Get CustomizeWoo.com FREE
* #author Rodolfo Melogli
* #testedwith WooCommerce 3.8
* #donate $9 https://businessbloomer.com/bloomer-armada/
*/
add_filter( 'woocommerce_product_tabs', 'bbloomer_remove_product_tabs', 9999 );
function bbloomer_remove_product_tabs( $tabs ) {
unset( $tabs['additional_information'] );
return $tabs;
}
/**
* Hide shipping rates when free shipping is available.
* Updated to support WooCommerce 2.6 Shipping Zones.
*
* #param array $rates Array of rates found for the package.
* #return array
*/
function my_hide_shipping_when_free_is_available( $rates ) {
$free = array();
foreach ( $rates as $rate_id => $rate ) {
if ( 'free_shipping' === $rate->method_id ) {
$free[ $rate_id ] = $rate;
break;
}
}
return ! empty( $free ) ? $free : $rates;
}
add_filter( 'woocommerce_package_rates', 'my_hide_shipping_when_free_is_available', 100 );
add_filter( 'woocommerce_default_address_fields', 'customise_postcode_fields' );
function customise_postcode_fields( $address_fields ) {
$address_fields['postcode']['required'] = false;
return $address_fields;
}
if ( function_exists( 'yith_affiliates_install' ) ) {
if ( ! function_exists( 'yith_wcaf_show_dashboard_links_call_back' ) ) {
function yith_wcaf_show_dashboard_links_call_back() {
return 'yes';
}
}
add_filter( 'yith_wcaf_show_dashboard_links', 'yith_wcaf_show_dashboard_links_call_back' );
}

Woocommerce custom payment gateway redirect back to woocommerce

I have a custom gateway, I am new to the custom plugins for woocommerce, now my problem I have is that I am able to redirect to my payment gateway but in my payment gateway (HTML) how do I redirect back after payment was made? I don't understand the whole process as yet, I know once payment is selected then I can redirect to my custom payment gateway but the confusing part is returning from payment gateway to woocommerce to say it was a success or not
<?php
/**
* Plugin Name: Woocommerce CloudCart Payment Gateway
* Plugin URI: http://cloudcart.online
* Description: Payment Gateway to use CloudCart points.
* Author: Cornelis Kuijpers
* Author URI: http://kuijpersconsulting.co.za
* Version: 1.0.1
*
*/
add_action('plugins_loaded', 'init_Cloudcart', 0);
function init_Cloudcart() {
if ( ! class_exists( 'WC_Payment_Gateway' ) ) return;
class woocommerce_Cloudcart extends WC_Payment_Gateway {
public function __construct() {
global $woocommerce;
$this->id = 'Cloudcart';
$this->method_title = __('Cloudcart', 'Cloudcart-chearaan-woo');
$this->icon = plugins_url( 'Cloudcart.png', __FILE__ );
$this->has_fields = false;
$this->notify_url = str_replace( 'https:', 'http:', add_query_arg( 'wc-api', 'woocommerce_Cloudcart', home_url( '/' ) ) );
// Load the form fields.
$this->init_form_fields();
// Load the settings.
$this->init_settings();
// Define user set variables
$this->Cloudcarturl = $this->settings['Cloudcarturl'];
$this->title = $this->settings['title'];
$this->description = $this->settings['description'];
$this->merchantid = $this->settings['merchantid'];
$this->hashKey = $this->settings['hashKey'];
$this->transactionDate = date('Y-m-d H:i:s O');
$this->woo_version = $this->get_woo_version();
// Actions
add_action('init', array(&$this, 'successful_request'));
add_action('woocommerce_api_woocommerce_Cloudcart', array( &$this, 'successful_request' ));
add_action('woocommerce_receipt_Cloudcart', array(&$this, 'receipt_page'));
if ( version_compare( WOOCOMMERCE_VERSION, '2.0.0', '>=' ) ) {
add_action('woocommerce_update_options_payment_gateways_' . $this->id, array( &$this, 'process_admin_options' ));
} else {
add_action('woocommerce_update_options_payment_gateways', array( &$this, 'process_admin_options' ));
}
}
/**
* Initialise Gateway Settings Form Fields
*/
function init_form_fields() {
$this->form_fields = array(
'enabled' => array(
'title' => __( 'Enable/Disable:', 'Cloudcart-chearaan-woo' ),
'type' => 'checkbox',
'label' => __( 'Enable Cloudcart', 'Cloudcart-chearaan-woo' ),
'default' => 'yes'
),
'Cloudcarturl' => array(
'title' => __( 'Test/Production:', 'Cloudcart-chearaan-woo' ),
'type' => 'checkbox',
'label' => __( 'Test', 'Cloudcart-chearaan-woo' ),
'default' => 'yes'
),
'title' => array(
'title' => __( 'Title:', 'Cloudcart-chearaan-woo' ),
'type' => 'text',
'description' => __( 'The title which the user sees during checkout.', 'Cloudcart-chearaan-woo' ),
'default' => __( 'Cloudcart Online Payment Gateway', 'Cloudcart-chearaan-woo' )
),
'description' => array(
'title' => __( 'Description:', 'Cloudcart-chearaan-woo' ),
'type' => 'textarea',
'description' => __( 'Description which the user sees during checkout.', 'Cloudcart-chearaan-woo' ),
'default' => __('Pay securely through Cloudcart\'s Secure Servers.', 'Cloudcart-chearaan-woo')
),
'merchantid' => array(
'title' => __( 'Merchant ID:', 'Cloudcart-chearaan-woo' ),
'type' => 'text',
'description' => __( 'Please enter your Merchant ID as provided by Cloudcart.', 'Cloudcart-chearaan-woo' ),
'default' => ''
),
'hashKey' => array(
'title' => __( 'Merchant hashKey:', 'Cloudcart-chearaan-woo' ),
'type' => 'text',
'description' => __( 'Please enter your Merchant hashKey as provided by Cloudcart.', 'Cloudcart-chearaan-woo' ),
'default' => ''
)
);
}
public function admin_options() {
?>
<h3>Cloudcart</h3>
<p><?php _e('Cloudcart works by sending the user to Cloudcart to enter their payment information.', 'Cloudcart-chearaan-woo'); ?></p>
<table class="form-table">
<?php
// Generate the HTML For the settings form.
$this->generate_settings_html();
?>
</table><!--/.form-table-->
<?php
} // End admin_options()
/**
* There are no payment fields, but we want to show the description if set.
**/
function payment_fields() {
if ($this->description) echo wpautop(wptexturize($this->description));
}
/**
* Generate the button link
**/
public function generate_Cloudcart_form( $order_id ) {
global $woocommerce;
$order = new WC_Order( $order_id );
if ($this->Cloudcarturl == "yes"){
$Cloudcart_adr = "https://ckconsulting.ddns.net/API/CloudCart/";
}else{
$Cloudcart_adr = "https://ckconsulting.ddns.net/API/CloudCart/";
}
$sHash = strtoupper(hash('sha256', $this->hashKey."Continue".str_pad($this->merchantid, 10, '0', STR_PAD_LEFT).str_pad($order->id, 20, '0', STR_PAD_LEFT).str_pad(($order->order_total*100), 12, '0', STR_PAD_LEFT)));
$Cloudcart_args = array(
'secureHash' => $sHash,
'mid' => str_pad($this->merchantid, 10, '0', STR_PAD_LEFT),
'invno' => str_pad($order->id, 20, '0', STR_PAD_LEFT),
'amt' => str_pad(($order->order_total*100), 12, '0', STR_PAD_LEFT),
'desc' => str_pad("Order No ".$order_id, 255, ' ', STR_PAD_RIGHT),
'postURL' => $this->notify_url,
'phone' => $order->billing_phone,
'email' => $order->billing_email,
'param' => 'WC|V1'
);
$Cloudcart_args_array = array();
foreach ($Cloudcart_args as $key => $value) {
$Cloudcart_args_array[] = '<input type="hidden" name="'.$key.'" value="'. $value .'" /><br>';
}
wc_enqueue_js('
jQuery(function(){
jQuery("body").block(
{
message: "<img src=\"'.$woocommerce->plugin_url().'/images/uploading.gif\" alt=\"Redirecting…\" style=\"float:left; margin-right: 10px;\" />'.__('Thank you for your order. We are now redirecting you to Cloudcart to make payment.', 'Cloudcart-chearaan-woo').'",
overlayCSS:
{
background: "#fff",
opacity: 0.5
},
css: {
padding: 18,
textAlign: "center",
color: "#555",
border: "2px solid #aaa",
backgroundColor:"#fff",
cursor: "wait",
lineHeight: "30px"
}
});
jQuery("#submit_Cloudcart_payment_form").click();
});
');
return '<form action="'.$Cloudcart_adr.'" method="post">
' . implode('', $Cloudcart_args_array) . '
<input type="submit" class="button-alt" id="submit_Cloudcart_payment_form" value="'.__('Pay via Cloudcart', 'Cloudcart-chearaan-woo').'" /> <a class="button cancel" href="'.$order->get_cancel_order_url().'">'.__('Cancel order & restore cart', 'Cloudcart-chearaan-woo').'</a>
</form>';
}
/**
* Process the payment and return the result
**/
function process_payment( $order_id ) {
$order = new WC_Order( $order_id );
echo get_permalink(get_option('woocommerce_pay_page_id'));
if($this->woo_version >= 2.1){
$redirect = $order->get_checkout_payment_url( true );
}else if( $this->woo_version < 2.1 ){
$redirect = add_query_arg('order', $order->id, add_query_arg('key', $order->order_key, get_permalink(get_option('woocommerce_pay_page_id'))));
}else{
$redirect = add_query_arg('order', $order->id, add_query_arg('key', $order->order_key, get_permalink(get_option('woocommerce_pay_page_id'))));
}
return array(
'result' => 'success',
'redirect' => $redirect
);
}
/**
* receipt_page
**/
function receipt_page( $order ) {
echo '<p>'.__('Please click the button below to pay with Cloudcart.', 'Cloudcart-chearaan-woo').'</p>';
echo $this->generate_Cloudcart_form( $order );
}
/**
* Server callback was valid, process callback (update order as passed/failed etc).
**/
function successful_request($Cloudcart_response) {
global $woocommerce;
echo 'Hello from the other side';
if (isset($_GET['wc-api']) && $_GET['wc-api'] == 'woocommerce_Cloudcart') {
/** need to trim from result **/
$Url_result = $_GET['result'];
$order = new WC_Order( (int) substr($Url_result,7,20) );
$tranID = (int)substr($Url_result,1,6);
if (substr($Url_result,0,1) == '0'){
$r_status = 0;
}else{
$r_status = 33;
}
/*
$order = new WC_Order( (int) $_POST['invno'] );
$r_status = (int) $_POST['result'];
*/
if ($r_status == '0' ){
$order->payment_complete();
$order->add_order_note('Cloudcart Payment was SUCCESSFUL '.'<br>AuthCode is ' . $tranID);
wp_redirect( $this->get_return_url($order) ); exit;
//wp_redirect( $this->order->get_checkout_order_received_url() ); exit;
}else{
$order->update_status('failed', sprintf(__('Cloudcart Payment Failed. Error Communicating with Bank.', 'Cloudcart-chearaan-woo') ) );
wp_redirect($order->get_cancel_order_url()); exit;
}
}
}
function get_woo_version() {
// If get_plugins() isn't available, require it
if ( ! function_exists( 'get_plugins' ) )
require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
// Create the plugins folder and file variables
$plugin_folder = get_plugins( '/woocommerce' );
$plugin_file = 'woocommerce.php';
// If the plugin version number is set, return it
if ( isset( $plugin_folder[$plugin_file]['Version'] ) ) {
return $plugin_folder[$plugin_file]['Version'];
} else {
// Otherwise return null
return NULL;
}
}
}
}
/**
* Add the gateway to WooCommerce
**/
function add_Cloudcart( $methods ) {
$methods[] = 'woocommerce_Cloudcart'; return $methods;
}
add_filter('woocommerce_payment_gateways', 'add_Cloudcart' );

Woocommerce Custom Payment Gateway Not Redirecting

I have a WC payment gateway which was build and working until WP version 4.1. Today I started testing it on WP 4.9.8 and WC 3.5.1.
When I try to complete purchase the payment gateway is not taking me to the payment screen to fill credit card details. It get stuck on redirection state.
Hope someone can help me out to solve this.
Below the image reference and the code I am using:
<?php
/**
* Plugin Name: CustomPaymentGateway
*/
add_action('plugins_loaded', 'init_mpay', 0);
function init_mpay() {
if ( ! class_exists( 'WC_Payment_Gateway' ) ) return;
class woocommerce_mpay extends WC_Payment_Gateway {
public function __construct() {
global $woocommerce;
$this->id = 'mpay';
$this->method_title = __('MPay', 'mpay-chearaan-woo');
$this->icon = plugins_url( 'mpay.png', __FILE__ );
$this->has_fields = false;
$this->notify_url = str_replace( 'https:', 'http:', add_query_arg( 'wc-api', 'woocommerce_mpay', home_url( '/' ) ) );
// Load the form fields.
$this->init_form_fields();
// Load the settings.
$this->init_settings();
// Define user set variables
$this->mpayurl = $this->settings['mpayurl'];
$this->title = $this->settings['title'];
$this->description = $this->settings['description'];
$this->merchantid = $this->settings['merchantid'];
$this->hashKey = $this->settings['hashKey'];
$this->transactionDate = date('Y-m-d H:i:s O');
$this->woo_version = $this->get_woo_version();
// Actions
add_action('init', array(&$this, 'successful_request'));
add_action('woocommerce_api_woocommerce_mpay', array( &$this, 'successful_request' ));
add_action('woocommerce_receipt_mpay', array(&$this, 'receipt_page'));
if ( version_compare( WOOCOMMERCE_VERSION, '2.0.0', '>=' ) ) {
add_action('woocommerce_update_options_payment_gateways_' . $this->id, array( &$this, 'process_admin_options' ));
} else {
add_action('woocommerce_update_options_payment_gateways', array( &$this, 'process_admin_options' ));
}
}
/**
* Initialise Gateway Settings Form Fields
*/
function init_form_fields() {
$this->form_fields = array(
'enabled' => array(
'title' => __( 'Enable/Disable:', 'mpay-chearaan-woo' ),
'type' => 'checkbox',
'label' => __( 'Enable MPay', 'mpay-chearaan-woo' ),
'default' => 'yes'
),
'mpayurl' => array(
'title' => __( 'UAT/Production:', 'mpay-chearaan-woo' ),
'type' => 'checkbox',
'label' => __( 'UAT', 'mpay-chearaan-woo' ),
'default' => 'yes'
),
'title' => array(
'title' => __( 'Title:', 'mpay-chearaan-woo' ),
'type' => 'text',
'description' => __( 'The title which the user sees during checkout.', 'mpay-chearaan-woo' ),
'default' => __( 'MPay Online Payment Gateway', 'mpay-chearaan-woo' )
),
'description' => array(
'title' => __( 'Description:', 'mpay-chearaan-woo' ),
'type' => 'textarea',
'description' => __( 'Description which the user sees during checkout.', 'mpay-chearaan-woo' ),
'default' => __('Pay securely through MPay\'s Secure Servers.', 'mpay-chearaan-woo')
),
'merchantid' => array(
'title' => __( 'Merchant ID:', 'mpay-chearaan-woo' ),
'type' => 'text',
'description' => __( 'Please enter your Merchant ID as provided by MPay.', 'mpay-chearaan-woo' ),
'default' => ''
),
'hashKey' => array(
'title' => __( 'Merchant hashKey:', 'mpay-chearaan-woo' ),
'type' => 'text',
'description' => __( 'Please enter your Merchant hashKey as provided by MPay.', 'mpay-chearaan-woo' ),
'default' => ''
)
);
}
public function admin_options() {
?>
<h3>MPay</h3>
<p><?php _e('MPay works by sending the user to MPay to enter their payment information.', 'mpay-chearaan-woo'); ?></p>
<table class="form-table">
<?php
// Generate the HTML For the settings form.
$this->generate_settings_html();
?>
</table><!--/.form-table-->
<?php
} // End admin_options()
/**
* There are no payment fields, but we want to show the description if set.
**/
function payment_fields() {
if ($this->description) echo wpautop(wptexturize($this->description));
}
/**
* Generate the button link
**/
public function generate_mpay_form( $order_id ) {
global $woocommerce;
$order = new WC_Order( $order_id );
if ($this->mpayurl == "yes"){
$mpay_adr = "https://pcimdex.mpay.my/mdex2/payment/eCommerce";
}else{
$mpay_adr = "https://www.mdex.my/mdex/payment/eCommerce";
}
$sHash = strtoupper(hash('sha256', $this->hashKey."Continue".str_pad($this->merchantid, 10, '0', STR_PAD_LEFT).str_pad($order->id, 20, '0', STR_PAD_LEFT).str_pad(($order->order_total*100), 12, '0', STR_PAD_LEFT)));
$mpay_args = array(
'secureHash' => $sHash,
'mid' => str_pad($this->merchantid, 10, '0', STR_PAD_LEFT),
'invno' => str_pad($order->id, 20, '0', STR_PAD_LEFT),
'amt' => str_pad(($order->order_total*100), 12, '0', STR_PAD_LEFT),
'desc' => str_pad("Order No ".$order_id, 255, ' ', STR_PAD_RIGHT),
'postURL' => $this->notify_url,
'phone' => $order->billing_phone,
'email' => $order->billing_email,
'param' => 'WC|V1'
);
$mpay_args_array = array();
foreach ($mpay_args as $key => $value) {
$mpay_args_array[] = '<input type="hidden" name="'.$key.'" value="'. $value .'" /><br>';
}
wc_enqueue_js('
jQuery(function(){
jQuery("body").block(
{
message: "<img src=\"'.$woocommerce->plugin_url().'/images/uploading.gif\" alt=\"Redirecting…\" style=\"float:left; margin-right: 10px;\" />'.__('Thank you for your order. We are now redirecting you to MPay to make payment.', 'mpay-chearaan-woo').'",
overlayCSS:
{
background: "#fff",
opacity: 0.5
},
css: {
padding: 18,
textAlign: "center",
color: "#555",
border: "2px solid #aaa",
backgroundColor:"#fff",
cursor: "wait",
lineHeight: "30px"
}
});
jQuery("#submit_mpay_payment_form").click();
});
');
return '<form action="'.$mpay_adr.'" method="post">
' . implode('', $mpay_args_array) . '
<input type="submit" class="button-alt" id="submit_mpay_payment_form" value="'.__('Pay via MPay', 'mpay-chearaan-woo').'" /> <a class="button cancel" href="'.$order->get_cancel_order_url().'">'.__('Cancel order & restore cart', 'mpay-chearaan-woo').'</a>
</form>';
}
/**
* Process the payment and return the result
**/
function process_payment( $order_id ) {
$order = new WC_Order( $order_id );
if($this->woo_version >= 2.1){
$redirect = $order->get_checkout_payment_url( true );
}else if( $this->woo_version < 2.1 ){
$redirect = add_query_arg('order', $order->id, add_query_arg('key', $order->order_key, get_permalink(get_option('woocommerce_pay_page_id'))));
}else{
$redirect = add_query_arg('order', $order->id, add_query_arg('key', $order->order_key, get_permalink(get_option('woocommerce_pay_page_id'))));
}
return array(
'result' => 'success',
'redirect' => $redirect
);
}
/**
* receipt_page
**/
function receipt_page( $order ) {
echo '<p>'.__('Please click the button below to pay with MPay.', 'mpay-chearaan-woo').'</p>';
echo $this->generate_mpay_form( $order );
}
/**
* Server callback was valid, process callback (update order as passed/failed etc).
**/
function successful_request($mpay_response) {
global $woocommerce;
if (isset($_GET['wc-api']) && $_GET['wc-api'] == 'woocommerce_mpay') {
/** need to trim from result **/
$Url_result = $_GET['result'];
$order = new WC_Order( (int) substr($Url_result,7,20) );
$tranID = (int)substr($Url_result,1,6);
if (substr($Url_result,0,1) == '0'){
$r_status = 0;
}else{
$r_status = 33;
}
/*
$order = new WC_Order( (int) $_POST['invno'] );
$r_status = (int) $_POST['result'];
*/
if ($r_status == '0' ){
$order->payment_complete();
$order->add_order_note('MPay Payment was SUCCESSFUL '.'<br>AuthCode is ' . $tranID);
wp_redirect( $this->get_return_url($order) ); exit;
//wp_redirect( $this->order->get_checkout_order_received_url() ); exit;
}else{
$order->update_status('failed', sprintf(__('MPay Payment Failed. Error Communicating with Bank.', 'mpay-chearaan-woo') ) );
wp_redirect($order->get_cancel_order_url()); exit;
}
}
}
function get_woo_version() {
// If get_plugins() isn't available, require it
if ( ! function_exists( 'get_plugins' ) )
require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
// Create the plugins folder and file variables
$plugin_folder = get_plugins( '/woocommerce' );
$plugin_file = 'woocommerce.php';
// If the plugin version number is set, return it
if ( isset( $plugin_folder[$plugin_file]['Version'] ) ) {
return $plugin_folder[$plugin_file]['Version'];
} else {
// Otherwise return null
return NULL;
}
}
}
}
/**
* Add the gateway to WooCommerce
**/
function add_mpay( $methods ) {
$methods[] = 'woocommerce_mpay'; return $methods;
}
add_filter('woocommerce_payment_gateways', 'add_mpay' );

WooCommerce - send custom email on custom order status change

I added a custom status wc-order-confirmed:
// Register new status
function register_order_confirmed_order_status() {
register_post_status( 'wc-order-confirmed', array(
'label' => 'Potvrzení objednávky',
'public' => true,
'exclude_from_search' => false,
'show_in_admin_all_list' => true,
'show_in_admin_status_list' => true,
'label_count' => _n_noop( 'Potvrzení objednávky <span class="count">(%s)</span>', 'Potvrzení objednávky <span class="count">(%s)</span>' )
) );
}
add_action( 'init', 'register_order_confirmed_order_status' );
// Add to list of WC Order statuses
function add_order_confirmed_to_order_statuses( $order_statuses ) {
$new_order_statuses = array();
// add new order status after processing
foreach ( $order_statuses as $key => $status ) {
$new_order_statuses[ $key ] = $status;
if ( 'wc-processing' === $key ) {
$new_order_statuses['wc-order-confirmed'] = 'Potvrzení objednávky';
}
}
return $new_order_statuses;
}
add_filter( 'wc_order_statuses', 'add_order_confirmed_to_order_statuses' );
I added a custom email wc_confirmed_order:
/**
* A custom confirmed Order WooCommerce Email class
*
* #since 0.1
* #extends \WC_Email
*/
class WC_Confirmed_Order_Email extends WC_Email {
/**
* Set email defaults
*
* #since 0.1
*/
public function __construct() {
// set ID, this simply needs to be a unique name
$this->id = 'wc_confirmed_order';
// this is the title in WooCommerce Email settings
$this->title = 'Potvrzení objednávky';
// this is the description in WooCommerce email settings
$this->description = 'Confirmed Order Notification';
// these are the default heading and subject lines that can be overridden using the settings
$this->heading = 'Potvrzení objednávky';
$this->subject = 'Potvrzení objednávky';
// these define the locations of the templates that this email should use, we'll just use the new order template since this email is similar
$this->template_html = 'emails/customer-confirmed-order.php';
$this->template_plain = 'emails/plain/admin-new-order.php';
// Trigger on confirmed orders
add_action( 'woocommerce_order_status_pending_to_order_confirmed', array( $this, 'trigger' ) );
add_action( 'woocommerce_order_status_processing_to_order_confirmed', array( $this, 'trigger' ) );
// Call parent constructor to load any other defaults not explicity defined here
parent::__construct();
// this sets the recipient to the settings defined below in init_form_fields()
$this->recipient = $this->get_option( 'recipient' );
// if none was entered, just use the WP admin email as a fallback
if ( ! $this->recipient )
$this->recipient = get_option( 'admin_email' );
}
/**
* Determine if the email should actually be sent and setup email merge variables
*
* #since 0.1
* #param int $order_id
*/
public function trigger( $order_id ) {
// bail if no order ID is present
if ( ! $order_id )
return;
if ( $order_id ) {
$this->object = wc_get_order( $order_id );
$this->recipient = $this->object->billing_email;
$this->find['order-date'] = '{order_date}';
$this->find['order-number'] = '{order_number}';
$this->replace['order-date'] = date_i18n( wc_date_format(), strtotime( $this->object->order_date ) );
$this->replace['order-number'] = $this->object->get_order_number();
}
if ( ! $this->is_enabled() || ! $this->get_recipient() )
return;
// woohoo, send the email!
$this->send( $this->get_recipient(), $this->get_subject(), $this->get_content(), $this->get_headers(), $this->get_attachments() );
}
/**
* get_content_html function.
*
* #since 0.1
* #return string
*/
public function get_content_html() {
ob_start();
wc_get_template( $this->template_html, array(
'order' => $this->object,
'email_heading' => $this->get_heading()
) );
return ob_get_clean();
}
/**
* get_content_plain function.
*
* #since 0.1
* #return string
*/
public function get_content_plain() {
ob_start();
wc_get_template( $this->template_plain, array(
'order' => $this->object,
'email_heading' => $this->get_heading()
) );
return ob_get_clean();
}
/**
* Initialize Settings Form Fields
*
* #since 2.0
*/
public function init_form_fields() {
$this->form_fields = array(
'enabled' => array(
'title' => 'Enable/Disable',
'type' => 'checkbox',
'label' => 'Enable this email notification',
'default' => 'yes'
),
'recipient' => array(
'title' => 'Recipient(s)',
'type' => 'text',
'description' => sprintf( 'Enter recipients (comma separated) for this email. Defaults to <code>%s</code>.', esc_attr( get_option( 'admin_email' ) ) ),
'placeholder' => '',
'default' => ''
),
'subject' => array(
'title' => 'Subject',
'type' => 'text',
'description' => sprintf( 'This controls the email subject line. Leave blank to use the default subject: <code>%s</code>.', $this->subject ),
'placeholder' => '',
'default' => ''
),
'heading' => array(
'title' => 'Email Heading',
'type' => 'text',
'description' => sprintf( __( 'This controls the main heading contained within the email notification. Leave blank to use the default heading: <code>%s</code>.' ), $this->heading ),
'placeholder' => '',
'default' => ''
),
'email_type' => array(
'title' => 'Email type',
'type' => 'select',
'description' => 'Choose which format of email to send.',
'default' => 'html',
'class' => 'email_type',
'options' => array(
'plain' => __( 'Plain text', 'woocommerce' ),
'html' => __( 'HTML', 'woocommerce' ),
'multipart' => __( 'Multipart', 'woocommerce' ),
)
)
);
}
} // end \WC_confirmed_Order_Email class
I can see the email in the email settings, and the status in the order statuses dropdown. Now, I need to send my new email whenever the order status is changed to wc-order-confirmed. The transition hook seems to never be firing.
I also tried:
/**
* Register the "woocommerce_order_status_pending_to_quote" hook which is necessary to
* allow automatic email notifications when the order is changed to refunded.
*
* #modified from http://stackoverflow.com/a/26413223/2078474 to remove anonymous function
*/
add_action( 'woocommerce_init', 'so_25353766_register_email' );
function so_25353766_register_email(){
add_action( 'woocommerce_order_status_pending_to_order_confirmed', array( WC(), 'send_transactional_email' ), 10, 10 );
add_action( 'woocommerce_order_status_processing_to_order_confirmed', array( WC(), 'send_transactional_email' ), 10, 10 );
}
Which also doesn't seem to work at all... Any ideas, please?
The hook you need is:
woocommerce_order_status_changed
add_action("woocommerce_order_status_changed", "my_awesome_publication_notification");
function my_awesome_publication_notification($order_id, $checkout=null) {
global $woocommerce;
$order = new WC_Order( $order_id );
if($order->status === 'completed' ) {
// Create a mailer
$mailer = $woocommerce->mailer();
$message_body = __( 'Hello world!!!' );
$message = $mailer->wrap_message(
// Message head and message body.
sprintf( __( 'Order %s received' ), $order->get_order_number() ), $message_body );
// Cliente email, email subject and message.
$mailer->send( $order->billing_email, sprintf( __( 'Order %s received' ), $order->get_order_number() ), $message );
}
}
}
As Xcid's answer indicates, you need to register the email.
In WC 2.2+ I believe you can do this via the following:
add_action( 'woocommerce_order_status_wc-order-confirmed', array( WC(), 'send_transactional_email' ), 10, 10 );
I'd added a filter to WooCommerce 2.3, so when that comes out custom emails will be able to be added to the list of email actions that WooCommerce registers:
// As of WooCommerce 2.3
function so_27112461_woocommerce_email_actions( $actions ){
$actions[] = 'woocommerce_order_status_wc-order-confirmed';
return $actions;
}
add_filter( 'woocommerce_email_actions', 'so_27112461_woocommerce_email_actions' );
As you can see here :
https://github.com/woothemes/woocommerce/blob/f8a161c40673cb019eb96b04c04a774ca040a15a/includes/abstracts/abstract-wc-order.php#L2097
you can use this hook :
do_action( 'woocommerce_order_status_' . $new_status, $this->id );
with you custom status should give :
add_action( 'woocommerce_order_status_wc-order-confirmed' , array( $this, 'trigger' ) );
I imagine that you also add you custom email to the mailer, if not :
just add :
add_filter( 'woocommerce_email_classes', array($this,'edit_woocommerce_email_classes' ));
function edit_woocommerce_email_classes( $email_classes ) {
require_once( 'your-email-class.php' );
$email_classes[ 'WC_Confirmed_Order_Email' ] = new WC_Confirmed_Order_Email();
return $email_classes;
}
Edit :
You need to instanciate woocommerce emails before so you can add
add_action( 'init' , 'initiate_woocommerce_email' );
function initiate_woocommerce_email(){
// Just when you update the order_status on backoffice
if( isset($_POST['order_status']) ) {
WC()->mailer();
}
}
You can try to watch when the order status changed so put this into functions.php:
function confirmed_notifications($order_id, $checkout=null) {
global $woocommerce;
$order = new WC_Order( $order_id );
if( $order->status === 'order-confirmed' ) {
// Trigger transactional email to client
$email = $mailer->emails['WC_Confirmed_Order_Email'];
$email->trigger( $order_id );
}
}
add_action("woocommerce_order_status_changed", "confirmed_notifications");
This function will trigger your email and send it.

Categories