I have created a custom payment gaeway where user can place order through whatsapp. When place order is clicked I want to open whatsapp url in the new tab and thank you page in same tab. I am stuck at sending the customer to the whatsapp url and at the same time open thank you page in same tab.
Here is the full code of custom payment gateway:
class WC_Gateway_WhatsApp extends WC_Payment_Gateway
{
public function __construct()
{
//... predefined variables
add_action('woocommerce_update_options_payment_gateways_' . $this->id, array($this, 'process_admin_options'));
}
public function init_form_fields()
{
$this->form_fields = array(
//...fields
);
}
public function payment_fields()
{
$order_id = absint( get_query_var( 'order-pay' ) );
$order = wc_get_order( $order_id );
echo '<p>' . esc_html__($this->description, 'woocommerce') . '</p>';
?>
<script type="text/javascript">
jQuery(document).ready(function($) {
const form = $("form.checkout");
form.submit(function(e) {
if (form.find("input[name='payment_method']:checked").val() === "whatsapp") {
e.preventDefault();
const whatsappUrl = $('#whatsapp-url').data('url');
window.open(whatsappUrl, "_blank");
form.unbind('submit').submit();
}
});
});
</script>
<?php
}
public function process_payment($order_id)
{
$order = wc_get_order($order_id);
$order->set_payment_method($this->id);
$order->save();
$whatsapp_url = $this->generate_whatsapp_message($order);
echo '<input type="hidden" id="whatsapp-url" data-url="' . esc_url($whatsapp_url) . '" />';
return array(
'result' => 'success',
'redirect' => $this->get_return_url($order)
);
}
private function generate_whatsapp_message($order) {
$customer_name = $order->get_billing_first_name() . ' ' . $order->get_billing_last_name();
$whatsapp_message = "Order from " . $customer_name . ":n";
$whatsapp_message .= "Order Id = " . $order_id . "n";
//...other message
$whatsapp_number = $this->number;
$whatsapp_url = 'https://wa.me/' . $whatsapp_number . '?text=' . urlencode($whatsapp_message);
return $whatsapp_url;
}
}