Send a message to a Telegram bot using PHP - php

I'm trying to send a message to a Telegram Bot using CURL in this PHP code ...
<?php
$botToken="<MY_DESTINATION_BOT_TOKEN_HERE>";
$website="https://api.telegram.org/bot".$botToken;
$chatId=1234567; //Receiver Chat Id
$params=[
'chat_id'=>$chatId,
'text'=>'This is my message !!!',
];
$ch = curl_init($website . '/sendMessage');
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
?>
The code runs with no error but no message is shown in my destination Telegram bot.
The token is what the BotFather give me when I created my destination Telegram bot (Use this token to access the HTTP API: <MY_DESTINATION_BOT_TOKEN>)
Any suggestion will be appreciated ...

I've solved .... In my original code there were two errors, one in the code and one due on a Telegram feature that I didn't know: actually, telegram bot to bot communication is not possible as explained here Simulate sending a message to a bot from url
So my code revised is the follow
<?php
$botToken="<MY_DESTINATION_BOT_TOKEN_HERE>";
$website="https://api.telegram.org/bot".$botToken;
$chatId=1234567; //** ===>>>NOTE: this chatId MUST be the chat_id of a person, NOT another bot chatId !!!**
$params=[
'chat_id'=>$chatId,
'text'=>'This is my message !!!',
];
$ch = curl_init($website . '/sendMessage');
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
?>
In this way all works fine!

You can obtain chat ID from #RawDataBot, it will be .message.chat.id.
For instance, in this response will be 109780439.

if you want to send telegram using CURL, you need to download file cacert.pem and copy to your web server and then call them from your PHP script.
You can download file cacert.pem from
https://drive.google.com/open?id=1FCLH88MpKNLDXZg3pJUSAZ0BbUbNmBR2
I have tutorial video that can give you the clearly answer, include how to create bot, get token, get user chat_id, troubleshooting SSL and Proxy in CURL, etc:
Here is the link of my tutorial video https://youtu.be/UNERvcCz-Hw
Here is the complete script:
<?php
// using GET URL Parameter -> message
$pesan = urlencode($_GET["message"]);
$token = "bot"."<token>";
$chat_id = "<chat_id>";
$proxy = "<ip_proxy>:<port>";
$url = "https://api.telegram.org/$token/sendMessage?parse_mode=markdown&chat_id=$chat_id&text=$pesan";
$ch = curl_init();
if($proxy==""){
$optArray = array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CAINFO => "C:\cacert.pem"
);
}
else{
$optArray = array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_PROXY => "$proxy",
CURLOPT_CAINFO => "C:\cacert.pem"
);
}
curl_setopt_array($ch, $optArray);
$result = curl_exec($ch);
$err = curl_error($ch);
curl_close($ch);
if($err<>"") echo "Error: $err";
else echo "Message SENT";
?>

use this will work
$TOKEN="your bot token";
$url="https://api.telegram.org/bot{$TOKEN}/sendMessage";
$request=curl_init($url);
$query=http_build_query([
'chat_id'=>"your id",
'text'=>$msg,
'parse_mode'=>'MarkDown'
]);
curl_setopt_array($request,[
CURLOPT_POST=>1,
CURLOPT_POSTFIELDS=>$query,
]);
curl_exec($request);

I've tested it and its worked.
you only need to us chatId like below:
$chatId='1234567';

Related

Firebase Cloud Message (FCM) : trying to send message to device from PHP (error: InvalidRegistration)

