Order status still “Pending Payment” after successful payment (Custom payment gateway) - wordpress

I was develop a custom payment gateway for woocommerce, everything is good but after payment success the order still "pending payment"
In the __construct() function I check for payment provider respond
<?php
//when payment done and redirected with payment reference code
if(isset($_REQUEST['transaction_id'])){
paytabs_set_cookie('transaction_id', $_REQUEST['transaction_id']);
$order = new WC_Order($order_id);
$this->order = $order;
$this->complete_transaction($order->get_id(), $_REQUEST['transaction_id']);
}
and here is the complete_transaction() function
<?php
/*
When transaction completed it is check the status
is transaction completed or rejected
*/
function complete_transaction($order_id, $transaction_id) {
global $woocommerce;
$order = new WC_Order( $order_id );
$request_string=array(
'secret_key' => $_COOKIE['secret_key'],
'merchant_email' => $_COOKIE['merchant_email'],
'transaction_id' => $transaction_id,
'order_id' => $order_id
);
$gateway_url=$this->liveurl.'apiv2/verify_payment_transaction';
$getdataresponse=$this->sendRequest($gateway_url, $request_string);
$object=json_decode($getdataresponse, true);
if (isset($object->response_code)) {
//if get response successfull
if($object->response_code == '100'){
// thankyou and set error message
$this->msg['class'] = 'woocommerce_message';
$check=$order->payment_complete();
// Reduce stock levels
$order->reduce_order_stock();
// Remove cart
$woocommerce->cart->empty_cart();
wc_add_notice( '' . __( 'Thank you for shopping with us. Your account has been charged and your transaction is successful.
We will be shipping your order to you soon.', 'woocommerce' ), 'success' );
wp_redirect( $this->get_checkout_order_received_url( $order ) );
exit;
}else{
// Change the status to pending / unpaid
$order->update_status('failed', __('Payment Cancelled', 'error'));
// Add error for the customer when we return back to the cart
$message=$object->result;
wc_add_notice( '<strong></strong> ' . __($message, 'error' ), 'error' );
// Redirect back to the last step in the checkout process
wp_redirect( $this->get_cancel_order_url( $order ) );
exit;
}
}
}
But the order status still "pending payment".
now I need to change the order status to "Completed" after check the payment provider respond.

Fixed
The problem because of this line
wp_redirect( $this->get_checkout_order_received_url( $order ) );
it must be $order instead of $this so the line is like this
wp_redirect( $order->get_checkout_order_received_url( $order ) );

Related

Redirecting customers to custom page after sale in WooCommerce

I'm trying to learn WooCommerce and WordPress plugins so I'm tweaking around. I'm trying to create a plugin that redirects customer to a custom page after checkout. The custom page/url can be defined when I create the product. Here is my code:
<?php
/*
Plugin Name: Custom Redirect After Sale
Description: Redirects customers to a custom page after a successful sale.
*/
// Register a new meta field for products
add_action( 'add_meta_boxes', 'custom_redirect_meta_box' );
function custom_redirect_meta_box() {
add_meta_box( 'custom_redirect_meta_box', 'Custom Redirect URL', 'custom_redirect_meta_box_callback', 'product', 'side' );
}
function custom_redirect_meta_box_callback( $post ) {
$value = get_post_meta( $post->ID, '_custom_redirect_url', true );
echo '<label for="custom_redirect_url">Custom Redirect URL:</label>';
echo '<input type="text" id="custom_redirect_url" name="custom_redirect_url" value="' . esc_attr( $value ) . '" style="width:100%">';
}
// Save the meta field value when the product is saved
add_action( 'save_post_product', 'save_custom_redirect_meta_box_data' );
function save_custom_redirect_meta_box_data( $post_id ) {
if ( isset( $_POST['custom_redirect_url'] ) ) {
update_post_meta( $post_id, '_custom_redirect_url', sanitize_text_field( $_POST['custom_redirect_url'] ) );
}
}
// Redirect to the custom page after a successful sale
add_action( 'woocommerce_payment_complete', 'custom_redirect_after_sale' );
function custom_redirect_after_sale( $order_id ) {
$order = wc_get_order( $order_id );
//$order->update_status( 'completed' );
$items = $order->get_items();
// Get the first product in the order
$product = reset($items);
// Get the custom redirect URL for the product
//$redirect_url = get_post_meta( $product->get_product_id(), '_custom_redirect_url', true );
$redirect_url = get_post_meta( $product->get_id(), '_custom_redirect_url', true );
//echo "Meta retrieved: " . $redirect_url;
//error_log("callback fired");
//echo "Payment complete ho ho ho";
if( $redirect_url ) {
wp_redirect( $redirect_url );
exit;
}
}
It seems the woocommerce_payment_complete hook is not firing. I tried to echo out the redirect url and text but it doesn't seem to work.
I'm on localhost and I'm using the cash on delivery payment method.
Basing this answer on the great https://rudrastyh.com/ - specifically this tutorial https://rudrastyh.com/woocommerce/thank-you-page.html#redirects this is the code that should work for what you are trying to do.
First, you hook into the template_redirect action to determine the URL where the customer needs to go
Getting the Order ID, you can get the products purchased for that order
Once you have the purchased products, you can get their ID and meta data, the redirect URL you saved for each. Note that while you use WP functions for handling meta, when working with WooCommerce it is best practice to use its CRUD methods. In case in the future they port products to custom tables, your code will continue working.
Implement the redirect with the WP function wp_safe_redirect
Note that what you are trying to achieve will have problems if customers purchase orders with more than 1 product, and you have more than 1 redirect URL. In this implementation, the first product in the order that has a saved redirect URL will override all others
add_action( 'template_redirect', 'purchased_product_redirect');
function purchased_product_redirect(){
if( !function_exists( 'is_wc_endpoint_url' )){
return;
}
// do nothing if we are not on the order received page
if( ! is_wc_endpoint_url( 'order-received' ) || empty( $_GET[ 'key' ] ) ) {
return;
}
// Get the order ID
$order_id = wc_get_order_id_by_order_key( $_GET[ 'key' ] );
// Get an instance of the WC_Order object
$order = wc_get_order( $order_id );
// Get and Loop Over Order Items
foreach ( $order->get_items() as $item_id => $item ) {
$product_id = $item->get_product_id();
$product = wc_get_product($product_id);
if(!$product){
continue;
}
//Get the first product's redirect URL
$product_redirect_url = $product->get_meta('_custom_redirect_url');
if(!$product_redirect_url){
continue;
}
wp_safe_redirect( $product_redirect_url );
exit; // always exit after using wp_safe_redirect
}
}

Send Email notifications when a user completes a successful order using a certain code l Woocommerce [duplicate]

How to send order notification to a business partner when a specific coupon is used?
I found a solution for the instance when the coupon is applied here :
Send an email notification when a specific coupon code is applied in WooCommerce
However, I need to find a solution for when after order is submitted, because the order is not always submitted after coupon is applied.
Each coupon will have its own email address.
First we add a setting field to admin Coupon pages, to set an email recipient for for a coupon:
// Add a custom field to Admin coupon settings pages
add_action( 'woocommerce_coupon_options', 'add_coupon_text_field', 10 );
function add_coupon_text_field() {
woocommerce_wp_text_input( array(
'id' => 'email_recipient',
'label' => __( 'Email recipient', 'woocommerce' ),
'placeholder' => '',
'description' => __( 'Send an email notification to a defined recipient' ),
'desc_tip' => true, // Or false
) );
}
// Save the custom field value from Admin coupon settings pages
add_action( 'woocommerce_coupon_options_save', 'save_coupon_text_field', 10, 2 );
function save_coupon_text_field( $post_id, $coupon ) {
if( isset( $_POST['email_recipient'] ) ) {
$coupon->update_meta_data( 'email_recipient', sanitize_text_field( $_POST['email_recipient'] ) );
$coupon->save();
}
}
Then email is sent for each applied coupon to a submitted order, if the email recipient has been set for the applied coupon.
Caution! choose only one of the following functions:
For woocommerce versions Up to 4.3 (new hook)
// For Woocommerce version 4.3+
add_action( 'woocommerce_checkout_order_created', 'custom_email_for_orders_with_applied_coupon' );
function custom_email_for_orders_with_applied_coupon( $order ){
$used_coupons = $order->get_used_coupons();
if( ! empty($used_coupons) ){
foreach ( $used_coupons as $coupon_code ) {
$coupon = new WC_Coupon( $coupon_code ); // WC_Coupon Object
$recipient = $coupon->get_meta('email_recipient'); // get recipient
if( ! empty($recipient) ) {
$subject = sprintf( __('Coupon "%s" has been applied'), $coupon_code );
$content = sprintf( __('The coupon code "%s" has been applied by a customer'), $coupon_code );
wp_mail( $recipient, $subject, $content ); // Send email
}
}
}
}
Or for all WooCommerce versions (since version 3.0)
// For all Woocommerce versions (since 3.0)
add_action( 'woocommerce_checkout_update_order_meta', 'custom_email_for_orders_with_applied_coupon' );
function custom_email_for_orders_with_applied_coupon( $order_id ){
$order = wc_get_order( $order_id );
$used_coupons = $order->get_used_coupons();
if( ! empty($used_coupons) ){
foreach ( $used_coupons as $coupon_code ) {
$coupon = new WC_Coupon( $coupon_code ); // WC_Coupon Object
$recipient = $coupon->get_meta('email_recipient'); // get recipient
if( ! empty($recipient) ) {
$subject = sprintf( __('Coupon "%s" has been applied'), $coupon_code );
$content = sprintf( __('The coupon code "%s" has been applied by a customer'), $coupon_code );
wp_mail( $recipient, $subject, $content ); // Send email
}
}
}
}
Code goes in functions.php file of your active child theme (or active theme). Tested and works.

How to link WooCommerce guest orders to customer account after registration

Our scenario is:
The guest user enters the site and places one or more orders without the need to register. And after a while, he decides to register on the site.
Now how to link guest orders to customer account after registeration?
I use the following code, but this code only works for users who have already registered but did not log in at the time of purchase. Any advice?
//assign user in guest order
add_action( 'woocommerce_new_order', 'action_woocommerce_new_order', 10, 1 );
function action_woocommerce_new_order( $order_id ) {
$order = new WC_Order($order_id);
$user = $order->get_user();
if( !$user ){
//guest order
$userdata = get_user_by( 'email', $order->get_billing_email() );
if(isset( $userdata->ID )){
//registered
update_post_meta($order_id, '_customer_user', $userdata->ID );
}else{
//Guest
}
}
}
You can use the woocommerce_created_customer action hook and the wc_update_new_customer_past_orders() function
So you get:
function action_woocommerce_created_customer( $customer_id, $new_customer_data, $password_generated ) {
// Link past orders to this newly created customer
wc_update_new_customer_past_orders( $customer_id );
}
add_action( 'woocommerce_created_customer', 'action_woocommerce_created_customer', 10, 3 );

Update WooCommerce order status via WooCommerce callback

I created a custom payment gateway plugin that caters payment for WooCommerce site orders via a third party payment gateway. Once the third party received the payment of the customer it then sends post data into your designated URL so you can process/update your database. Updating order status on WooCommerce callback via Get method works but not with Post.
This what i am working with
add_action( 'woocommerce_api_callback', array( $this, 'thirdparty_response' ));
function thirdparty_response()
{
global $woocommerce;
if(isset($_POST['order_id']) && isset($_POST['order_status'])) //Parameters sent by third party gateway
{
$order_status = $_POST['order_status'];
$order_id = $_POST['order_id'];
$order = new WC_Order( $order_id );
if ($order_status == "success")
{
$order->update_status('processing', __('Payment Received', 'woothemes'));
}
else
{
$order->update_status('failed', __('Payment Failed', 'woothemes'));
}
}
}
Thank you and I hope you can help me.
Have you created your Gateway class? This is a snippet from WC Paypal Gateway, and to activate the check_response you have to configure your 3rd party Payment Gateway service to callback your URL formed like this (you need to replace the name of your class in both callback URL and in the hook name):
$your_callback = str_replace( 'https:', 'http:', add_query_arg( 'wc-api', 'WC_Gateway_Paypal', home_url( '/' ) ) );
public function __construct( $sandbox = false, $receiver_email = '' ) {
add_action( 'woocommerce_api_wc_gateway_paypal', array( $this, 'check_response' ) );
add_action( 'valid-paypal-standard-ipn-request', array( $this, 'valid_response' ) );
$this->receiver_email = $receiver_email;
$this->sandbox = $sandbox;
}

WooCommerce automatically sending cancelled orders email

I received five cancellation notification emails came, all about the same time, and none of them canceled their orders. I called each and every customer and they all told me that they did not cancel the order. The orders were not actually canceled in Wordpress but for some reason, email notifications for cancellation were sent.
Please help me to resolve this issue.
Thanks!
add_action("woocommerce_order_status_changed", "my_custom_notification");
function my_custom_notification($order_id, $checkout=null) {
global $woocommerce;
$order = new WC_Order( $order_id );
if($order->status === 'cancelled' ) {
// 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 );
}
}
You can set your own notification mail on order get cancelled(order status changing to cancelled)

Resources