So I have been working on a project to integrate custom SMS API with woocommerce and wc vendor plugins. Unfortunately, I didn't find any particular solution for this. Everyone was talking about some plugins who actually support existing gateways. I was wondering what if someone wants to integrate own api with woocommerce!
Finally, I have come up with own code which is given below. The code goes to function.php in your child theme. FYKI, I had to use rawurlencode to encode the text message as some telcos require encoded message.
Thank you.
Special thanks to: Integrating SMS api with woocommerce , Not sending messages
//DYNAMIC ORDER MSG TO CUSTOMER
add_action('woocommerce_order_status_processing', 'custom_msg_customer_process_order', 10, 3);
function custom_msg_customer_process_order ($order_id) {
//Lets get data about the order made
$order = new WC_Order($order_id);
//Now will fetch billing phone
$billing_phone = $order->get_billing_phone();
$billing_name = $order->get_billing_first_name();
$textmessage = rawurlencode("Dear $billing_name, Thank you for your order. Your order #$order_id is being processed. Please wait for confirmation call.");
// Now put HTTP SMS API URL
$url = "http://msms.THE_COMPANY.com/RequestSMS.php?user_name=YOUR_USER_NAME&pass_word=YOUR_PASSWORD&brand=YOUR_BRAND_NAME&type=1&destination=$billing_phone&sms=$textmessage";
// NOW WILL CALL FUNCTION CURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
$err = curl_error($ch);
curl_close($ch);
return $order_id;
}
I recently had this challenge myself, I had found an easy way to send notification SMS messages from WooCommerce with a plugin but I needed something to send messages in my own way.
I ended up using the Twilio service along with their API, I wrote up this tutorial as to how you can get it all set up so hope it helps!
function wpcodetips_send_sms( $smsMessage , $contactNumber ){
// Change to your account SID
$accountSID = 'XXXXXXXXXXXXX';
// Change to your account Auth Key
$authKey = 'XXXXXXXXXXXXX';
// Change to your account trial number
$sendNumber = '+XXXXXXXXXXX';
// The Twilio API Url
$url = "https://api.twilio.com/2010-04-01/Accounts/".$accountSID."/Messages.json";
// The data being sent to the API
$data = array(
'From' => $sendNumber,
'To' => $contactNumber,
'Body' => $smsMessage
);
// Set the authorisation header
$headers = array( 'Authorization' => 'Basic ' . base64_encode($accountSID . ':' . $authKey));
// Send the POST request and store the response in a variable
$result = wp_remote_post($url, array( 'body' => $data, 'headers' => $headers));
// Return the response body to ensure it has worked
return json_decode($result['body'], true);
}
https://www.wpcodetips.com/wordpress-tutorials/how-to-send-an-sms-from-wordpress-programmatically/
Not sure if this helps anyone but I recently set up a woocommerce shop where the owners are not able to check their email for orders all day as they are out on the field.
So with the mix of Hasan's and Gary's post right here I consolidated them into one to make a notification over SMS using Twilio when a new order comes in.
Just add the below to your functions.php and replace the accountSID, authKey, SendNumber and contactNumber values. And of course change the message to your preference.
Tested it with special characters like ÅÄÖ as well and it worked.
//Send SMS Notification to admin
add_action('woocommerce_order_status_processing', 'send_woo_order_sms', 10, 3);
function send_woo_order_sms ($order_id){
//Get order data
$order = new WC_Order($order_id);
//Get first name from order
$billing_first_name = $order->get_billing_first_name();
//Get last name from order
$billing_last_name = $order->get_billing_last_name();
// Change to your Twilio account SID
$accountSID = 'xxxxxxxxxxxxxxxx';
// Change to your Twilio account Auth Key
$authKey = 'xxxxxxxxxxxxxxxx';
// Change to your Twilio account number
$sendNumber = '+xxxxxxxxxxxxxxxx';
//Change to your verified caller number (receiver of the sms)
$contactNumber = '+xxxxxxxxxxxxxxxx';
//Message to send
$smsMessage = "$billing_first_name $billing_last_name has just placed an order. See order #$order_id.";
// The Twilio API Url
$url = "https://api.twilio.com/2010-04-01/Accounts/".$accountSID."/Messages.json";
// The data being sent to the API
$data = array(
'From' => $sendNumber,
'To' => $contactNumber,
'Body' => $smsMessage
);
// Set the authorisation header
$headers = array( 'Authorization' => 'Basic ' . base64_encode($accountSID . ':' . $authKey));
// Send the POST request and store the response in a variable
$result = wp_remote_post($url, array( 'body' => $data, 'headers' => $headers));
return $order_id;
}
I guess it could easily be changed to be sent out to the customer instead by changing the contactNumber to the billing phone.
$contactNumber = $order->get_billing_phone();
This would however require a paid plan at Twilio.
Ufone pakistan sms integration with woocommerce wordpress
if you are looking for integration with ufone pakistan sms api bsms ufone pakistan service provider with woocommerce wordpress then use the following code in your functions file
sms api integration ufone bsms with wordpress woocommerce
thanks to the author on this page
Integrating custom SMS API with woocommerce
//add this line for calling your function on creation of order in woocommerce
add_action('woocommerce_order_status_processing', 'custom_func', 10, 3);
function custom_func ($order_id) {
$order_details = new WC_Order($order_id);
//fetch all required fields
$billing_phone = $order_details->get_billing_phone();
$billing_name = $order_details->get_billing_first_name();
$billing_last_name = $order_details->get_billing_last_name();
$total_bill = $order_details->get_total();
$textmessage = rawurlencode("Dear $billing_name, Thank you for your order. Your order #$order_id is being processed. Please wait for confirmation call Total Bill = $total_bill");
// Now put HTTP ufone BSMS API URL
$url = "https://bsms.ufone.com/bsms_v8_api/sendapi-0.3.jsp?id=msisdn&message=$textmessage&shortcode=SHORTCODE&lang=English&mobilenum=$billing_phone&password=password&messagetype=Nontransactional";
// NOW WILL CALL FUNCTION CURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
$err = curl_error($ch);
curl_close($ch);
return $order_id;
}
Related
I am using the following API code to send an SMS when a new order is placed, the SMS API code is working to send SMS... Placed at the end of child theme in functions.php file... all is updated(WordPress 5.9.3 and woo-commerce 6.4 with PHP 8.0)
2 Issues:
The $order_id and $order_date do not populate in the given variables and the SMS is received as is with the 2 variables.
When the order is placed by a customer this code is triggered and SMS is received even when the payment is not made and the order status in the backend is showing pending payment.
Tried the following:
For the 1st issue I changed the message variable to '$order_id' or '.$order_id.' but it did not work and wp crashed so had to keep plain $order_id...
For the 2nd issue, I changed the hook to 'woocommerce_order_status_processing' but this code does not work for a new order.
Documentation: https://www.textlocal.in/free-developer-sms-api/
Any suggestions to tweak the code so both the problems are solved?
Thanks
// Sending SMS to customers on new orders
add_action('woocommerce_new_order', 'custom_msg_customer_process_order', 10, 3);
function custom_msg_customer_process_order ($order_id) {
$order = new WC_Order( $order_id );
$order_date = $order->get_date_created();
$billing_phone = $order->get_billing_phone();
$apiKey = urlencode('apikey');
// Message details
$numbers = array($billing_phone,91xxxxxxxxxx);
$sender = urlencode('TXTCL');
$message = rawurlencode('Thank you for buying from us, a Wellness product. Your order number $order_id Dated $order_date is confirmed.');
$numbers = implode(',', $numbers);
// Prepare data for POST request
$data = array('apikey' => $apiKey, 'numbers' => $numbers, "sender" => $sender, "message" => $message);
// Send the POST request with cURL
$ch = curl_init('https://api.textlocal.in/send/');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
// Process your response here
echo $response;
}
While I don't know much about the texting API (and I sure hope your customers are opting in to text updates!), what I think is happening is that new WC_Order never reads your data from the database. How you should get a new order object is wc_get_order(). However, the woocommerce_new_order hook passes along the $order object as the 2nd parameter
So if we make sure our callback is expecting a second parameter there's no need to re-instantiate the order object.
As for part 2, woocommerce_new_order will fire when the order is saved to the DB and it doesn't matter what the order status is. Instead, I think we can use woocommerce_order_status_pending_to_processing which is what the new order email uses.
/**
* Sending SMS to customers on new orders.
*
* #param int $order_id The order ID. *
* #param WC_Order $order Order object.
*/
function custom_msg_customer_process_order( $order_id, $order ) {
$order_date = $order->get_date_created();
$billing_phone = $order->get_billing_phone();
$apiKey = urlencode('apikey');
// Message details
$numbers = array($billing_phone,91xxxxxxxxxx);
$sender = urlencode('TXTCL');
// Use sprintf() to replace placeholders with values.
$message = rawurlencode( sprintf( 'Thank you for buying from us, a Wellness product. Your order number %s Dated %s is confirmed.', $order_id, $order_date ) );
$numbers = implode(',', $numbers);
// Prepare data for POST request
$data = array('apikey' => $apiKey, 'numbers' => $numbers, "sender" => $sender, "message" => $message);
// Send the POST request with cURL
$ch = curl_init('https://api.textlocal.in/send/');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
// Process your response here
echo $response;
}
add_action('woocommerce_order_status_pending_to_processing', 'custom_msg_customer_process_order', 10, 2 );
Alternative
The above depends on your gateway setting the order to processing. If it does not (or if it wasn't initially pending) then it may not fire... since it only fires on the transition from pending to processing. A better hook might actually be woocommerce_payment_complete. But note that in source, it only passes 1 parameter to its callbacks... the $order_id (similar to the woocommerce_thankyou hook does). Therefore the code snippet would need to be adjusted to expect only a single parameter:
/**
* Sending SMS to customers on new orders.
*
* #param int $order_id The order ID. *
*/
function custom_msg_customer_process_order( $order_id ) {
$order = wc_get_order( $order_id );
// Quit early if not a valid order.
if ( ! $order ) {
return;
}
$order_date = wc_format_datetime( $order->get_date_created() );
$billing_phone = $order->get_billing_phone();
$apiKey = urlencode('apikey');
// Message details
$numbers = array($billing_phone,91xxxxxxxxxx);
$sender = urlencode('TXTCL');
// Use sprintf() to replace placeholders with values.
$message = rawurlencode( sprintf( 'Thank you for buying from us, a Wellness product. Your order number %s Dated %s is confirmed.', $order_id, $order_date ) ) );
$numbers = implode(',', $numbers);
// Prepare data for POST request
$data = array('apikey' => $apiKey, 'numbers' => $numbers, "sender" => $sender, "message" => $message);
// Send the POST request with cURL
$ch = curl_init('https://api.textlocal.in/send/');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
// Process your response here
echo $response;
}
add_action('woocommerce_payment_complete', 'custom_msg_customer_process_order' );
I want to send FCM push notifications in specific android users only using their token saved in mysql database as identification. here's my current progress
PHP Script Snippet Code: Report_Status.php (File 1)
//Gets the token of every user and sends it to Push_User_Notification.php
while ($User_Row = mysqli_fetch_array($Retrieve_User, MYSQLI_ASSOC)){
$User_Token = $User_Row['User_Token'];
include "../Android_Scripts/Notifications/Push_User_Notification.php";
$message = "Your Report has been approved! Please wait for the fire fighters to respond!";
send_notification($User_Token, $message);
}
PHP code for File 2: Push_User_Notification.php
<?php //Send FCM push notifications process
include_once("../../System_Connector.php");
function send_notification ($tokens, $message)
{
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = array(
'registration_ids' => $tokens,
'data' => $message
);
$headers = array(
'Authorization:key = API_ACCESS_KEY',
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
curl_close($ch);
}
?>
Problem:
The page is always stuck in Report_Status.php every time I ran the
script. It is supposed to go in Push_User_Notification and return to Report_Status once the process is done. Am I wrong in the implementation of calling the
Push_User_Notification.php or the receiving parameters to
Push_User_Notification.php?
P.S.
Here's my full source code of Report_Status.php in case anyone wants to check it: Report_Status.php
I think the problem you may be having is that you are sending a lot of notifications to several devices in short amount of time. I think it might be being picked up as spaming. My suggestion is sending one notification to multiple devices.
Try changing your code in report_status.php to this.
include "../Android_Scripts/Notifications/Push_User_Notification.php";
$message = "Your Report has been approved! Please wait for the fire fighters to respond!";
while ($User_Row = mysqli_fetch_array($Retrieve_User, MYSQLI_ASSOC)){
$User_Token[] = $User_Row['User_Token'];
}
$tokens = implode(",", $User_Token);
send_notification($tokens, $message);
the idea is that you will collect the user tokens in $User_Token[] array. Then you would comma seperate the tokens and send the message once to all the devices that associate to the tokens. FCM allows you to send to multiple tokens in one go.
updated
$User_Token needs to be an array. so remove the implode. That was my mistake.
Secondly the $message needs to be in the following format.
$message = array(
'title' => 'This is a title.',
'body' => 'Here is a message.'
);
Also another thing to note is that there are 2 types of messages you can send using FCM. Notification Messages or Data Messages. Read more here: https://firebase.google.com/docs/cloud-messaging/concept-options
I dont know if your app is handling the receipt of messages (i dont know if you have implemented onMessageRecieve method) so i would probably suggest making a small change to the $fields array in send_notification function. Adding the notification field allows android to handle notifications automatically if your app is in the background. So make sure you app is in the background when testing. https://firebase.google.com/docs/cloud-messaging/android/receive
$fields = array(
'registration_ids' => $tokens,
'data' => $message,
'notification' => $message
);
So try the code below. I have tried and tested. It works for me. If it does not work. In send_notification function echo $result to get the error message. echo $result = curl_exec($ch); Then we can work from there to see what is wrong. You can see what the errors mean here: https://firebase.google.com/docs/cloud-messaging/http-server-ref#error-codes
include "../Android_Scripts/Notifications/Push_User_Notification.php";
$message = array(
'title' => 'Report Approved',
'body' => 'Your Report has been approved! Please wait for the fire fighters to respond!'
);
while ($User_Row = mysqli_fetch_array($Retrieve_User, MYSQLI_ASSOC)){
$User_Token[] = $User_Row['User_Token'];
}
send_notification($User_Token, $message);
I am integrating SMS gateway for the very first time. I want to send sms when someone pays to the website. I am using the following code:
<?php
$pay="1000";
$msg="Arivind";
echo $url="http://yourdomainname.com/api/swsend.asp?username=xxxxxx&password=xxxxxx&sender=SENDERID&sendto=91XXXXXXXXX&message=Dear'$msg' Thanks for making payment of Rs '$pay'";
$c=curl_init();
curl_setopt($c,CURLOPT_RETURNTRANSFER,1);
curl_setopt($c,CURLOPT_URL,$url);
$contents=curl_exec($c);
curl_close($c);
echo "SMS Successfully sent";
?>
Now if i am using variable in body of message, the message is not sent but if i use static message the message is getting delivered to the number.
The static message doesnt solve my purpose as i need the message to be sent to different person, the variable used ie $msg will have different name of people & fetched from database.
KINDLY SUGGEST.
Using variables between single quotes ' does not convert it into dynamic values. Also its better to RestApi in simple PHP function:
function CURLcall($number, $message_body){
$api_params = "swsend.asp?username=xxxxxx&password=xxxxxx&sender=SENDERID&sendto=91XXXXXXXXX&message=$message_body";
$smsGatewayUrl = "echo $url="http://yourdomainname.com/api/";
$smsgatewaydata = $smsGatewayUrl.$api_params;
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_URL, smsgatewaydata);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
// Use file get contents when CURL is not installed on server.
if(!$output){
$output = file_get_contents($smsgatewaydata);
}
}
Call above function as:
$message_body = urlencode("Dear $msg Thanks for making payment of Rs $pay");
CURLcall('918954xxxxx',$message_body);
Please note: urlencode is useful to avoid errors in GET method as it convert space into encoded format http://php.net/manual/en/function.urlencode.php
You can also use http_build_query to convert your variables into a nicely formatted URL.
<?php
$fname = 'Matthew';
$lname = 'Douglas';
$amount = 1000;
$message = "Thanks for your payment of Rs {$amount}.";
$urlComponents = array(
'firstName' => $fname,
'lastName' => $lname,
'message' => $message
);
$url = 'http://yourdomainname.com/api/swsend.asp?';
echo $url . http_build_query($urlComponents);
?>
I have a codeigniter base website and I have tried making forgot password by Phone and Email using Codeigniter framework to change password notification.And email is already working but I don't know how to send message to phone using codeigniter??
And one of my friends told me that use Curl function to send message to phone.But I didn't have any prior idea about CURL function so I searched on google but I couldn't figure out how to do this.
Would you please give me proper suggestion about how to send message to phone using codeigniter.
Any kind of help would be highly appreciated.
Thanks in advance.
Here is a simple code-igniter helper which you need to save as helpers/sendsms_helper.php
function sendsms($number, $message_body, $return = '0') {
$sender = 'SEDEMO'; // Can be customized
$smsGatewayUrl = 'http://springedge.com';
$apikey = '62q3xxxxxxxxxxxxxxxxxxxxxx'; // Need to change
$textmessage = urlencode($textmessage);
$api_element = '/api/web/send/';
$api_params = $api_element.'?apikey='.$apikey.'&sender='.$sender.'&to='.$number.'&message='.$textmessage;
$smsgatewaydata = $smsGatewayUrl.$api_params;
$url = $smsgatewaydata;
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $output = curl_exec($ch);
curl_close($ch);
if(!$output){ $output = file_get_contents($smsgatewaydata); }
if($return == '1'){ return $output; }else{ echo "Sent"; }
}
How to use:
You can use below function anywhere in project to send sms:
Call sendsms function Ex. sendsms( '919918xxxxxx', 'test message' );
Please make sure to Load sendsms helper as $this->load->helper('sendsms_helper');
There are many companies that provide api for the same. I have used twilio for some time and find it reliable. The code for same can be
<?php
require "Services/Twilio.php";
$AccountSid = ""; //get from twilio
$AuthToken = ""; //get from twilio
$client = new Services_Twilio($AccountSid, $AuthToken);
$sms = $client->account->messages->sendMessage(
$tNumber, // Your twilio number
$number, // Number you want to send to
$message // Message you want to sms
);
Hope this helps. Again there are many other services out there also that you can look into
MY SMS CODE: I have purchased the sms gate from third party.I am having some issue with that when I integrate in my website. I have listed my issue.can anyone guide me what I have to do further?Read my question?
<?php
$ID = 'xxxxxx';
$Pwd = 'xxxxx';
$PhNo = '1234567890,123456789';
$Text = 'welcome to US';
$url="http://t.dialmenow.info/sendsms.jsp?user=$ID&password=$Pwd&mobiles=$PhNo&sms=$Text&senderid =";
//echo $url;
$ret = file($url);
//echo $ret;
echo $ret[9];
?>
**I have problem with my message and delivery report.**
1.If you see the $Text variable $Text=welcome to US if I give space after first word the message is not coming to my mobile.
2.In api documentation they have given how to check delivery status. Here is the api delivery status code.they have given sample code. I want to know how to write the sample delivery status code for above php code.
http://t.dialmenow.info/getDLR.jsp?userid=username&password=password&messageid=1,2&externalid=1,2 &drquantity=X&fromdate=yyyy-mm-dd hh:mm:ss&todate=yyyy-mm-ddhh:mm:ss&redownload=yes&responcetype=xml
Explanation:
messageid=>When you send a message you will get an unique message id from API and you have to use this
messageid=>for getting the deliver status for that message.
externalid=>unique sms serial no which you will get in response.
Drquantity=>it means how many delivery status you want from Dialmenow application
Try encoding your message using the below
$msg = urlencode($Text)
Havent used file() but you could try implementing via cURL. Pls ensure that cURL in installed in the server where the code will be executed.
$ID = 'xxxxxx';
$Pwd = 'xxxxx';
$PhNo = '1234567890,123456789';
$Text = 'welcome to US';
$msg=urlencode($Text);
$url="http://t.dialmenow.info/sendsms.jsp?user=$ID&password=$Pwd&mobiles=$PhNo&sms=$msg&senderid=";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER ,true);
$result = curl_exec($ch);
curl_close($ch);