I'm trying to send push messages from PHP but I'm getting the following error message:
{"multicast_id":4832091122368281316,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}
I suppose there is a mismatch with the browser ID but I don't know which one I'm supposed to use.
When I register the push notification through JS, I receive the following payload on my PHP server:
{"endpoint":"https://fcm.googleapis.com/fcm/send/XXX:YYY","expirationTime":null,"keys":{"p256dh":"ZZZ","auth":"AAA"}}
To send the message in PHP, I have used the following code (found on stackexchange):
function sendnotification($to, $title, $message, $img = "", $datapayload = "")
{
$msg = urlencode($message);
$data = array(
'title'=>$title,
'sound' => "default",
'msg'=>$msg,
'data'=>$datapayload,
'body'=>$message,
'color' => "#79bc64"
);
if($img)
{
$data["image"] = $img;
$data["style"] = "picture";
$data["picture"] = $img;
}
$fields = array(
'to'=>$to,
'notification'=>$data,
'data'=>$datapayload,
"priority" => "high",
);
$headers = array(
'Authorization: key=MYSERVERKEY',
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
curl_close( $ch );
return $result;
I think I'm using the right server key, when I don't, I get a different error message.
For $to, I'm wondering what I should use. I thought I had to use XXX:YYY after the endpoint but it's not working (XXX is very short, YYY is very long). I have also tried ZZZ and AAA but it doesn't help either.
My questions:
What kind of ID should I be using to send the message to one specific browser ?
What should I do to send a notification to all registered browser?
Thanks!
Well you have to make sure store the token of your user browser, which you can only get when they allow on request prompt e.g.
On user Allow the request it generate the token which look like as below
This token you can use for send the message to specific browser.
So in your code where as your $to = it should be the device token.
i.e. "to": "<DEVICE_REGISTRATION_TOKEN>"

Microsoft Dynamics CRM and PHP/JSON

I have to implement form on a webpage, that sends data to Microsoft Dynamics CRM when submited. The data needs to be saved to a certain lead.
I have created simple PHP script that uses curl to communicate with CRM server but I always get 401 status code that indicates authorization has failed.
define('MS_CRM_URL', 'https://______.crm.dynamics.com/');
define('MS_CRM_USER', 'user#domain.com');
define('MS_CRM_PASS', 'password');
$method = '/api/data/v8.0/accounts?$select=name&$top=3';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, MS_CRM_URL . $method);
curl_setopt($ch, CURLOPT_USERPWD, MS_CRM_USER .':'. MS_CRM_PASS);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Accept' => 'application/json',
'OData-MaxVersion' => '4.0',
'OData-Version' => '4.0',
'Content-Type' => 'application/json',
));
$server_output = curl_exec($ch);
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$json = array();
if ((int)$status_code === 200) {
$json = json_decode($server_output);
}
echo '<pre>';
var_dump($status_code);
var_dump($json);
echo '</pre>';
The $method var contents are taken from an example that I've found somewhere on Microsoft documentation site. The documentation was not very helpful to me.
Have you seen this yet? http://jlattimer.blogspot.com/2015/02/soap-only-authentication-using-php.html
Also, it looks like there's an ADAL library for PHP. https://github.com/jamesmcq/azure-activedirectory-library-for-php You should be able to authenticate using that.
You can do it using SOAP Authentication. I have same requirement where we need to send data to Dynamics 365 online from PHP website. I have achieved it using source code from below link :
https://bitbucket.org/nigelheap/msdynamicsphp-master

gcm push notification: first success, then not registered in IOS

