Sending SMS via PHP - php

I am woking on my final year project and I would like to send sms to a client via php.
Is there any way in which I can use my cell phone as a GSM modem and send sms via php?
I tried "Ozeki NG - SMS Gateway" but not sure how to send sms via php.
if anyone has used/tried "Ozeki NG - SMS Gateway" then please let me know how to use it properly?
Any suggestions please do let me know.
I have a nokia 701. Can it be used as a gsm modem?.
Thank you

Try out this example code from Twilio, I used it during one of the hackathons.
Just for demo purpose this may help.
Depends on what country though.
http://www.twilio.com/docs/quickstart/php/sms

American Telcos let you send text messages as emails. I haven't played with this is many years, but I remember Verizon being [Phone #]#vtext.com, where [Phone #] is the 10-digit phone number of the cell phone. There are different domains for the different Telcos that you can lookup. Best of all this is free, rather than having to pay per text message.

If your phone is android you could use an app such as SMS Gateway API which will turn your phone into a SMS gateway and would allow you to both send and receive messages via PHP.
$URL = "http://v2.smsgateway.me/API/Send/Single.php";
$postdata = http_build_query(
array(
'Username' => "foo#bar.co.uk",
'Password' => "password",
'Number' => "+447791064782",
'Message' => "Hello World!",
'Device' => 1, //Send from device 1 (optional)
'SendAt' => (time() + (60 * 60)), //Send in 1 hours time (optional)
'ExpireAt' => (time() + (60 * 60 * 2)) //Expire in 2 hours time (optional)
)
);
$opts = array('http' => array('method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata));
$context = stream_context_create($opts);
$result = file_get_contents($URL, false, $context);
echo $result;

Your can try https://www.clickatell.com/ it is easy to use & integrate into your php code you can use http or rest api.

I assume that you already have sms service from msg91 using above setup or you can use any sms service providers like Twilio, Nexmo etc. Now i am creating a common function which you can call anywhere in your PHP code to send any type of text sms.
//send otp message
public static function sendMessage($mobile, $message)
{
$message = urlencode($message);
$url = sprintf("http://api.msg91.com/api/v2/sendsms?authkey=%s&mobiles=%s&message=%s&sender=%s&route=%s",
env('MSG91_AUTH_KEY'), $mobile, $message, env('MSG91_SENDER_ID'), env('MSG91_ROUTE'));
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
For more details and step by step execution follow below link :
https://www.lelocode.com/posts/sending-sms-like-otp,-welcome-message,mobile-verification-using-php---lelocode

Related

Send FCM Push notifcations to specific devices in android app using MySQL query as identification from a PHP script

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);

Integrating custom SMS API with woocommerce

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;
}

Send SMS Message using PHP

I have developed a system which will send SMS to the customer after making insert to the database
but the system which I worked on is public ie. when my client asked me to buy the system he must insert his SMS API configuration to send a message to his customers
when I searched on the internet I found that every API have a differnt way to send SMS message
I have account in click tell API but when I send message by curl there is nothing happen
the code is
$url = 'https://platform.clickatell.com/messages/http/send?' . http_build_query(
[
'apiKey' => 'oGjnzDdSRhqdhhgnjFj3ZmzYA==',
// 'api_secret' => '4c98619ffb9af51585',
'to' => '94233698311783',
'content' => 'Hello from Netcom'
]
);
echo($url);echo('<br/>');
echo'https://platform.clickatell.com/messages/http/send?apiKey=oGkmzDdSRgekvjFjaZnzYA==&to=905373545631&content=Test+message+text"';
$ch = curl_init($url);
echo($ch);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
echo $response;
Where my code is wrong and what is the way to send SMS dynamically depending on the client's API info
For quick fix and testing add this in your curl request and check response.(Because url is https)
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false);
But it is recomonded to downloading a CA root certificate bundle at the curl website and saving it on your server which protect your site
I am not aware of Clickatell, but Aws SNS is quite simple,
$payload = array(
'Message' => $message,
'PhoneNumber' => $mobile,
'MessageAttributes' => $msgAttributes
);
$result = $sns->publish($payload);

