How to implement SMS notification in PHP? - php

I tried implementing curl in my code. But there is no error showing in the code editor but when the code is execute, I receive no message or feedback from the API. Is there something with my code? I also suspected that the url is wrong coded so it cannot be executed as an working url.
$token = "Yfkrf59TrbzxJHtbfn55P9OcyKMS7jq6";
$message = "Your Order Is Delivered";
$contact = $_GET['contactno'];
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://terminal.adasms.com/api/v1/send?_token=".$token."&phone=".$contact."&message=".$message."",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET"
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
I tried to build my url with php variable but nothing worked.
<?php
session_start();
if (isset($_GET['id'])) {
include "dbh.inc.php";
$id = $_GET['id'];
$current = $_SESSION['u_id'];
$newstatus = $_GET['orderstatus'];
if ($newstatus == "Pending")
{
$sql = "UPDATE orders SET orderstatus = 'Accepted' WHERE orderid = '$id';";
mysqli_query($con, $sql);
header("Location: ../currentorder.php");
}
else if ($newstatus == "Accepted")
{
$sql = "UPDATE orders SET orderstatus = 'In Delivery' WHERE orderid = '$id';";
mysqli_query($con, $sql);
header("Location: ../currentorder.php");
}
else if ($newstatus == "In Delivery")
{
$sql = "UPDATE orders SET orderstatus = 'Delivered' WHERE orderid = '$id';";
mysqli_query($con, $sql);
$token = "Yfkrf59TrbzxJHtbfn55P9OcyKMS7jq6";
$message = "Your Order Is Delivered";
$contact = $_GET['contactno'];
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://terminal.adasms.com/api/v1/send?_token=".$token."&phone=".$contact."&message=".$message."",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET"
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
header("Location: ../currentorder.php");
}
else{
header("Location: ../currentorder.php");
}
}

Related

Select Conditional SQL Statement