After all passages for receive the notification with google cloud messaging in IOS but i have this problem:
i send the post in php for the notification with server key and device's token, at first time the response is "success" but not receive nothing on device, at the second time, and subsequent times, the response is "notRegistered". I repeat all passages: create new key in keychain, load in provisioning profile, download the .cer, install in keychain, export .p12 and insert the certificates on google platform for "GoogleService-Info.plist" and reload the device's regId at php, but the response is always this. Help me please.
This is my php :
$apiKey = "server key";
$regId = 'registration token';
$url = 'https://gcm-http.googleapis.com/gcm/send';
$post = '{"to" : "' . $regId . '", "content_available" : true, "priority" : "high", "notification": {"title" : "test", "body" : "test"}}';
$headers = array(
"Authorization:key=$apiKey",
'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_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
if ( curl_errno( $ch ) )
{
echo 'GCM error: ' . curl_error( $ch );
}
curl_close( $ch );
echo $result;
Op's own answer, removed from the edited question:
The problem was the old account without the new provisioning profile, go to : XCode Accounts -> Apple IDs and view details -> Download All. For be sure go to : Targets -> project name -> Build Settings -> search "Provisioning Profile" -> change automatic and select your provisioning profile in use for certificates. The mystery is the xcode's reason don't warning me don't find the correct Provisioning Profile (different bundle id).
My five cents
In case you are having "notRegistered" error only when app is in production that was my mistake: I missed the that in the registration options provided in GCM:
[[GGLInstanceID sharedInstance] tokenWithAuthorizedEntity:_gcmSenderID
scope:kGGLInstanceIDScopeGCM
options:_registrationOptions
handler:self.registrationHandler];
There is an option kGGLInstanceIDAPNSServerTypeSandboxOption which should be set to NO in case of production
Hope it helps!
Some week ago, we also got NotRegistered error on second message send attempt. But For my experience, problem is not on ios side. The problem is on sent message parameters.
Please try to send all required and optional parameters.
Maybe you want to give a try to PHP script on this Q&A
Tip: Sending parameter "content_available as true, priority as high and notification as data" may help.
Below Example Json received with success again and again by ios devices.
"Content-Type" is "application/json"
{
"registration_ids":[
"<reg_id1>",
"<reg_id2>",
],
"priority":"high",
"content_available":true,
"time_to_live":2419200,
"data":{
"message":"Test 15:46:49",
"title":""
},
"notification":{
"title":"",
"body":"Test 15:46:49",
"sound":"default",
"badge":"1"
}
}
Edit 2:
Give a try that;
$apiKey = "server key";
$regId = 'registration token';
$url = 'https://gcm-http.googleapis.com/gcm/send';
$post = '{"to" : "' . $regId . '","priority":"high","content_available":true,"time_to_live":2419200,"data":{"message":"GCM Notifier:Message Success","title":"GCM Notifier:Title Success"},"notification":{"title":"GCM Notifier:Title Success","body":"GCM Notifier:Message Success","sound":"default","badge":"1"}}';
$headers = array(
"Authorization:key=$apiKey",
'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_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
if ( curl_errno( $ch ) )
{
echo 'GCM error: ' . curl_error( $ch );
}
curl_close( $ch );
echo $result;

Get Response from GCM

How can i get Response if the Message was sent or Not, using Php Script, Then i want to use the Response to Determine If the Device is Online or Not,
Here is my Php Script to Send a Message :
function send_push_notification($registration_ids, $message) {
$regId=$registration_ids;
$msg=$message;
$message = array("message" => $msg);
$regArray[]=$registration_ids;
$url = 'https://android.googleapis.com/gcm/send';
$fields = array('registration_ids' => $regArray, 'data' => $message,);
$headers = array( 'Authorization: key=API_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_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result=curl_exec($ch);
echo $result;
if($result==FALSE)
{
die('Curl Failed');
}
curl_close($ch);
}
Thanks
The response your server gets from GCM server doesn't tell you if the message was sent or not. It only tells you if the message was accepted by the GCM server or rejected. If it's accepted, GCM server will try to deliver it, but there's no guarantee it would succeed. If it's rejected, you get an error message (such as InvalidRegistration, MissingRegistration, etc...).
If you want an acknowledgment of delivery, you must have code in your Android app that upon receiving of the message makes a call to your server, to acknowledge the message was received.
You don't get response from the app; you can only get response from the GCM system itself. When the CURL call completes, $result contains a JSON-encoded object; its id property contains a message ID upon success.

Use GCM with PHP

I've seen several posts about how to send GCM messages from my PHP server, but I can't get it working. This is my code:
public function test_gcm($id_user){
// Search user's RegIds and stores them in $regids
if(count($regids) == 0){
echo "This user has no registered device.";
return;
}
$ch = curl_init();
$data = array(
'data' => array('message'=>'my message', 'title'=>'message title'),
'registration_ids' => $regids
);
curl_setopt($ch, CURLOPT_URL, 'https://android.googleapis.com/gcm/send');
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// WRITE JSON HEADERS
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Authorization:key=' . $apiKey)
);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
echo $result;
}
I'm using the browser key. I tried the server key too, but none of them work, the curl_exec always return false. Does anybody know why is it?
EDIT: I just used 'netstat -tuanc | grep 173' on my server and performed the server call. I'm using grep 173 because if I ping android.googleapis.com I ping this ip address. The netstat didn't show any connection to that ip address when I use the curl_exec. Does that mean I'm not connecting to android.googleapis.com? Or what I'm doing is wrong?
Thanks!
Check the "message" content are same or not in android code. 'message'=>'my message' should match with the message from IntentService class in android.
I've managed to fix it. It was a firewall issue, my firewall was blocking the connection. I've added the rules to accept these messages and now it works.
Thanks to all the people that tried to help :)
Try to change it from https to http
curl_setopt($ch, CURLOPT_URL, 'https://android.googleapis.com/gcm/send');
to
curl_setopt($ch, CURLOPT_URL, 'http://android.googleapis.com/gcm/send');
try this http://2mecode.blogspot.hk/2013/01/google-cloud-messaging-php.html
hope it can help you

Categories