Woocommerce, recognize "cash on delivery" not valid addresses - woocommerce

I'm trying to create a function.
My need is follow:
I have a cash on delivery payment method.
Sometime it happens that the shipping comes back because the address is wrong or not real.
Then I put this order in SPAM status.
I want that when I have a COD order, to check in all SPAM orders if address is present, if yes put the order in SPAM review status, so I can check it personally with client.
This is my code:
I put a check address button on "on hold" orders, that will check the addresses:
// 1. Create 2 new order statuses: SPAM and SPAM REVIEW
function create_new_order_statuses() {
register_post_status( 'wc-spam', array(
'label' => 'SPAM',
'public' => true,
'exclude_from_search' => false,
'show_in_admin_all_list' => true,
'show_in_admin_status_list' => true
) );
register_post_status( 'wc-spam-review', array(
'label' => 'SPAM REVIEW',
'public' => true,
'exclude_from_search' => false,
'show_in_admin_all_list' => true,
'show_in_admin_status_list' => true
) );
}
add_action( 'init', 'create_new_order_statuses' );
// 2. Register them in woocommerce
function add_spam_order_statuses_to_select( $order_statuses ) {
$order_statuses['wc-spam'] = 'SPAM';
$order_statuses['wc-spam-review'] = 'SPAM REVIEW';
return $order_statuses;
}
add_filter( 'wc_order_statuses', 'add_spam_order_statuses_to_select' );
add_action( 'woocommerce_admin_order_data_after_order_details', 'check_address_button_on_order_page' );
function check_address_button_on_order_page( $order ) {
if ( $order->get_status() === 'on-hold' ) {
$address = $order->get_address( 'shipping' );
echo '<button class="button check-address-button">Check Address</button>';
?>
<script>
jQuery('.check-address-button').click( function() {
var data = {
'action': 'check_address',
'address': <?php echo json_encode( $address ); ?>
};
jQuery.post(ajaxurl, data, function(response) {
if(response.found) {
alert('Match found, order status changed to "SPAM REVIEW"');
} else {
alert('No match found');
}
});
});
</script>
<?php
}
}
add_action( 'wp_ajax_check_address', 'check_address' );
function check_address() {
$address = json_decode( $_POST['address'] );
$spam_orders = wc_get_orders( array(
'status' => 'spam',
) );
foreach ( $spam_orders as $spam_order ) {
if ( $address == $spam_order->get_address( 'shipping' ) ) {
$order_id = $_POST['order_id'];
$order = wc_get_order( $order_id );
$order->update_status( 'spam-review' );
echo json_encode( array( 'found' => true ) );
wp_die();
}
}
echo json_encode( array( 'found' => false ) );
wp_die();
}
Of course doesn't work... any suggestion?

Related

How can I add a check and not send an auto-reply to certain comments if the user fills in a custom field?