I am posting data to a URL to send a Thank You Message. The details am picking are from a table called readtextfilejson. From where I am sending Thank you messages to users.
I am however not able to select details of the only users who haven't received their text message. My code is selecting all the data and posting to all the users again and again in a loop. Thus sending multiple ThankYouMessages to users.
I have added a new column called ThankyouMessage that is by default = 'not sent'.
So that when my script runs, it updates the ThankYouMessage column to = 'SENT', so that my script can Only select details of users who haven't yet received their thankyoumessage.
Thus i don't keep re-sending the same message again and again. Kindly take a look at my script below and assist how i might resolve this.
My table structure:
<?php
$data = (string) file_get_contents($file);
//echo $data;
$data = str_replace('//Confirmation Respose', '', $data);
$data = str_replace('// Validation Response', '', $data);
$data = str_replace(' ', '', $data);
$data = preg_replace('/\s+/S', " ", $data);
$data = trim($data);
$pattern = '/\s*/m';
$replace = '';
$testString = $data;
$removedWhitespace = preg_replace( $pattern, $replace,$testString );
$removedWhitespace2 = str_replace (' ', '', $testString);
$getAllData = explode('}{', $removedWhitespace2);
foreach ($getAllData as $row) {
$row = str_replace('{', '', $row);
$rowData = explode(',"', $row);
$rowData = explode(',"', $row);
$columnValues = array();
$chkTransId = '';
foreach ($rowData as $value) {
$newVal = explode(':', $value);
$key = str_replace('"', '', $newVal[0]);
$val = str_replace('"', '', $newVal[1]);
$val = trim($val);
$columnValues[] = ($val) ? "'$val'": "''";
if($key == 'TransID'){
$chkTransId = $val;
}
}
if($chkTransId == ''){
continue;
}
////THIS IS THE SECTION AM HAVING PROBLEMS WITH - I WANT TO
////SELECT ONLY THE DATA WHERE THE COLUMN WHERE thankyoumessage =
///// 'NOT SENT'
$chkSql = "select * from `readtextfilejson`where TransID='$chkTransId'";
$getResult = mysqli_query($con, $chkSql);
$getCount = mysqli_num_rows($getResult);
$row = mysqli_fetch_object($getResult);
$text = "Dear ". $row->FirstName ." Your Payment of ". $row->TransAmount ." to XXXXX was Received Succesfully. Confirmation Code: ". $row->TransID ."";
$destination = array("messageId"=>"$product_id","to"=>"$row->MSISDN");
$product_id=uniqid();
$notifyUrl = "URL";
$notifyContentType = "application/json";
$callbackData = 'eHostOnlineCodeCheck125690';
$username = "USERNAME";
$password = "PASSWORD";
$postUrl = "POSTURL";
$message = array("from" => "USERNAME",
"destinations" => $destination,
"text" => $text,
"bulkId" => "",
"notifyUrl" => $notifyUrl,
"flash" => "false",
"notifyContentType" => $notifyContentType,
"callbackData" => $callbackData);
$postData = array("messages" => array($message));
$postDataJson = json_encode($postData);
//Submit all data to SMS server
$ch = curl_init();
$header = array("Content-Type:application/json", "Accept:application/json");
curl_setopt($ch, CURLOPT_URL, $postUrl);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_MAXREDIRS, 2);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postDataJson);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// response of the POST request
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$responseBody = json_decode($response);
curl_close($ch);
echo "<pre>";
print_r($row);
print_r($responseBody);
echo "</pre>";
$Sql = "UPDATE readtextfilejson SET thankyoumessage = 'SENT' WHERE thankyoumessage = 'not sent'";
mysqli_query($con, $Sql) or die(mysqli_error($con));
if($getCount > 0){
continue;
}
$columnValues = implode(',', $columnValues);
$sql = "INSERT INTO `readtextfilejson`(`TransactionType`, `TransID`, `TransTime`, `TransAmount`, `BusinessShortCode`, `BillRefNumber`, `InvoiceNumber`, `OrgAccountBalance`, `ThirdPartyTransID`, `MSISDN`, `FirstName`, `MiddleName`, `LastName`) VALUES (".$columnValues.")";
mysqli_query($con, $sql) or die(mysqli_error($con));
}
echo 'Data inserted successfully';
?>
2 possible issues.
1) You are selecting the transaction regardless of what thankyoumessage is set to. You may need to add a condition to that first SQL's where clause
SELECT * FROM `readtextfilejson`
WHERE TransID = '$chkTransId' AND thankyoumessage = 'not sent'
2) When you update the transaction thankyoumessage to "SENT" you are setting all transactions, because your update statement is missing the transaction id. You may need to add it.
UPDATE readtextfilejson
SET thankyoumessage = 'SENT'
WHERE thankyoumessage = 'not sent' AND TransID = '$chkTransId'
And since you want to set it to SENT regardless of what it was before, you may not need the thankyoumessage check either.
UPDATE readtextfilejson
SET thankyoumessage = 'SENT'
WHERE TransID = '$chkTransId'

insert into vtiger table, php