Send out email/campaign to a list when url is visited in mailchimp

Hello Stackoverflow :)
I'm building a script for a client that has an e-paper that comes out everyday.
The e-paper is build by a 3rd party and when they publish it, they can have their system visit an URL of our choice.
When their system visits our URL we wan't a mailchimp automated e-mail (with a link to the e-paper) to be send out to everyone on one of our lists.
So my question is: Can the automated paid feature in Mailchimp do this for us or do we need to code a script with the mailchimp API at the URL to take care of the automated e-mail to the lists? And if the latter which methods should I look into in the documentation?
Not looking for a complete answer, but a pointing in the right direction :)
Google hasn't helped me with the following queries: "send out email to a list when url is visited", "send email campaign to list when url is visited" which is why I now turn to you :)
Thanks in advance
Generally speaking, you could use MailChimp's Goal and Automation features to accomplish something like this. However, you're dealing with a dynamically generated URL that needs to be included in your email. So far, I haven't come accross a way to transfer information from a "Goal page" to MailChimp - other than the data that is transferred automatically by the Goal script.
So I think you're looking at an API job. You'll need to use "Campaigns" methods (http://developer.mailchimp.com/documentation/mailchimp/reference/campaigns/).
Please note that creating and sending a campaign are two different steps of the overall process. You'll find the "send" method under "Action" on the same page. Just take the ID returned by the "create" method, feed it into the "send" method and watch the magic happen.
Hope this helps!
Here it is in all it's glory! And it' fixes the issue I had :)
<?php
/**
* Method for communicating with mailchimp API
*
* #param str $method Which url you need to access in the Mailchimp API
* #param str $type Which type of request (POST, GET etc)
* #param array $data Do you need to pass data along aswell in a multi dimensional array?
*
* #author Kenneth Johnsen <Johns3n#gmail.com>
* #return Server Header Response
*/
function request($method,$type, $data = false){
$apiKey = '<API KEY>';
$dataCenter = substr($apiKey,strpos($apiKey,'-')+1);
$url = 'https://' . $dataCenter . '.api.mailchimp.com/3.0'.$method;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_USERPWD, 'user:' . $apiKey);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $type);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
if($data){
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode($data));
}
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
// GET VARIABLES THAT MIGHT CHANGE DEPENDING ON E-PAPER SUPPLIER:
// -------------------------------------------------------------------------------------
$paper = 'Name of Company';
$replyTo = 'noreply#companyname.com';
$templateId = 65;
// CREATE CAMPAIGN AND RETURN THE ID SO WE CAN EDIT IT ASWELL:
// -------------------------------------------------------------------------------------
$campaign = array(
'type' => 'regular',
'recipients' => array(
'list_id' => '<LIST ID>'
),
'settings' => array(
'subject_line' => 'E-paper for '.$paper.' is now ready!',
'title' => $paper.' E-Paper Notification ('.date("d/m-Y").')',
'from_name' => $paper,
'reply_to' => $replyTo,
)
);
$createCampaign = request('/campaigns','POST',$campaign);
$createCampaign = json_decode($createCampaign);
// EDIT THE CAMPAIGN TO MATCH TEMPLATE ID:
// -------------------------------------------------------------------------------------
$editCampaign = array(
'template' => array(
'id' => $templateId
)
);
$updateCampaign = request('/campaigns/'.$createCampaign->id.'/content','PUT',$editCampaign);
// SCHEDULE THE CAMPAIGN FOR LAUNCH FROM NEAREST QUARTER MINUTE + ANOTHER 30 MINUTES:
// -------------------------------------------------------------------------------------
$time = time();
$time = round($time / (15 * 60)) * (15 * 60) + (30 * 60);
$time = date('i',$time);
$timeSchedule = date('Y-m-dTH:'.$time.':00+01:00');
$schedule = array(
'schedule_time' => $timeSchedule
);
$scheduleCampaign = request('/campaigns/'.$createCampaign->id.'/actions/schedule','POST',$schedule);
var_dump($scheduleCampaign);

