I can now send an SMS via kannel. However this is done via headers eg:
header("Location:http://localhost:13013/cgi-bin/sendsms?username=xxxx&password=xxxx&to=$in_number&text=$in_msg");
I want to send an sms via a php function and I got the code below online but it doesn't work. (Kannel smsbox log shows no request):
function sendSmsMessage($in_number, $in_msg)
{
$url = '/cgi-bin/sendsms?username=' . CONFIG_KANNEL_USER_NAME
. '&password=' . CONFIG_KANNEL_PASSWORD
. '&charset=UCS-2&coding=2'
. "&to={$in_number}"
. '&text=' . urlencode(iconv('utf-8', 'ucs-2', $in_msg));
$results = file('http://'
. CONFIG_KANNEL_HOST . ':'
. CONFIG_KANNEL_PORT . $url);
}
Is there something wrong? I tried replacing the CONFIG_KANNEL_USER_NAME and the rest with the actual values but it still doesn't work. Open to suggestions.
I used cURL and it works 100% okay. file_get_contents does not work for me because I want to pass variables to the kannel url and file_get_contents does not process variables coz it insists on using single quotes(php treats it as a string value) instead of double quotes(php will parse the string checking for variables etc).
Here is what i am currently doing assuming you already have your variables initialized somewhere:
$textmsg="Hello Stackoverflow Users!";
$cellphone_number = "+254xxxxxxx"
$encmsg=urlencode($textmsg);
$ch= curl_init();
curl_setopt($ch, "http://localhost:13013/cgi-bin/sendsms?username=xxxxx&password=xxxxx&to=$cellphone_number&text=$encmsg");
curl_exec($ch);
curl_close($ch);
This will work for the simple task of telling kannel to send an sms to a number. Took me a while to realize curl does not recognize spaces and special characters :-).
My friend and I from Ndola, Zambia are using ubuntu 11.04 to run kannel_1.4.3. It works perfectly way in sending and receiving sms. The code below had to be edited for it to send more that 70 characters. My friend and I struggled to figure out that there was a small error in the line '&charset=UCS-2&coding=2'. The correct line should be '&charset=UCS-2&encoding=2'. So the code should appear as below:
function sendSmsMessage($in_number, $in_msg)
{
$url = '/cgi-bin/sendsms?username=' . CONFIG_KANNEL_USER_NAME
. '&password=' . CONFIG_KANNEL_PASSWORD
. '&charset=UCS-2&encoding=2'
. "&to={$in_number}"
. '&text=' . urlencode(iconv('utf-8', 'ucs-2', $in_msg));
Using curl:
curl_init("http://$gw_host:$gw_port/cgi-bin/sendsms?username=$gw_user&password=$gw_pass&to=$to&from=$shortcode&smsc=$smsc&dlr-mask=$dlrmask&binfo=$shortcode&text=$message");
Replace the various variables/parameters with your values such as:
$gw_host=127.0.0.1
$gw_port=13xx3
etc.
If you're attempting to trigger a URL loading in the background (rather than by re-directing the user to the URL), you need to use something like cURL or perhaps even file_get_contents.
For example, if your set up has fopen URL wrappers enabled, you could simply use:
$response = file_get_contents("http://localhost:13013/cgi-bin/sendsms?username=xxxx&password=xxxx&to=$in_number&text=$in_msg");
Irrespective, it's hard to know why the function you found won't work without some additional debug information. (If CONFIG_KANNEL_HOST is defined as "localhost" and CONFIG_KANNEL_PORT is defined as 13013 then it's effectively doing the same thing, albeit with additional character set operations.)
Not to ressucitate an ancient question, but for posteriority and others searching for the same thing:
[root#sat2 tools]# cat kannel-send.php
<?php
function send_sms($msgid, $numto, $msgtext, $smsc = "smsc-default", $dlrmask = 63)
{
$sendsmsurl_prefix = "http://localhost:13013/cgi-bin/sendsms";
$dlrurl_prefix = "http://localhost/tools/kannel-receive.php";
$username = "user";
$password = "pass";
# fix number to what carriers expect
$numto = preg_replace('/^0/', '', $numto);
$numto = preg_replace('/^\+55/', '', $numto);
$numto = "0" . $numto;
if (!$msgid) $dlrmask = 0;
$dlrurl_params = array(
"type" => "dlr",
"timesent" => "%t",
"smsc" => "%i",
"uuid" => "%I",
"fid" => "%F",
"dlr-cod" => "%d",
"reply" => "%A",
"msgid" => $msgid,
"text" => "%a",
"to" => "%P",
"from" => "%p",
"origsmsc" => "%f",
);
$dlrurl = $dlrurl_prefix . "?" . urldecode(http_build_query($dlrurl_params));
$sendsmsurl_params = array(
"username" => $username,
"password" => $password,
"to" => $numto,
"dlr-mask" => $dlrmask,
"dlr-url" => $dlrurl,
"smsc"=> $smsc,
"text" => $msgtext,
);
$sendsmsurl = $sendsmsurl_prefix . "?" . http_build_query($sendsmsurl_params);
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $sendsmsurl);
$bogus = curl_exec($ch);
$ret = curl_error($ch);
curl_close($ch);
return $ret == "";
}
?>
And you could have this other one to receive sms and store it to mysql:
[root#sat2 tools]# cat kannel-receive.php
<?php
$debug = false;
$link = null;
function dbconnect()
{
global $link, $debug;
if ($link && mysql_ping($link))
return;
if ($debug) echo "Conectando ao banco de dados\n";
// TODO: criar um usuario de banco especifico pra isso
$host = 'localhost';
$user = 'user';
$pass = 'pass';
$db = 'dbname';
$link = mysql_connect($host, $user, $pass, true);
if (!$link){
if ($debug) echo "Can't connect to mysql: " . mysql_error() . "\n";
} else {
mysql_select_db($db, $link);
}
return;
}
function esc($str)
{
global $link;
return mysql_real_escape_string($str, $link);
}
if ($debug) {
echo "<br>Kannel inbound sms event:<br>\n";
var_dump($_GET);
}
dbconnect();
if ($_GET['type'] == "inbsms") {
$_GET['from'] = preg_replace('/^(\+55|0)/', '', $_GET['from']);
$sql = "INSERT INTO notificacao (tipo, endereco, mensagem, device,
dataEvento, situacao)
VALUES ('%s', '%s','%s','%s','%s','%s')";
$sql = sprintf($sql, 'sms', esc($_GET['from']), esc($_GET['text']),
esc($_GET['smsc']), esc($_GET['timesent']), "received");
} elseif ($_GET['type'] == "dlr") {
switch (esc($_GET['dlr-cod'])) {
case "1":
$sql = "UPDATE notificacao SET
situacao = 'confirmed',
dataConfirmacao = '{$_GET['timesent']}'
WHERE idnotificacao = {$_GET['msgid']}";
break;
case "8":
$sql = "UPDATE notificacao SET
situacao = 'sent',
device = '{$_GET['smsc']}',
dataEvento = '{$_GET['timesent']}'
WHERE idnotificacao = {$_GET['msgid']}";
break;
case "16":
$sql = "UPDATE notificacao SET
situacao = 'failed',
device = '{$_GET['smsc']}',
razaofalha = '{$_GET['reply']}',
dataEvento = '{$_GET['timesent']}'
WHERE idnotificacao = {$_GET['msgid']}";
break;
}
}
if ($debug) echo "sql: $sql\n";
$result = mysql_query($sql, $link);
if (!$result) {
if ($debug) echo "Erro sql: " . mysql_error() . "\n";
}
?>
This one doubles as a SMS receiver and a SMS-Delivery-Notification receiver (in that case it updates a record on the database that was put there when sending the sms, to confirm it was received).
It's used for DLR because I send the URL for that when sending the SMS (and set the DLR mask asking for confirmation), but for inbound SMS you have to configure your kannel.conf to use it (you can have many sms-service, this is just an example of a catch-all one:
[...]
group = sms-service
keyword = default
get-url = "http://localhost/tools/kannel-receive.php?type=inbsms&text=%a×ent=%t&from=%p&to=%P&smsc=%i&uuid=%I&delivery=%d&service=%n&encoding=%c&class=%m&mwi=%M&charset=%C&udh=%u&dcs=%O&origsmsc=%f"
catch-all = yes
max-messages = 0
accept-x-kannel-headers = true
concatenation = yes
omit-empty = yes
[...]
Sorry for some texts in portuguese, but you can get the picture.
//php code file name is test2.php.before that,you must install php5-curl on ubuntu14
Related
I'm trying to set Google Translation API on my server.
But code returns error "Could not construct ApplicationDefaultCredentials"
$translationClient = new Google\Cloud\Translate\V3\TranslationServiceClient();
putenv('GOOGLE_APPLICATION_CREDENTIALS="/path/to/credetials.json"');
$content = ['one', 'two', 'three'];
$targetLanguage = 'es';
$response = $translationClient->translateText(
$content,
$targetLanguage,
TranslationServiceClient::locationName('[ProjectID]', 'global')
);
$res = '';
foreach ($response->getTranslations() as $key => $translation) {
$separator = $key === 2
? '!'
: ', ';
$res .= $translation->getTranslatedText() . $separator;
}
} catch(\Exception $e) {
$res = $e->getMessage();
}
die(json_encode($res));
I've already spend a lot of time to setting it but with no result.
Please, help me
You can pass the credentials in a config variable and then initialize the client.
<?php
require __DIR__ . '/vendor/autoload.php';
use Google\Cloud\Translate\V2\TranslateClient;
/** Uncomment and populate these variables in your code */
$config = ['credentials' => 'key.json'];
$text = "The text to translate.";
$targetLanguage = "ja";
$translate = new TranslateClient($config);
$result = $translate->translate($text, [
"target" => $targetLanguage,
]);
print("Source language: $result[source]\n");
print("Translation: $result[text]\n");
?>
Source language: en
Translation: 翻訳するテキスト
Php putenv https://www.php.net/manual/en/function.putenv.php
Andrey this worked for me on Windows 10 Pro. Wampserver 3.2.0. Php 7.4.4. It definitely has a problem with Windows backslashes. Forwardslashes and avoiding double quotes and single quotes together has helped to bump the compiler along.
$file = trim("C:/users/boss/onedrive/desktop/google.json",'"');
putenv("GOOGLE_APPLICATION_CREDENTIALS=$file");
I can't seem to find any code to display returned values from the call.
I am running the xml-lib from the software vendor at the following link
https://support.sippysoft.com/support/solutions/articles/3000013653-xml-rpc-api-sign-up-html-page-fresh-version-
<?php
include 'xmlrpc/xmlrpc.inc';
function listAccounts()
{
//$params = array(new xmlrpcval(array("i_account"=> new xmlrpcval('14719', "string")), 'struct'));
$msg = new xmlrpcmsg('listAccounts');
/* replace here URL and credentials to access to the API */
$cli = new xmlrpc_client('https://DOMAINHERE/xmlapi/xmlapi');
$cli->setSSLVerifyPeer(false);
$cli->setSSLVerifyHost(false);
$cli->setCredentials('USERNAME', 'PASSWORD', CURLAUTH_DIGEST);
$r = $cli->send($msg, 20);
if ($r->faultCode()) {
error_log("Fault. Code: " . $r->faultCode() . ", Reason: " . $r->faultString());
print_r ($r->faultString());
return false;
}
else
{
return $r->value();
// I need something here to write returned values to normal PHP variable
}
}
Ok thanks to the comment from halfer.
I managed to get the issue and digging through the code in the library I found a function that does the trick.
Thanks a million for your pointer it really helped.
I am new to php and xml and the learning curve is quite tall but thanks.
for someone else reference maybe in the future here is the corrected code with the last 2 lines that does the magic for me.
<?php
include 'xmlrpc/xmlrpc.inc';
// $params = array(new xmlrpcval(array("offset"=> new xmlrpcval("1", "int")
// ,"i_customer"=> new xmlrpcval("321", "int")
// ), 'struct'));
$params = array(new xmlrpcval(array("i_customer"=> new xmlrpcval("321", "int")
), 'struct'));
$msg = new xmlrpcmsg('listAccounts', $params);
/* replace here URL and credentials to access to the API */
$cli = new xmlrpc_client('DOMAIN');
$cli->setSSLVerifyPeer(false);
$cli->setdebug(0);
$r = $cli->send($msg, 20); /* 20 seconds timeout */
if ($r->faultCode()) {
error_log("Fault. Code: " . $r->faultCode() . ", Reason: " . $r->faultString());
echo $r->faultString();
}
// now lets decode the xml response..
$values=php_xmlrpc_decode($r->value());
var_dump ($values['accounts'][0][username]);
?>
I need to send order confirmation SMS message to my users via my SMS gateway API in PrestaShop. Is that possible?
I am using the ValueFirst SMS gateway.
Here is my code:
<?php
$username="username";
$password="password";
$to="mobilenumber";
$sender="senderid";
$message="message";
if($username!='' && $password!='' && $to!='' && $sender!='' && $message!='')
{
class sendSms
{
var $serverURL = 'http://api.myvaluefirst.com/psms/servlet/psms.Eservice2';
var $gsmSender = 'MYGSMID';
function GetSenderID()
{
return $this->cdmaNumber;
}
function get_address($user_id,$to)
{
$address_info = sprintf('<ADDRESS FROM="%s" TO="%s" SEQ="%s" />',$user_id,$to,1);
return $address_info;
}
function postdata($url,$data)
{
$objURL = curl_init($url);
curl_setopt($objURL, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($objURL,CURLOPT_POST,1);
curl_setopt($objURL, CURLOPT_POSTFIELDS,$data);
$retval = trim(curl_exec($objURL));
curl_close($objURL);
return $retval;
}
function sendSmsToUser($prefix='',$contents='', $toAddr='',$sms_user_name='',$sms_password='',$sms_user_id='' )
{
$xmlstr ='<!DOCTYPE MESSAGE SYSTEM "http://127.0.0.1/psms/dtd/message.dtd"><MESSAGE><USER USERNAME="%s" PASSWORD="%s"/><SMS UDH=" 0 " CODING=" 1 " TEXT="%s" PROPERTY=" 0 " ID=" 2 ">%s</SMS></MESSAGE>';
$contents = stripslashes($prefix.$contents);
$contents = htmlentities($contents,ENT_COMPAT);
$username = stripslashes($sms_user_name);
$username = htmlentities($username,ENT_COMPAT);
$password = stripslashes($sms_password);
$password = htmlentities($password,ENT_COMPAT);
$user_id = stripslashes($sms_user_id);
$user_id = htmlentities($user_id,ENT_COMPAT);
$xmldata = sprintf($xmlstr,$username,$password,$contents,$this->get_address($user_id,$toAddr));
$data='data='. urlencode($xmldata);
$action='action=send';
$str_response = $this->postdata($this->serverURL,$action.'&'.$data);
$str_request = $this->serverURL.'?'.$action.'&'.$data;
}
}
$mclass = new sendSms();
$mclass->sendSmsToUser("Dear Guest,",$message,$to,$username,$password,$sender);
}
?>
This is my ValueFirst API script. I want to use this script into PrestaShop. How can I do that?
I think this is kinda duplicate with this one : How to integrate msg91 php api with Prestasms or Prestashop?
For instance, create a module at https://validator.prestashop.com/ then add Hooks (function triggered at a certain time automaticly, like on order update) with it.
I am running a PHP code on docker container hosted in Bluemix. The PHP code calls a python script which is a MQTT based subscribe code. My idea was everytime the subscribed code gets MQTT message it will write the values to a text file. The PHP code will keep on checking every 10 seconds for new values in the file.
The VCAP_ENV variables are getting written correctly. However, the site does not load.
The python script executes successfully when i try it locally. So no errors there too.
My code is as follows:
PHP CODE:
<?php
if( getenv("VCAP_SERVICES") ) {
// get IoT service configuration from Bluemix
$services = getenv("VCAP_SERVICES");
$services_json = json_decode($services, true);
$mysql_config = $services_json["iotf-service"][0]["credentials"];
$org_id = $mysql_config["org"];
$port = $mysql_config["mqtt_u_port"];
$username = $mysql_config["apiKey"];
$password = $mysql_config["apiToken"];
}
// set configuration values
$config = array(
'org_id' => $org_id,
'port' => $port,
'app_id' => 'mymqttfinalservice',
'iotf_api_key' => $username,
'iotf_api_secret' => $password,
'device_id' => '007',
'qos' => 1
);
$file = fopen("VCAP_CONFIG.ini","w");
#fwrite($file,"[config]" . PHP_EOL );
#fwrite($file,"org =" . $org_id . PHP_EOL );
#fwrite($file,"apikey =" . $username . PHP_EOL );
#fwrite($file,"authkey =" . $password . PHP_EOL );
fwrite($file,"[config]" . "\n" );
fwrite($file,"org =" . $org_id . "\n" );
fwrite($file,"apikey =" . $username . "\n" );
fwrite($file,"authkey =" . $password . "\n" );
fclose($file);
$file = file_get_contents('VCAP_CONFIG.ini', true);
echo $file;
$command = 'chmod 777 /app/PythonSubscribeCode.py';
$output = '';
exec ( $command);
$command = 'python3 /app/PythonSubscribeCode.py 2>&1';
$output = exec ($command);
print_r($output);
$x = 1;
while($x == 1)
{
$config = parse_ini_file('Data.ini');
echo json_encode($config);
sleep(5);
}
?>
Python Script:
# -*- coding: utf-8 -*-
#!/usr/bin/env python3
import paho.mqtt.client as mqtt
import os, json
import time
import configparser
# This is the Subscriber
settings = configparser.ConfigParser()
settings.read('VCAP_CONFIG.ini')
organization = settings['config']['org']
username = settings['config']['apikey']
password = settings['config']['authkey']
#Set the variables for connecting to the iot service
broker = ""
devicename = "007"
topic = "iot-2/type/DesktopApplication/id/007/evt/status/fmt/json"
#topic = 'iot-2/evt/status/fmt/json'
deviceType = "DesktopApplication"
clientID = "a:" + organization + ":appId"
print (clientID)
broker = organization + ".messaging.internetofthings.ibmcloud.com"
mqttc = mqtt.Client(clientID)
if username is not "":
mqttc.username_pw_set(username, password=password)
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
def on_subscribe(mosq, obj, mid, granted_qos):
print("Subscribed: " + str(mid) + " " + str(granted_qos))
def on_message(mosq, obj, msg):
global message
print(msg.topic + " " + str(msg.qos) + " " + str(msg.payload))
def on_message(client, userdata, msg):
writeData = msg.payload.decode('utf-8')
parsed_json = json.loads(writeData)
UDD = parsed_json['UDD']
DDD = parsed_json['DDD']
PH = parsed_json['PH']
Ignition = parsed_json['Ignition']
# add the settings to the structure of the file, and lets write it out...
config = configparser.ConfigParser()
config['Data'] = {'UDD': UDD,
'DDD': DDD,
'PH': PH,
'Ignition':Ignition}
with open('Data.ini', 'w') as configfile:
config.write(configfile)
mqttc.connect(host=broker, port=1883, keepalive=60)
test = mqttc.subscribe(topic,0)
#print (test)
mqttc.on_connect = on_connect
mqttc.on_subscribe = on_subscribe
mqttc.on_message = on_message
mqttc.loop_forever()
Can someone please guide on this?
Do you get any useful error messages from cf ic logs containerid to see what might be failing? As an alternate, you could also try execing into the container (either cf ic exec -ti containerid bash or docker exec...) and run the python script directly to see if that's giving you other errors when running there.
I need to retrieve a get http request in php and store it in a variable.
I need to execute the following:
https://graph.facebook.com/oauth/access_token?
client_id=YOUR_APP_ID&client_secret=YOUR_APP_SECRET&
grant_type=client_credentials
I know this is simple. just not able to get my head around it.
$content = file_get_contents('https://graph.facebook.com/oauth/access_token?client_id=YOUR_APP_ID&client_secret=YOUR_APP_SECRET&grant_type=client_credentials');
Within the Open Graph protocol page on Facebook, there is an example within the documentation coded using PHP: http://developers.facebook.com/docs/opengraph/
<?php
$ogurl = "INSERT_YOUR_OG_URL_HERE";
define(FACEBOOK_APP_ID, "YOUR_APP_ID_HERE");
define(FACEBOOK_SECRET, "YOUR_SECRET_KEY_HERE");
$mymessage = "Hello World!";
$access_token_url = "https://graph.facebook.com/oauth/access_token";
$parameters = "grant_type=client_credentials&client_id=" . FACEBOOK_APP_ID ."&client_secret=" . FACEBOOK_SECRET;
$access_token = file_get_contents($access_token_url . "?" . $parameters);
$apprequest_url = "https://graph.facebook.com/feed";
$parameters = "?" . $access_token . "&message=" . urlencode($mymessage) . "&id=" . $ogurl . "&method=post";
$myurl = $apprequest_url . $parameters;
$result = file_get_contents($myurl);
// output the post id
echo "post_id" . $result;
}
?>
The key line in actually making the call being:
$result = file_get_contents($myurl);
There is also a good amount of other information about the resulting object you get back there that would be good to take a look into.
Hope this is helpful.
if ($fp = fopen('https://graph.facebook.com/oauth/access_token?
client_id=YOUR_APP_ID&client_secret=YOUR_APP_SECRET&
grant_type=client_credentials', 'r')) {
$content = '';
// keep reading until there's nothing left
while ($line = fread($fp, 1024)) {
$content .= $line;
}
// do something with the content here
// ...
} else {
// an error occured when trying to open the specified url
}
You mean something like
$client_id = $_GET['client_id'];
$client_secret = $_GET['client_secret'];
$grant_type = $_GET['grant_type'];
?
Or rather something like
$content = file_get_contents($url);
?
Use the following
$id = $_GET['client_id'];
$type = $_GET['grant_type'];
$secret = $_GET['client_secret'];
Hope this helps you