I have code which connecting to vtiger and now i have problem to insert data into vtiger module Accounts. With select statement I haven't problem, it's working fine, but i cannot insert data. I want to create new organization.
function call($url, $params, $type = "GET")
{
$is_post = 0;
if($type == "POST") {
$is_post = 1;
$post_data = $params;
} else {
$url = $url . "?" . http_build_query($params);
}
$ch = curl_init($url);
if(!$ch) {
die("Cannot allocate a new PHP-CURL handle");
}
if($is_post) {
curl_setopt($ch, CURLOPT_POST, $is_post);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
$return = null;
if(curl_error($ch)) {
$return = false;
} else {
$return = json_decode($data, true);
}
curl_close($ch);
return $return;
}
$endpointUrl = 'http://localhost/vtigercrm/webservice.php';
$userName = 'username';
$password = 'pass';
$userAccessKey = 'acckey';
$sessionData = call($endpointUrl, array(
"operation" => "getchallenge",
"username" => $userName
));
$challengeToken = $sessionData['result']['token'];
$generatedKey = md5($challengeToken . $userAccessKey);
$dataDetails = call($endpointUrl, array(
"operation" => "login",
"username" => $userName,
"accessKey" => $generatedKey
), "POST");
$query = "INSERT INTO Accounts(accountname) VALUES ('some_name');";
$sessionid = $dataDetails['result']['sessionName'];
$getUserDetail = call($endpointUrl, array(
"operation" => "query",
"sessionName" => $sessionid,
'query' => $query
));
To create an object with the webservice you should use the "create" operation not "query"
You can check the webservice tutorial :
https://wiki.vtiger.com/index.php/Webservices_tutorials#Create

SQL Query in PHP script doesnt fill table in database

In PHP script I parsed some .csv file and trying to execute on a few ways and this is a closest I can get. When I run query manually in database everything is o.k but when I go through the the script I just got New record created successfully and the table stays empty except ID which count how many inserts I got.
o.k that's cool optimization but I still don't getting the data. Yap the $dataPacked is clear below is my whole script can you pls gave some suggestion.
<?php
class AdformAPI {
private $baseUrl = 'https://api.example.com/Services';
private $loginUrl = '/Security/Login';
private $getDataExportUrl = '/DataExport/DataExportResult?DataExportName=ApiTest';
public function login($username, $password) {
$url = $this->baseUrl . $this->loginUrl;
$params = json_encode(array('UserName' => $username, 'Password' => $password));
$response = $this->_makePOSTRequest($url, $params);
$response = json_decode($response, true);
if (empty($response['Ticket'])) {
throw new \Exception('Invalid response');
}
// var_dump($response);
return $response['Ticket'];
}
public function getExportData($ticket) {
$url = $this->baseUrl . $this->getDataExportUrl;
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url,
));
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Ticket: '. $ticket
));
$output = curl_exec($ch);
return $output;
}
public function downloadFileFromUrl($url, $savePath) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSLVERSION,3);
$data = curl_exec ($ch);
$error = curl_error($ch);
curl_close ($ch);
// if (!is_dir($savePath) && is_writable($savePath)) {
$file = fopen($savePath, "w+");
fputs($file, $data);
fclose($file);
// } else {
// throw new \Exception('Unable to save file');
// }
}
private function _makePOSTRequest($url, $json_data) {
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POST, count($json_data));
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
}
// Login and data download url
$api = new AdformAPI();
$ticket = $api->login('example', '123546');
$exportDataResponseJson = $api->getExportData($ticket);
$exportDataResponse = json_decode($exportDataResponseJson, true);
if (empty($exportDataResponse['DataExportResult']) || $exportDataResponse['DataExportResult']['DataExportStatus'] != "Done") {
throw new \Exception('GetDataExport invalid response');
}
// Download zip
$fileDir = '/var/www/html/app-catalogue/web/export';
$fileName = 'report.zip';
$filePath = $fileDir . DIRECTORY_SEPARATOR . $fileName;
$api->downloadFileFromUrl($exportDataResponse['DataExportResult']['DataExportResultUrl'], $filePath);
// Unzip
$zip = new ZipArchive;
$res = $zip->open($filePath);
$csvFilename = '';
if ($res === true) {
for ($i = 0; $i < $zip->numFiles; $i++) {
$csvFilename = $zip->getNameIndex($i);
}
$zip->extractTo($fileDir);
$zip->close();
} else {
throw new Exception("Unable to unzip file");
}
// Parse CSV
$csvPath = $fileDir . DIRECTORY_SEPARATOR . $csvFilename;
if (is_readable($csvPath)) {
$dataCsv = file_get_contents($fileDir . DIRECTORY_SEPARATOR . $csvFilename);
$dataArr = explode("\n", $dataCsv);
$dataPacked = array();
foreach ($dataArr as $row) {
$row = str_replace(" ", "", $row);
//$row = wordwrap($row, 20, "\n", true);
$row = preg_replace('/^.{20,}?\b/s', "$0&nbsp", $row);
$row = explode("\t", $row);
$dataPacked[] = $row;
}
}
// SQL Connestion
$servername = "192.168.240.22";
$username = "liferaypublic";
$password = "liferaypublic";
$dbname = "liferay_dev";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset("utf8");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->query("set names 'utf8'");
$sql = " INSERT INTO ho_adform_reports (`Timestamp`, `Campaign`, `Paid_Keywords`, `Natural_Search_Keywords`, `Referrer_Type`, `Referrer`, `Page`, `Order_ID`)
VALUES ";
$flag = true;
foreach($dataPacked as $rowArray) {
if($flag or count($rowArray)<= 7) { $flag = false; continue; }
$sql .= "('".implode("','", $rowArray)."'),";
}
$sql = trim($sql,",");
echo $sql; //For debug only
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
//var_dump($dataPacked);
try this - I am assuming you have sanitised the values in $dataPacked.
Note edited to addslashes just in case.
$conn->query("set names 'utf8'");
$sql = " INSERT INTO ho_adform_reports (`Timestamp`, `Campaign`, `Paid_Keywords`, `Natural_Search_Keywords`, `Referrer_Type`, `Referrer`, `Page`, `Order_ID`)
VALUES ";
$flag = true;
foreach($dataPacked as $rowArray) {
if($flag or count($rowArray)<= 7) { $flag = false; continue;}
foreach ($rowArray as $k=>$v) {
$sanitised = preg_replace("/[^[:alnum:][:space:]]/ui", '', $v);
$rowArray[$k] = addslashes(trim($sanitised));
}
$sql .= "('".implode("','", $rowArray)."'),";
}
$sql = trim($sql,",");
echo $sql; //For debug only
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();