I'm using custom fields in the comment form "Did you like this book?" and "yes" and "no" values. I want to send 2 different auto-replies to a comment, if the user selects "yes" then the response is "Thank you for your kind recognition, customer's satisfaction is always our goal." and if "no" then the auto answer is "We'll strive to do better." I would appreciate any of your help...
//And this is how I send an auto reply to a comment
add_action( 'comment_post', 'author_new_comment', 10, 3 );
function author_new_comment( $comment_ID, $comment_approved, $commentdata ){
$comment_parent = (int) $commentdata['comment_parent'];
// If a new comment is a reply to another comment, don't do anything
if ( $comment_parent !== 0 ) {
return;
}
//How do I add a response if the comment contains the value of the [likebook ] meta field???
if( !empty( $_POST['likebook'] ) {
return;
}
$commentdata = [
'comment_post_ID' => $commentdata['comment_post_ID'],
'comment_author' => 'admin',
'comment_author_email' => 'admin#example.com',
'comment_author_url' => 'http://example.com',
'comment_content' => 'Thank you for your kind recognition, customer satisfaction is always our goal.',
'comment_type' => 'comment',
'comment_parent' => $comment_ID,
'user_ID' => 1,
];
wp_new_comment( $commentdata );
}
try these,
add_action( 'comment_post', 'author_new_comment', 10, 3 );
function author_new_comment( $comment_ID, $comment_approved, $comment ) {
if ( $comment['comment_parent'] !== 0 ) {
return;
}
if ( ! empty( $_POST['like'] ) ) {
if ( $_POST['like'] == 'dog' ) {
$msg = 'We are glad that you liked it!';
} else {
$msg = 'We will try to make this product better!';
}
$admins = get_super_admins();
$current_user = get_user_by( 'login', $admins[0] );
$data = array(
'comment_post_ID' => $comment['comment_post_ID'],
'comment_content' => $msg,
'comment_parent' => $comment_ID,
'user_id' => $current_user->ID,
'comment_author' => $current_user->user_login,
'comment_author_email' => $current_user->user_email,
'comment_author_url' => $current_user->user_url
);
$comment_id = wp_insert_comment( $data );
if ( is_wp_error( $comment_id ) ) {
throw new Exception( $comment_id );
}
}
}

Refresh shipping rates on city select field

I am trying to update/refresh the shipping rates on city change, so far I have managed to do so only by refreshing the page manually.
add_action( 'woocommerce_package_rates', 'check_minimum_and_city', 10, 2 );
function check_minimum_and_city($rates, $package){
$selected_city = WC()->checkout->get_value('billing_city');
$price_thirty = array('bat-yam','hulon','azur','tel-aviv-yafo','givatayim','ramat-gan','bnei-brak','rishon-letzion','netaim','yavne','kfar-nagid','galiya','ben-zakai','beit-gamliel');
$price_fifty = array('einot','gan-shlomo','beit-oved','aseret','givat-brener','irus','misgav-dov','givton','kerem-yavne','beit-raban','rehovot','beit-elezri','beit-hanan','kvuzat-yavne','kfar-bilu','bnei-darom','nir-galim','kiryat-ekron','gedera','nes-tziona','kanot','gan-darom','netayim','mishmar-hashiva','gan-sorek','beit-dagan','ganot','beit-hanan-irus','hemed');
$price_sixty = array('savion','ganei-tikva','or-yehuda','kiryat-ono','yehud','petah-tikva','ramat-hasharon','herzliya','kfar-shmariyahu','rishpon','raanana','kfar-saba','tsafria','beer-yaakov','netser-sireni','nir-tzvi','ramla','matsliax','bnaya','kfar-aviv');
if(WC()->session->get( 'chosen_shipping_methods' )[0] == 'local_pickup:13'){
$minimum = 0;
}else{
$minimum_thirty = 100;
$minimum_fifty = 150;
$minimum_sixty = 200;
if(in_array($selected_city, $price_thirty)){
unset( $rates['flat_rate:18']);
unset( $rates['flat_rate:19']);
if(WC()->cart->subtotal < $minimum_thirty){
throw new Exception(
sprintf( 'סכום ההזמנה הנוכחית שלך עומד על %s, מינימום הזמנה לפני משלוח הינו %s.' ,
wc_price( WC()->cart->subtotal ),
wc_price( $minimum_thirty )
)
);
}
}elseif(in_array($selected_city, $price_fifty)){
unset( $rates['flat_rate:9']);
unset( $rates['flat_rate:19']);
if(WC()->cart->subtotal < $minimum_fifty){
throw new Exception(
sprintf( 'סכום ההזמנה הנוכחית שלך עומד על %s, מינימום הזמנה לפני משלוח הינו %s.' ,
wc_price( WC()->cart->subtotal ),
wc_price( $minimum_fifty )
)
);
}
}elseif(in_array($selected_city, $price_sixty)){
unset( $rates['flat_rate:9']);
unset( $rates['flat_rate:18']);
if(WC()->cart->subtotal < $minimum_sixty){
throw new Exception(
sprintf( 'סכום ההזמנה הנוכחית שלך עומד על %s, מינימום הזמנה לפני משלוח הינו %s.' ,
wc_price( WC()->cart->subtotal ),
wc_price( $minimum_sixty )
)
);
}
}
return $rates;
}
}
When I select a city field (dropdown custom list) I get the shipping cost I have made through the woocommerce settings but when I change it it does not update the rates.
add_filter( 'woocommerce_checkout_fields', 'city_dropdown_field' );
function city_dropdown_field( $fields ) {
$city_args = wp_parse_args( array(
'type' => 'select',
'options' => array(
'' => '',
'yavne' => 'יבנה',
'kfar-nagid' => 'כפר הנגיד',
'galiya' => 'גאליה',
'ben-zakai' => 'בן זכאי',
'beit-gamliel' => 'בית גמליאל',
'bnaya' => 'בניה',
'einot' => 'עינות',
'kfar-aviv' => 'כפר אביב',
'gan-shlomo' => 'גן שלמה',
'beit-oved' => 'בית עובד',
'aseret' => 'עשרת',
'givat-brener' => 'גבעת ברנר',
'irus' => 'אירוס',
'misgav-dov' => 'משגב דב',
'givton' => 'גיבתון',
'kerem-yavne' => 'כרם יבנה',
'beit-raban' => 'בית רבן',
'rehovot' => 'רחובות',
'beit-elezri' => 'בית אלעזרי',
'beit-hanan' => 'בית חנן',
'kvuzat-yavne' => 'קבוצת יבנה',
'kfar-bilu' => 'כפר בילו',
'bnei-darom' => 'בני דרום',
'nir-galim' => 'ניר גלים',
'kiryat-ekron' => 'קרית עקרון',
'gedera' => 'גדרה',
'nes-tziona' => 'נס ציונה',
'kanot' => 'כנות',
'netayim' => 'נטעים',
'gan-darom' => 'גן דרום',
'givatayim' => 'גבעתיים',
'ramat-gan' => 'רמת גן',
'tel-aviv-yafo' => 'תל אביב - יפו',
'bnei-brak' => 'בני ברק',
'ramat-hasharon' => 'רמת השרון',
'herzliya' => 'הרצליה',
'kfar-shmariyahu' => 'כפר שמריהו',
'rishpon' => 'רישפון',
'raanana' => 'רעננה',
'kfar-saba' => 'כפר סבא',
'bat-yam' => 'בת ים',
'hulon' => 'חולון',
'azur' => 'אזור',
'savion' => 'סביון',
'ganei-tikva' => 'גני תקווה',
'or-yehuda' => 'אור יהודה',
'kiryat-ono' => 'קרית אונו',
'yehud' => 'יהוד',
'petah-tikva' => 'פתח תקווה',
'rishon-letzion' => 'ראשון לציון',
'mishmar-hashiva' => 'משמר השבעה',
'gan-sorek' => 'גן שורק',
'beit-dagan' => 'בית דגן',
'ganot' => 'גנות',
'beit-hanan-irus' => 'בית חנן אירוס',
'hemed' => 'חמד',
'tsafria' => 'צפריה',
'beer-yaakov' => 'באר יעקב',
'netser-sireni' => 'נצר סירני',
'nir-tzvi' => 'ניר צבי',
'ramla' => 'רמלה',
'matsliax' => 'מצליח',
'clear' => true
),
), $fields['shipping']['shipping_city'] );
$fields['shipping']['shipping_city'] = $city_args;
$fields['billing']['billing_city'] = $city_args;
return $fields;
}
Tried using this jQuery but nothing does the work
add_action( 'wp_footer', 'checkout_shipping_city_refresh_display' );
function checkout_shipping_city_refresh_display() {
// On checkout
if ( is_checkout() && ! is_wc_endpoint_url() ) :
?><script type="text/javascript">
jQuery( function($){
// Shipping fias code change & input events
$(document.body).on( 'change', 'select[name=billing_city]', function() {
console.log($(this).val());
});
});
</script>
<?php
endif;
}
Help is appreciated. :-)
I have Managed to resolve the issue and here is my solution, the answer was in corrected AJAX call and changing from multiple shipping rates to one and changing the rate by code.
add_action('woocommerce_checkout_update_order_review', 'refresh_shipping_methods', 10, 1 );
function refresh_shipping_methods( $post_data ){
WC()->cart->calculate_shipping();
}
add_action( 'wp_footer', 'checkout_shipping_city_refresh_display' );
function checkout_shipping_city_refresh_display() {
// On checkout
if ( is_checkout() && ! is_wc_endpoint_url() ) :
?><script type="text/javascript">
jQuery(document).on('change', 'select[name=billing_city]', function(){
var requested_city = jQuery(this).val();
ajaxurl = '<?php echo admin_url( 'admin-ajax.php' ) ?>'; // get ajaxurl
var data = {
'action': 'get_and_set_shipping_rate',
'city': requested_city
};
jQuery.ajax({
type: "POST",
url: ajaxurl, // this will point to admin-ajax.php
data: data,
async: false,
success: function (response) {
console.log(response);
setTimeout(function (){
jQuery('.shipping_method:checked').trigger('change');
});
}
});
});
</script>
<?php
endif;
}
function get_and_set_shipping_rate(){
$shipping_city = $_POST['city'];
$shipping_cost = get_shipping_cost_by_city($shipping_city);
setcookie('shipping_city_cost', $shipping_cost, time() + (86400 * 30), '/');
$_COOKIE['shipping_city_cost'] = $shipping_cost;
echo $shipping_cost;
wp_die();
}
add_action( 'wp_ajax_get_and_set_shipping_rate', 'get_and_set_shipping_rate' );
add_action( 'wp_ajax_nopriv_get_and_set_shipping_rate', 'get_and_set_shipping_rate' );
function get_shipping_cost_by_city( $city ) {
$cost = 30;
$price_thirty = array('bat-yam','hulon','azur','tel-aviv-yafo','givatayim','ramat-gan','bnei-brak','rishon-letzion','netaim','yavne','kfar-nagid','galiya','ben-zakai','beit-gamliel');
$price_fifty = array('einot','gan-shlomo','beit-oved','aseret','givat-brener','irus','misgav-dov','givton','kerem-yavne','beit-raban','rehovot','beit-elezri','beit-hanan','kvuzat-yavne','kfar-bilu','bnei-darom','nir-galim','kiryat-ekron','gedera','nes-tziona','kanot','gan-darom','netayim','mishmar-hashiva','gan-sorek','beit-dagan','ganot','beit-hanan-irus','hemed');
$price_sixty = array('savion','ganei-tikva','or-yehuda','kiryat-ono','yehud','petah-tikva','ramat-hasharon','herzliya','kfar-shmariyahu','rishpon','raanana','kfar-saba','tsafria','beer-yaakov','netser-sireni','nir-tzvi','ramla','matsliax','bnaya','kfar-aviv');
// SET HERE the default cost (when "calculated cost" is not yet defined)
if(in_array($city, $price_thirty)){
$cost = 30;
}elseif(in_array($city, $price_fifty)){
$cost = 50;
}elseif(in_array($city, $price_sixty)){
$cost = 60;
}
return $cost;
}
add_filter('woocommerce_package_rates', 'update_shipping_costs_based_on_cart_session_custom_data', 10, 2);
function update_shipping_costs_based_on_cart_session_custom_data( $rates, $package ){
$selected_city = WC()->checkout->get_value('billing_city');
$calculated_cost = get_shipping_cost_by_city($selected_city);
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return $rates;
// SET HERE the default cost (when "calculated cost" is not yet defined)
$cost = '30';
// Iterating though Shipping Methods
foreach ( $rates as $rate_key => $rate_values ) {
$method_id = $rate_values->method_id;
$rate_id = $rate_values->id;
// For "Flat rate" Shipping" Method only
if ( 'flat_rate' === $method_id ) {
if( ! empty( $calculated_cost ) ) {
$cost = $calculated_cost;
}
// Set the rate cost
$rates[$rate_id]->cost = number_format($rates[$rate_id]->cost * $cost, 2);
WC()->session->set( 'shipping_calculated_cost', $rates[$rate_id]->cost );
// Taxes rate cost (if enabled)
foreach ($rates[$rate_id]->taxes as $key => $tax){
if( $rates[$rate_id]->taxes[$key] > 0 ){ // set the new tax cost
$taxes[$key] = number_format( $rates[$rate_id]->taxes[$key] * $cost, 2 );
$has_taxes = true;
} else {
$has_taxes = false;
}
}
if( $has_taxes )
$rates[$rate_id]->taxes = $taxes;
}
}
return $rates;
}