Emailing entire userbase in one PHP script? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm wondering how do people handle emailing their userbase. I'm using PHP and SendGrid is handling the emails. The use case is a newsletter.
When I send myself 50 emails in testing the script already takes quite a long time and I worry that the application will time out if go for more emails at a time.
I don't really want to send myself 100, then 1,000, then 10,000 emails to see what the upper limit is testing this out.
I'm running this on a medium EC2 Linux if that is helpful.
There are several ways to accomplish this with SendGrid.
Send Emails in Parallel
It's likely that you're currently sending your emails in a series (i.e. send one email, wait for it to send, then send the next). This means if it takes you 1 second to send an email, it will take you 100 seconds to send one hundred.
Luckily, PHP's cURL Library allows you to send many POST requests in parallel, rather than in a series.
// An array of the emails you want to send to:
$emails = array("joe#example.org", "sue#example.com");
$credentials = array("api_user" => YOUR_SENDGRID_USERNAME, "api_key" => YOUR_SENDGRID_PASSWORD);
$multi_handle = curl_multi_init();
$handles = array();
// Loop through each email and create a cURL Handle for the email
// The cURL handle will POST an email to SendGrid with the proper info
foreach ($emails as $key => $email) {
// Create an email data object with your credentials in it,
// we'll POST this to SendGrid
$email_data = $credentials;
// Fill out all the information you want for the email
$email_data = array(
"to" => $email,
"from" => "you#example.net",
"subject" => generate_subject(),
"html" => generate_html(),
"text" => generate_text()
);
$handles[$key] = curl_init();
curl_setopt($handles[$key], CURLOPT_URL, "https://api.sendgrid.com/api/mail.send.json");
curl_setopt($handles[$key], CURLOPT_POST, 1);
curl_setopt($handles[$key], CURLOPT_POSTFIELDS, $email_data);
curl_setopt($handles[$key], CURLOPT_RETURNTRANSFER, true);
curl_multi_add_handle($multi_handle, $handles[$key]);
}
$running = null;
// Run through each cURL handle and execute it.
do {
curl_multi_exec($multi_handle, $running);
} while ($running);
curl_multi_close($multi_handle);
This method works well if you have lots of hyper-unique emails that you want to send, however it still results in a bunch of POST requests from your server, which are slow and resource consuming. There's often a better way.
Send Emails Using the SMTPAPI
SendGrid has an SMTPAPI which allows you to send up to 10,000 emails with one POST request using the to parameter. You can make these emails semi-unique by using substitution tags.
For this you'd do something like the following:
// An array of the emails you want to send to:
$emails = array("joe#example.org", "sue#example.com");
// Encode it into the SendGrid SMTPAPI Format
$smtpapi = array( "to" => $emails );
$params = array(
"api_user" => YOUR_SENDGRID_USERNAME,
"api_key" => YOUR_SENDGRID_PASSWORD,
"to" => "you#example.com",
"subject" => "testing from curl",
"html" => "testing body",
"text" => "testing body",
"from" => "you#example.com",
"x-smtpapi" => json_encode($smtpapi);
);
$request = "https://api.sendgrid.com/api/mail.send.json";
// Generate curl request
$session = curl_init($request);
// Tell curl to use HTTP POST
curl_setopt ($session, CURLOPT_POST, true);
// Tell curl that this is the body of the POST
curl_setopt ($session, CURLOPT_POSTFIELDS, $params);
// Tell curl not to return headers, but do return the response
curl_setopt($session, CURLOPT_HEADER, false);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
// obtain response
$response = curl_exec($session);
curl_close($session);
However, it's probably better to do this with SendGrid's PHP Library
$emails = array("joe#example.org", "sue#example.com");
$sendgrid = new SendGrid(YOUR_SENDGRID_USERNAME, YOUR_SENDGRID_PASSWORD);
$email = new SendGrid\Email();
$email->setTos($emails)->
setFrom('me#bar.com')->
setSubject('Subject goes here')->
setText('Hello World!')->
setHtml('<strong>Hello World!</strong>');
$sendgrid->send($email);
Queueing
Finally, you could utilize a queue and send all the emails from a different process to speed up your execution time, information on how to do that is in this StackOverflow response.

Categories