Gcm message not sent to more that 1000 users

Gcm message not sent to more that 1000 users , gcm has its own limit of sending message to 1000 users so the idea is to divide the users in batch of 1000 each i tried that but the gcm message is received by first 1000 users only how can we send the message in batches of 1000 each, in a total of say 5000 users, so that all users get the message i am new to php please explain the working
<?php
require 'connect.php';
function sendPushNotification($registration_ids, $message) {
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registration_ids,
'data' => $message,
);
define('GOOGLE_API_KEY', 'xxxxxxxxxxxxxxxxxxxxxxxxx');
$headers = array(
'Authorization:key=' . GOOGLE_API_KEY,
'Content-Type: application/json'
);
//echo json_encode($fields);
$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_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
if($result === false)
die('Curl failed ' . curl_error());
curl_close($ch);
return $result;
}
$pushStatus = '';
function getGCMCount(){
$total = "";
$query = "SELECT count(gcm_regId) as total FROM gcm_users";
while($query_row = mysql_fetch_assoc($query_run)) {
$total = $query_row['total'] / 1000;
}
return $total;
}
if(!empty($_GET['push'])) {
$query = "SELECT gcm_regId FROM gcm_users";
if($query_run = mysql_query($query)) {
$gcmRegIds = array();
$i = 0;
while($query_row = mysql_fetch_assoc($query_run)) {
$i++;
$gcmRegIds[floor($i/1000)][] = $query_row['gcm_regId'];
//echo $i . "</br>" ;
}
}
$pushMessage = $_POST['message'];
if(isset($gcmRegIds) && isset($pushMessage)) {
$pushStatus = array();
//echo "</br> counnt of messages send is". count($pushStatus);
foreach($gcmRegIds as $key=>$val)
{
$message = array('price' => $pushMessage);
//$message1 = array($key=>$val);
//$c = (array_merge($message ,$message1 ));
$pushStatus[] = sendPushNotification($val, $message);
//echo $key;
}
}
}
?>
<html>
<head>
<title>Google Cloud Messaging (GCM) Server in PHP</title>
</head>
<body>
<h1>Google Cloud Messaging (GCM) Server in PHP</h1>
<form method = 'POST' action = 'send_all.php/?push=1'>
<div>
<textarea rows = 2 name = "message" cols = 23 placeholder = 'Messages to Transmit via GCM'></textarea>
</div>
<div>
<input type = 'submit' value = 'Send Push Notification via GCM'>
</div>
<p><h3><?php //echo $pushStatus . "<br>"?></h3></p>
</form>
</body>
</html>
Refer this snippet for sending messages to more than 1000 users
<?php
//Sample for sending notification to more than 1000 users
$mPushNotification = $push->getMessage();
$stmt = $this->con->prepare("SELECT gcm_regid FROM gcm_users");
$stmt->execute();
$result = $stmt->get_result();
$tokens = array();
while ($token = $result->fetch_assoc()) {
array_push($tokens, $token['gcm_regid']);
}
$firebase = new Firebase();
$total = count($tokens);
$groups = ceil($total/800);
$currentval=ceil($total/$groups);
$firebase = new Firebase();
for ($i=0; $i <$groups; $i++) {
$val=($i*$currentval)+1;
$total = ($i+1)*$currentval;
$resToken = getSpecificToken($val,$total);
$result1 = $firebase->send($resToken, $mPushNotification);
}
function getSpecificToken($upper,$lower)
{
$stmt = $this->con->prepare("SELECT * FROM gcm_users LIMIT $upper,$lower");
$stmt->execute();
$result = $stmt->get_result();
$tokens = array();
while ($token = $result->fetch_assoc()) {
array_push($tokens, $token['gcm_regid']);
}
return $tokens;
}
function getMessage() {
$res = array();
$res['data']['id'] = 1;
$res['data']['title'] = "TestTitle";
$res['data']['message'] = "TestMessage : Hello";
return $res;
}
?>
//Firebase File
<?php
class Firebase {
public function send($registration_ids, $message) {
$fields = array(
'registration_ids' => $registration_ids,
'data' => $message,
);
return $this->sendPushNotification($fields);
}
/*
* This function will make the actual curl request to firebase server
* and then the message is sent
*/
private function sendPushNotification($fields) {
//importing the constant files
require_once 'Config.php';
//firebase server url to send the curl request
$url = 'https://fcm.googleapis.com/fcm/send';
//building headers for the request
$headers = array(
'Authorization: key=' . FIREBASE_API_KEY,
'Content-Type: application/json'
);
//Initializing curl to open a connection
$ch = curl_init();
//Setting the curl url
curl_setopt($ch, CURLOPT_URL, $url);
//setting the method as post
curl_setopt($ch, CURLOPT_POST, true);
//adding headers
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//disabling ssl support
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//adding the fields in json format
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
//finally executing the curl request
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
//Now close the connection
curl_close($ch);
//and return the result
return $result;
}
}
?>

Curl within while loop only sending variables once but runs the loop multiple times

The code below is only sending one variable to my script but it is running trough the loop as normal. I would appreciate some help with this. Thank You.
<?php
$result = mysql_query("SELECT * FROM users WHERE id =$id");
while($row = mysql_fetch_assoc($result)){
//$user_phone = $row['phone'];
$phone = $row['email'];
$email = $row['phone'];
$url = 'http://example.com/request.php?phone='.$phone.'&email='.$email.'';
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_TIMEOUT => '5'
));
$resp = curl_exec($curl);
curl_close($curl);
}
?>
I think try to seperate curl statement from the loop.
<?php
$result = mysql_query("SELECT * FROM users WHERE id =$id");
while($row = mysql_fetch_assoc($result)){
//$user_phone = $row['phone'];
$phone = $row['email'];
$email = $row['phone'];
$url = 'http://example.com/request.php?phone='.$phone.'&email='.$email.'';
call_curl($url);
}
?>
function call_curl($url){
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_TIMEOUT => '5'
));
$resp = curl_exec($curl);
curl_close($curl);
}

Categories