Not displayed in the article list until you click "Update" on the dashboard

I am challenging Ajax implementation when replying by "BBPress".
However, reply posted in this manner is displayed in the dashboard, but it is not displayed in the loop of the replies list.
This will be displayed in the loop of the replies list only when you click "Update" on the dashboard.
I want to know the code that displays correctly in the loop.
This is my code:
my-reply.js
"use strict";
(function($){
$(document).on("click","#bbp_reply_submit", function() {
// get
var inputForum = '56'; //There is only one forum.
var inputTopic = $('#bbp_topic_id').val();
var inputTitle = $('#bbp-reply-form-info').text();
var inputContent = $('#bbp_reply_input').val();
var inputParent = $('#bbp_reply_to').val();
var inputIp = $('#my_reply_ip').val();
// Ajax
$.ajax({
url: MY_AJAX.api,
type: 'POST',
data: {
// action name
action: MY_AJAX.action,
// nonce
nonce: MY_AJAX.nonce,
// submit data
submitForum: inputForum,
submitTopic: inputTopic,
submitTitle: inputTitle,
submitContent: inputContent,
submitParent: inputParent,
submitIp: inputIp,
}
})
// scusess
.done(function( response ) {
alert('success'); // Actually, I will display reply instead of alerts.
})
// error
.fail(function( jqXHR, textStatus, errorThrown ) {
alert('error');
});
});
})(jQuery);
functions.php
// nonce
function my_enqueue_scripts() {
$handle = 'my-script';
$jsFile = 'path/to/myscript.js';
wp_register_script($handle, $jsFile, ['jquery']);
$acrion = 'my-ajax-action';
wp_localize_script($handle, 'MY_AJAX', [
'api' => admin_url( 'admin-ajax.php' ),
'action' => $acrion,
'nonce' => wp_create_nonce( $acrion ),
]);
wp_enqueue_script($handle);
}
add_action( 'wp_enqueue_scripts', 'my_enqueue_scripts' );
// post reply
function my_ajax_event() {
$action = 'my-ajax-action';
if( check_ajax_referer($action, 'nonce', false) ) {
$submitForum = esc_html( $_POST['submitForum'] );
$submitTopic = esc_html( $_POST['submitTopic'] );
$submitTitle = esc_html( $_POST['submitTitle'] );
$submitContent = esc_html( $_POST['submitContent'] );
$submitParent = esc_html( $_POST['submitParent'] );
$submitIp = esc_html( $_POST['submitIp'] );
$submitTopicslug = esc_html( $_POST['submitTopicslug'] );
$page = get_post( $submitTopic );
$slug = $page->post_name;
$date = 'Y-m-d H:i:s';
$my_post = array(
'post_title' => (string)wp_strip_all_tags($_POST['submitTitle']),
'post_content' => (string)$_POST['submitContent'],
'post_status' => 'publish',
'post_author' => get_current_user_id(),
'post_type' => 'reply',
'meta_input' => array(
'_bbp_forum_id' => $_POST['submitForum'],
'_bbp_topic_id' => $_POST['submitTopic'],
'_bbp_reply_to' => $_POST['submitParent'],
'_bbp_author_ip' => $_POST['submitIp'],
'_edit_last' => get_current_user_id(),
'_bbp_topic_sort_desc' => 'dft',
'_bbp_sort_desc' => 'dft',
'_bbp_topic_sort_show_lead_topic' => 'dft',
'_bbp_topic_sort_show_lead_topic_forum' => 'dft',
'_wp_old_slug' => $slug,
'_bbp_last_active_time' => $date,
'_bbp_reply_count' => '',
'_bbp_engagement' => '',
'_bbp_reply_count_hidden' => '',
'_bbp_voice_count' => '',
)
);
wp_insert_post( $my_post );
} else {
status_header( '403' );
}
die();
}
add_action( 'wp_ajax_my-ajax-action', 'my_ajax_event' );
add_action( 'wp_ajax_nopriv_my-ajax-action', 'my_ajax_event' );

Woocommerce not list orders all orders, why?

My woocommerce are not listing orders with status 'wc-expired'. I tried adding the 'wc_order_statuses' filter, but it still does not work.
add_filter('wc_order_statuses', function ($order_statuses){
$order_statuses['wc-expired'] = _x( 'Expired', 'Order status', 'woocommerce' );
return $order_statuses;
});
Row in Table wp_posts
The Orders List in Admin
Create new order status. Sample:
function register_expired_order_status() {
register_post_status( 'wc-expired', array(
'label' => 'Expired',
'public' => true,
'exclude_from_search' => false,
'show_in_admin_all_list' => true,
'show_in_admin_status_list' => true,
'label_count' => _n_noop( 'Expired <span class="count">(%s)</span>', 'Expired <span class="count">(%s)</span>' )
) );
}
add_action( 'init', 'register_expired_order_status' );
function add_expired_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-expired'] = 'Expired';
}
}
return $new_order_statuses;
}
add_filter( 'wc_order_statuses', 'add_expired_to_order_statuses' );

WooCommerce Custom Payment Gateway

I am trying to make a Custom Gateway Plugin for my Merchant Account but I got stuck and I don't know how to continue.
Now, here is what I done so far:
<?php
/*
Plugin Name: Paysecure.ro Payment Gateway
Plugin URI: http://www.Paysecure.ro
Description: Allows you to use Paysecure.ro Payment Gateway with the WooCommerce plugin.
Version: 0.0.1
Author: Andrei Raileanu
*/
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
add_action('plugins_loaded', 'woocommerce_Paysecure', 0);
function woocommerce_Paysecure(){
if (!class_exists('WC_Payment_Gateway'))
return; // if the WC payment gateway class is not available, do nothing
if(class_exists('WC_Paysecure'))
return;
class WC_Gateway_Paysecure extends WC_Payment_Gateway{
public function __construct(){
$plugin_dir = plugin_dir_url(__FILE__);
global $woocommerce;
$this->id = 'Paysecure';
$this->icon = apply_filters('woocommerce_Paysecure_icon', ''.$plugin_dir.'Paysecure.png');
$this->has_fields = true;
// Load the settings
$this->init_form_fields();
$this->init_settings();
// Define user set variables
$this->title = "Credit/Debit Card";
$this->description = "You will be redirected to paysecure.ro to complete your purchase.";
$this->cui = "XXXXXXXXX";
$this->encryption_key = "XXXXXXXXX";
$this->currency = "USD";
// Logs
if ($this->debug == 'yes'){
$this->log = $woocommerce->logger();
}
// Actions
add_action('woocommerce_receipt_' . $this->id, array($this, 'receipt_page'));
// Save options
add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) );
// Payment listener/API hook
add_action('woocommerce_api_wc_' . $this->id, array($this, 'check_ipn_response'));
}
function init_form_fields()
{
$this->form_fields = array(
'enabled' => array(
'title' => __( 'Enable/Disable', 'woocommerce' ),
'type' => 'checkbox',
'label' => __( 'Enable Paysecure', 'woocommerce' ),
'default' => 'yes'
)
);
}
public function admin_options() {
?>
<h3><?php _e( 'Paysecure', 'woocommerce' ); ?></h3>
<p><?php _e( 'Paysecure Payment Gateway', 'woocommerce' ); ?></p>
<table class="form-table">
<?php $this->generate_settings_html(); ?>
</table>
<?php
}
function payment_fields() {
$plugin_dir = plugin_dir_url(__FILE__);
// Description of payment method from settings
if ($this->description) { ?>
<p><?php
echo $this->description; ?>
</p><?php
} ?>
<?php
}
function process_payment( $order_id ) {
global $woocommerce;
$order = new WC_Order($order_id);
// I WILL NEED THESE FIELDS
//$this->notify_url;
//$order->get_total();
//$order->get_order_number();
//$order->billing_first_name;
//$order->billing_email;
}
}
function add_Paysecure_gateway($methods){
$methods[] = 'WC_Gateway_Paysecure';
return $methods;
}
add_filter('woocommerce_payment_gateways', 'add_Paysecure_gateway');
}
Here are the PHP instructions from my merchant account provider:
<?php
require_once('./functions.php');
$key = 'THIS IS THE ENCRYPTION KEY';
$data = array( 'cui' => 'THIS IS THE CUI CODE',
'AMOUNT' => '200',
'CURRENCY' => 'USD',
'ORDER' => '12313',
'DESC' => ps_clean('SHORT DESCRIPTION'),
'PENTRU' => 'EMAIL ADDRESS',
'TRTYPE' => 0,
'BACKREF' => 'http://www.site.ro/test.php',
'TIMESTAMP'=>time()
);
echo '<form action="https://paysecure.ro/order/cgi-bin/" method="post" >';
foreach ($data as $l => $v ) echo '<input size="55" readonly type="text" name="'.$l.'" value="'.$v.'" /> : <label for="'.$l.'">'.$l.'</label><br>';
echo '<input size="55" type="text" name="P_SIGN" readonly value="'.calculateSign($data,$key).'" /><br>' ; //se calculeaza P_SIGN - ul , encriptarea datelor
?>
<input type="submit" />
</form>
Can someone help me with the rest of the code?
1st mistake I noticed you made, $this->id MUST be in lowercase. 'Paysecure' is not gonna work here come time for the API hook.
// Payment listener/API hook
add_action('woocommerce_api_wc_' . $this->id, array($this, 'check_ipn_response'));
change to this instead:
// Payment listener/API hook
add_action('woocommerce_api_wc_paysecure', array($this, 'check_ipn_response'));
2nd mistake is that you forgot to create the function check_ipn_response()
// Handles the callbacks received from the payment backend. give this url to your payment processing comapny as the ipn response URL:
// USAGE: http://myurl.com/?wc-api=WC_Gateway_Paysecure
function check_ipn_response() {
$http_contents = file_get_contents("php://input");
$json = json_decode($http_contents, true);
$order = new WC_Order($json['custom']);
if ($callback_json['status'] == 'Transaction approved')
{
$order->payment_complete(); //This will ensure stock reductions are made, and the status is changed to the correct value.
$order->add_order_note( __( 'KiwiPay Transaction Approved.', 'kiwipay' ) );
}
else
{
$order->update_status('failed');
$order->add_order_note('KiwiPay status received - ' . $callback_json['status']);
}
//references:
//http://docs.woothemes.com/document/payment-gateway-api/
//https://github.com/Paymium/WooCommerce/blob/master/checkout.php
//https://github.com/tubiz/voguepay-woocommerce-payment-gateway/blob/master/voguepay-woocommerce-payment-gateway.php
/*
{
"id":1863,
"amount":1750,
"status":"Transaction approved",
"created":1434198776,
"reference":"2626", //this is the order number $order->get_order_number()
"name":"HamishTest Test",
"email":"hamish#tst.xom",
"address":{"street":"my rd","region":"N/A","city":"tauranga","zip":"3175","country":"NZ"},
"test":true,
"price":"17.50",
"custom":"6589" //this is the wc order_id passed during process_payment to the paymen processor.
}
*/
How about this?
add_action( 'plugins_loaded', 'init_gateway_cash' );
function init_gateway_cash() {
class WC_Gateway_Cash extends WC_Payment_Gateway {
function __construct() {
$this->id = "Cash Gateway";
$this->title = "Cash";
$this->description = "More later";
$this->init_form_fields();
$this->init_settings();
add_action( 'woocommerce_update_options_payment_gateways', array( &$this, 'process_admin_options' ) );
}
function init_form_fields(){
$this->form_fields = array(
'enabled' => array(
'title' => __( 'Enable/Disable', 'woocommerce' ),
'type' => 'checkbox',
'label' => __( 'Enable Cheque Payment', 'woocommerce' ),
'default' => 'yes'
),
'title' => array(
'title' => __( 'Title', 'woocommerce' ),
'type' => 'text',
'description' => __( 'This controls the title which the user sees during checkout.', 'woocommerce' ),
'default' => __( 'Cheque Payment', 'woocommerce' ),
'desc_tip' => true,
),
'description' => array(
'title' => __( 'Customer Message', 'woocommerce' ),
'type' => 'textarea',
'default' => ''
)
);
}
function process_payment( $order_id ) {
global $woocommerce;
$order = new WC_Order( $order_id );
$productArray = array();
$x = 0;
foreach( $order->get_items() as $item_id => $item ) {
$productArray[$x] = $order->get_product_from_item( $item );
$x++;
}
// Mark as on-hold (we're awaiting the cheque)
$order->update_status('on-hold',
__( 'Awaiting cheque payment.', 'woocommerce' )
);
// Remove cart
$woocommerce->cart->empty_cart();
// Return thankyou redirect
return array(
'result' => 'success',
'redirect' => $this->get_return_url( $order )
);
}
}
}
function add_gateway_cash_class ($methods ) {
$methods[] = 'WC_Gateway_Cash';
return $methods;
}
add_filter( 'woocommerce_payment_gateways', 'add_gateway_cash_class' );

Resources