Creating Java Client to access WSHTTPBINDING API Service - wshttpbinding

I need to consume a web service from UltiPro in Java. All the examples from UltiPro are for C# (see below) and I cannot see how to translate the into Java.
My research indicates that the key is WSHttpBinding.
UltiPro's documentation includes an XML file that they say...
The following code is an XML example of authenticating to your UltiPro data. You can copy the entire contents and update the values in the request. The response example shows how a successful response will be formatted.
I have written many Web Services and RESTful programs before, but I am stuck on this one.
<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://www.w3.org/2005/08/addressing">
<s:Header>
<a:Action s:mustUnderstand="1">http://www.ultipro.com/services/loginservice/ILoginService/Authenticate</a:Action>
<h:ClientAccessKey xmlns:h="http://www.ultipro.com/services/loginservice">CAK</h:ClientAccessKey>
<h:Password xmlns:h="http://www.ultipro.com/services/loginservice">PASSWORD</h:Password>
<h:UserAccessKey xmlns:h="http://www.ultipro.com/services/loginservice">USER API KEY</h:UserAccessKey>
<h:UserName xmlns:h="http://www.ultipro.com/services/loginservice">USERNAME</h:UserName>
</s:Header>
<s:Body>
<TokenRequest xmlns="http://www.ultipro.com/contracts" />
</s:Body>
</s:Envelope>
C# code:
namespace ConsoleSample
{
using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
using ConsoleSample.LoginService;
public class Program
{
internal static void Main(string[] args)
{
// Setup your user credentials:
const string UserName = "";
const string Password = "";
const string UserApiKey = "";
const string CustomerApiKey = "";
// Create a proxy to the login service:
var loginClient = new LoginServiceClient("WSHttpBinding_ILoginService");
try
{
// Submit the login request to authenticate the user:
string message;
string authenticationToken;
AuthenticationStatus loginRequest =
loginClient
.Authenticate(
CustomerApiKey,
Password,
UserApiKey,
UserName,
out message,
out authenticationToken);
if (loginRequest == AuthenticationStatus.Ok)
{
// User is authenticated and the authentication token is provided.
Console.WriteLine("User authentication successful.");
}
else
{
// User authentication has failed. Review the message for details.
Console.WriteLine("User authentication failed: " + message);
}
loginClient.Close();
Console.WriteLine("Press a key to exit...");
Console.ReadKey(true);
}
catch (Exception ex)
{
Console.WriteLine("Exception: " + ex);
loginClient.Abort();
throw;
}
}

I understand you are looking to write it in JAVA but maybe something from my code will help.
I was able to successfully authenticate using the following code:
<?php
$url = 'https://rental5.ultipro.com/services/LoginService';
$action = 'http://www.ultipro.com/services/loginservice/ILoginService/Authenticate';
$username = 'MY_USERNAME';
$password = 'MY_PASSWORD';
$userAccessKey = 'MY_USER_ACCESS_KEY';
$clientAccessKey = 'MY_CLIENT_ACCESS_KEY';
$loginPayload =<<<EOD
<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://www.w3.org/2005/08/addressing">
<s:Header>
<a:Action s:mustUnderstand="1">{$action}</a:Action>
<h:ClientAccessKey xmlns:h="http://www.ultipro.com/services/loginservice">{$clientAccessKey}</h:ClientAccessKey>
<h:Password xmlns:h="http://www.ultipro.com/services/loginservice">{$password}</h:Password>
<h:UserAccessKey xmlns:h="http://www.ultipro.com/services/loginservice">{$userAccessKey}</h:UserAccessKey>
<h:UserName xmlns:h="http://www.ultipro.com/services/loginservice">{$username}</h:UserName>
</s:Header>
<s:Body>
<TokenRequest xmlns="http://www.ultipro.com/contracts" />
</s:Body>
</s:Envelope>
EOD;
$client = new SoapClient(
null,
array(
'location' => $url,
'uri' => '',
'trace' => 1,
'encoding' => 'UTF-8',
'use' => SOAP_LITERAL,
'soap_version' => SOAP_1_2
)
);
try {
$order_return = $client->__doRequest($loginPayload, $url, $action, SOAP_1_2, 0);
$getLastRequestHeaders = $client->__getLastRequestHeaders();
$getLastRequest = $client->__getLastRequest();
$getLastResponseHeaders = $client->__getLastResponseHeaders();
$getLastResponse = $client->__getLastResponse();
echo "<pre>";
echo $getLastRequestHeaders;
echo '<br>';
echo $getLastResponseHeaders;
echo '<br>';
print_r($order_return);
echo "</pre>";
} catch (SoapFault $exception) {
var_dump(get_class($exception));
var_dump($exception);
}
?>

Related

Swiss post tracking web service implementation using php soap

I'm working on a E-commerce site on which orders are placed. i want to track that delivery status of order and I need to give a status of order to user over mail.
I have to use Swiss Post Tracking Web Service API. Can anyone show me how to do so? I am new to SOAP WSDL.
From my understanding i did this now how to go further? My code below its just basic client i need to:
I need to track the delivery status
Below is my code
$wsdl = "https://webservices.post.ch:17005/IN_MYPBxTT/services/TrackAndTraceDFU.ws?WSDL
$username = 'username';
$password = 'password';
$trace = True;
$soapConfig = array(
'login'=>$username,
'password'=>$password,
'trace'=>$trace,
'keep_alive'=>TRUE,
'encoding'=>'utf8',
'connection_timeout'=>90,
);
$soapClient = new SoapClient($wsdl, $soapConfig);
try {
$xml = '<soapenv:Envelope xmlns:soapenv=“http://schemas.xmlsoap.org/soap/envelope/“
xmlns:req=“http://www.post.ch/npp/trackandtracews/v02/shipmentssearch/req“>
<soapenv:Header/>
<soapenv:Body>
<req:ShipmentsSearch>
<language>de</language>
<ShipmentNumbers>
<ShipmentNumber>99.60.122566.27198756</ShipmentNumber>
</ShipmentNumbers>
<Identity>?</Identity>
<Version>2.4</Version>
</req:ShipmentsSearch>
</soapenv:Body>
</soapenv:Envelope>';
$args = array(new SoapVar($xml, XSD_ANYXML));
$res = $this->_soapClient->__soapCall('ShipmentsSearch', $args);
return $res;
} catch (SoapFault $e) {
echo "Error: {$e}";
}
echo "<hr>Last Response";
echo "<pre>", htmlspecialchars($this->_soapClient->__getLastResponse()), "</pre>";
die;
I am using this code but getting below error
Error: SoapFault exception: [env:Client] Internal Error in /directory-name/ConsignmentWebService.php:114
Stack trace: #0 /directory-name/ConsignmentWebService.php(114): SoapClient->__soapCall('ShipmentsSearch', Array)
and get the response like this
Last Request
<?xml version='1.0' ?>
<env:Envelope xmlns:env='http://schemas.xmlsoap.org/soap/envelope/'>
<env:Body>
<env:Fault>
<faultcode>env:Client</faultcode>
<faultstring>Internal Error</faultstring>
</env:Fault>
</env:Body>
</env:Envelope>
I referred this tutorial
https://www.post.ch/en/business-solutions/digital-commerce/notification-services/sendungsinformationen
please help me I am new in soap
Updated Code who are looking for solution
$wsdl = "https://webservices.post.ch:17005/IN_MYPBxTT/services/TrackAndTraceDFU.ws?WSDL
$username = 'username';
$password = 'password';
$trace = True;
$soapConfig = array(
'login'=>$username,
'password'=>$password,
'trace'=>$trace,
'keep_alive'=>TRUE,
'encoding'=>'utf8',
'connection_timeout'=>90,
);
$soapClient = new SoapClient($wsdl, $soapConfig);
$response = null;
$generateRequest = array(
'language'=>'de',
'ShipmentNumbers'=>array(
'ShipmentNumber'=>$tracking_code, //your track code
),
'Identity'=>'?',
'Version'=>2.4
);
try {
$response = $this->_soapClient->ShipmentsSearch($generateRequest);
return $response;
} catch (SoapFault $fault) {
echo('Error in Getting Delivery Status: '. $fault->__toString() .'<br />');
echo '<pre>';
var_dump($this->_soapClient->__getLastResponse());
echo '</pre>';
die();
}

PHP Soap Client call to WCF service?

How to do this, I m new Soap API, Any sample Code
$soapClient = new SoapClient("http://website.com/EComintegration/IntegrationService.svc?wsdl");
// Prepare SoapHeader parameters
$sh_param = array(
'UserName' => 'admin',
'Password' => 'admin');
//'ClientID' => 1,
//'OutletID' => 1,
//'TerminalID' => 1);
$headers = new SoapHeader('http://website.com/EComintegration/IntegrationService.svc', 'UserCredentials', $sh_param);
// Prepare Soap Client
$soapClient->__setSoapHeaders(array($headers));
// Setup the RemoteFunction parameters
$ap_param = array(
'Location' => 2,
'DateFilter'=>'20200220'
);
// Call RemoteFunction ()
$error = 0;
try {
$info = $soapClient->__call("GetInventory", array($ap_param));
} catch (SoapFault $fault) {
$error = 1;
print("
alert('Sorry, blah returned the following ERROR: ".$fault->faultcode."-".$fault->faultstring.". We will now take you back to our home page.');
window.location = 'main.php';
");
}
if ($error == 0) {
$auth_num = $info->ItemName;
}
WCF is also an implementation of SOAP web service, thereby we should call the service like calling a SOAP web service. Please refer to the official documentation.
https://www.php.net/manual/en/book.soap
https://www.php.net/manual/en/class.soapclient
Also, here are some relevant links, wish it is helpful to you.
How to consume a WCF Web Service that uses custom username validation with a PHP page?
https://forums.asp.net/t/1602125.aspx
https://social.msdn.microsoft.com/Forums/vstudio/en-US/4abef020-7fb5-40ef-be77-227d329bb172/call-wcf-service-from-php-with-authentication?forum=wcf
Feel free to let me know if there is anything I can help with.

Sharepoint 2010 Custom WCF service returns 400 - "bad request" with OpenXML

I'm developing a custom Sharepoint 2010 service to work with Excel files. I'm using VS2015 on my local workstation.
The service works and debugs just fine getting the SPFile, reading it's properties and converting it into a stream. However, as soon as I include the code to create the SpreadsheetDocument using SpreadsheetDocument.Open() it doesn't even debug anymore but simply retuns a response of 400 "Bad Request".
Service Code
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using Microsoft.SharePoint;
using System;
using System.IO;
using System.ServiceModel.Activation;
namespace Lifeco.Corp.Sharepoint
{
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class ExcelItemToSapService : IExcelItemToSapService
{
public ServiceResult SubmitSpreadsheet(string documentUrl)
{
// Ensure we have the neccessary information.
if (string.IsNullOrEmpty(documentUrl))
{
return new ServiceResult() { Status = "error", Message = "List item url is required as the 'documentUrl' parameter." };
}
SPFile doc = SPContext.Current.Web.GetFile(documentUrl);
if (doc == null || !doc.Exists)
{
return new ServiceResult() { Status = "error", Message = string.Format("Document item at '{0}' was not found.", documentUrl) };
}
using (Stream dataStream = doc.OpenBinaryStream())
{
// As is this works. Uncommenting the following 'using' block and I receive 400 - Bad Request without even getting to step into the code and debug.
//using (SpreadsheetDocument document = SpreadsheetDocument.Open(dataStream, false))
//{
// // work with spreadsheet...
//}
}
ServiceResult response = new ServiceResult() { Status = "success" };
response.Message = string.Format("Title: {0} | Version: {1} | Modified By: {2}", doc.Title, doc.UIVersionLabel, doc.ModifiedBy.Name);
return response;
}
}
}
.svc
# ServiceHost
Language="C#"
Debug="true"
Service="Lifeco.Corp.Sharepoint.ExcelItemToSapService, $SharePoint.Project.AssemblyFullName$"
CodeBehind="ExcelItemToSapService.svc.cs"
Factory="Microsoft.SharePoint.Client.Services.MultipleBaseAddressWebServiceHostFactory, Microsoft.SharePoint.Client.ServerRuntime, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
The error is received the same whether calling the service directly in the browser or with the following jquery on a Sharepoint page
$.ajax({
type: "GET",
url: webServerRelativeUrl + '/_vti_bin/ExcelItemToSapService/ExcelItemToSapService.svc/SubmitSpreadsheet',
contentType: "application/json; charset=utf-8",
data: { "documentUrl": "http://s040997/Corporate/Insurance Risk Sample 2.xlsm" },
dataType: 'json',
success: function (data) {
//alert('Success\n' + JSON.stringify(data));
$resultEl.html('<pre>' + JSON.stringify(data) + '</pre>');
},
error: function (jqXHR, status, error) {
$resultEl.html('');
alert('Error\n' + jqXHR.responseText + '\nstatus: ' + status);
//alert('Error\n' + jqXHR.responseText + '\nheader: ' + jqXHR.getResponseHeader() + '\nerror: ' + error);
}
});
Any thoughts?
Thanks
Figured out the issue.
I needed to add the DocumentFormat.OpenXml.dll as an Additional Assembly to my Sharepoint package.
Open /Package/Package.package from Solution Explorer
Advanced tab
Add -> Add Existing assembly
Entered the source path to the DocumentFormat.OpenXml.dll
Selected Deployment Target = GlobalAssemblyCache
OK
And the next test succeeded.

On Tomcat Server Using Yii Framework HTTP_X_USERNAME locally recognized but not online

I prepared an api using yii framework. The api contains an authentication method which checks the HTTP_X_USERNAME and HTTP_X_PASSWORD parameters and compares them with some data in the database.
While testing everything locally on the test dev (WAMP + Eclipse + Tomcat) it worked normally. I tested everything with the Postman. I have put those two parameters (HTTP_X_...) into the header.
After I uploaded the api to the production server (Tomcat) the api always returns authentication FALSE although the authorization data locally and online is the same. The code stops at the part where it checks if those parameters are even set "You must be authorized to access the api. No USERNAME and PASSWORD set.".
Does any one have an idea where the problem is? Why does it work locally and not online???
private function _checkAuth() {
$headers = apache_request_headers ();
if (! (isset ( $headers ['HTTP_X_USERNAME'] ) and isset ( $headers ['HTTP_X_PASSWORD'] ))) {
// Error: Unauthorized
$this->badResponse ( 401, 'You must be authorized to access the api. No USERNAME and PASSWORD set.');
}
$username = $headers ['HTTP_X_USERNAME'];
$password = $headers ['HTTP_X_PASSWORD'];
// Find the user
$criteria = new CDbCriteria ();
$criteria->addCondition ( 'email = :email');
$criteria->addCondition( 'api_access_token = :pass');
$criteria->params = array(':email' => $username, ":pass" => $password);
$school = AutoSchool::model ()->find ( $criteria );
if ($school === null) {
$this->badResponse ( 401, 'Error: You must be authorized to access the api.' );
}
return $school->id;
}
Finally found the problem!
After debuging found that the problem was the method apache_request_headers() since it did not return anything useful which i set in the header.
I implemented my own method
private function apache_request_headers2() {
foreach($_SERVER as $key=>$value) {
if (substr($key,0,5)=="HTTP_") {
$key=str_replace(" ","-",ucwords(strtolower(str_replace("_"," ",substr($key,5)))));
$out[$key]=$value;
}else{
$out[$key]=$value;
}
}
return $out;
}
But this is not all. I had to change the header parameters i was requesting. I had to use $headers ['PHP_AUTH_USER'] and $headers ['PHP_AUTH_PW'] instead of HTTP_X_USERNAME and HTTP_X_PASSWORD.
And finally while issuing the POST request I had to use Basic Authentication and not setting the Header parameters
And the complete code of the edited method:
private function _checkAuth() {
$headers = $this->apache_request_headers2();
if (! (isset ( $headers ['PHP_AUTH_USER'] ) and isset ( $headers ['PHP_AUTH_PW'] ))) {
// Error: Unauthorized
$this->badResponse ( 401, 'You must be authorized to access the api. No USERNAME and PASSWORD set.');
}
$username = $headers ['PHP_AUTH_USER'];
$password = $headers ['PHP_AUTH_PW'];
// Find the user
$criteria = new CDbCriteria ();
$criteria->addCondition ( 'email = :email');
$criteria->addCondition( 'api_access_token = :pass');
$criteria->params = array(':email' => $username, ":pass" => $password);
$school = AutoSchool::model ()->find ( $criteria );
if ($school === null) {
$this->badResponse ( 401, 'Error: You must be authorized to access the api.' );
}
return $school->id;
}

Got problems with webhook to Telegram Bot API

Why is my webhook not working? I do not get any data from telegram bot API. Here is the detailed explanation of my problem:
I got SSL cert from StartSSL, it works fine on my website (according to GeoCerts SSL checker), but still seems like my webhook to Telegram Bot API doesn't work (despite it says that webhook was set I do not get any data).
I am making a webhook to my script on my website in this form:
https://api.telegram.org/bot<token>/setWebhook?url=https://mywebsite.com/path/to/giveawaysbot.php
I get this text in response:
{"ok":true,"result":true,"description":"Webhook was set"}
So it must be working, but it actually doesn't.
Here is my script code:
<?php
ini_set('error_reporting', E_ALL);
$botToken = "<token>";
$website = "https://api.telegram.org/bot".$botToken;
$update = file_get_contents('php://input');
$update = json_decode($update);
print_r($update); // this is made to check if i get any data or not
$chatId = $update["message"]["chat"]["id"];
$message = $update["message"]["text"];
switch ($message) {
case "/test":
sendMessage($chatId,"test complete");
break;
case "/hi":
sendMessage($chatId,"hey there");
break;
default:
sendMessage($chatId,"nono i dont understand you");
}
function sendMessage ($chatId, $message) {
$url = $GLOBALS[website]."/sendMessage?chat_id=".$chatId."&text=".urlencode($message);
file_get_contents($url);
}
?>
I don't actually receive any data to $update. So webhook is not working. Why?
Just another one moment, why your webhooks not work.
In my case the reason was in allowed_updates webhook parameter.
By calling :
https://api.telegram.org/bot<your_bot_token>/getWebhookInfo
You can see
{
"ok": true,
"result": {
"url": "<your webhook url should be here>",
"has_custom_certificate": false,
"pending_update_count": 0,
"max_connections": 40,
"allowed_updates": [
"callback_query"
]
}
}
It means, that your bot can't react to your text messages, and you will not receive any webhooks!
You can note, that "allowed_updates" contains array. So, currently it will react only to inline button events (passed as keyboard layout!). According to the setWebhook documentation, allowed_updates is an "optional" parameter.
To start receieve text messages, you need to add "message" to your "allowed_updates" prop. To do it, just again set your webhooks and add it to query. Like here :
https://api.telegram.org/bot<your_token>/setWebHook?url=<your_url>&allowed_updates=["callback_query","message"]
You will receive something like "url already added", but don't worry, allowed_updates will be updated even in this case. Just try type your message to bot and test your webhooks.
That's all, now, telegram will send webhooks to each direct message from you to your bot. Hope, it helps someone.
I was with this problem. I was trying to look everywhere and couldn't find the solution for my problem, because people were all the time saying that the problem was the SSL certificate. But I found the problem, and that were a lot of things missing on the code to interact with the telegram API webhook envolving curl and this kind of stuff. After I looked in an example at the telegram bot documentation, I solved my problem. Look this example https://core.telegram.org/bots/samples/hellobot
<?php
//telegram example
define('BOT_TOKEN', '12345678:replace-me-with-real-token');
define('API_URL', 'https://api.telegram.org/bot'.BOT_TOKEN.'/');
function apiRequestWebhook($method, $parameters) {
if (!is_string($method)) {
error_log("Method name must be a string\n");
return false;
}
if (!$parameters) {
$parameters = array();
} else if (!is_array($parameters)) {
error_log("Parameters must be an array\n");
return false;
}
$parameters["method"] = $method;
header("Content-Type: application/json");
echo json_encode($parameters);
return true;
}
function exec_curl_request($handle) {
$response = curl_exec($handle);
if ($response === false) {
$errno = curl_errno($handle);
$error = curl_error($handle);
error_log("Curl returned error $errno: $error\n");
curl_close($handle);
return false;
}
$http_code = intval(curl_getinfo($handle, CURLINFO_HTTP_CODE));
curl_close($handle);
if ($http_code >= 500) {
// do not wat to DDOS server if something goes wrong
sleep(10);
return false;
} else if ($http_code != 200) {
$response = json_decode($response, true);
error_log("Request has failed with error {$response['error_code']}: {$response['description']}\n");
if ($http_code == 401) {
throw new Exception('Invalid access token provided');
}
return false;
} else {
$response = json_decode($response, true);
if (isset($response['description'])) {
error_log("Request was successfull: {$response['description']}\n");
}
$response = $response['result'];
}
return $response;
}
function apiRequest($method, $parameters) {
if (!is_string($method)) {
error_log("Method name must be a string\n");
return false;
}
if (!$parameters) {
$parameters = array();
} else if (!is_array($parameters)) {
error_log("Parameters must be an array\n");
return false;
}
foreach ($parameters as $key => &$val) {
// encoding to JSON array parameters, for example reply_markup
if (!is_numeric($val) && !is_string($val)) {
$val = json_encode($val);
}
}
$url = API_URL.$method.'?'.http_build_query($parameters);
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($handle, CURLOPT_TIMEOUT, 60);
return exec_curl_request($handle);
}
function apiRequestJson($method, $parameters) {
if (!is_string($method)) {
error_log("Method name must be a string\n");
return false;
}
if (!$parameters) {
$parameters = array();
} else if (!is_array($parameters)) {
error_log("Parameters must be an array\n");
return false;
}
$parameters["method"] = $method;
$handle = curl_init(API_URL);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($handle, CURLOPT_TIMEOUT, 60);
curl_setopt($handle, CURLOPT_POSTFIELDS, json_encode($parameters));
curl_setopt($handle, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
return exec_curl_request($handle);
}
function processMessage($message) {
// process incoming message
$message_id = $message['message_id'];
$chat_id = $message['chat']['id'];
if (isset($message['text'])) {
// incoming text message
$text = $message['text'];
if (strpos($text, "/start") === 0) {
apiRequestJson("sendMessage", array('chat_id' => $chat_id, "text" => 'Hello', 'reply_markup' => array(
'keyboard' => array(array('Hello', 'Hi')),
'one_time_keyboard' => true,
'resize_keyboard' => true)));
} else if ($text === "Hello" || $text === "Hi") {
apiRequest("sendMessage", array('chat_id' => $chat_id, "text" => 'Nice to meet you'));
} else if (strpos($text, "/stop") === 0) {
// stop now
} else {
apiRequestWebhook("sendMessage", array('chat_id' => $chat_id, "reply_to_message_id" => $message_id, "text" => 'Cool'));
}
} else {
apiRequest("sendMessage", array('chat_id' => $chat_id, "text" => 'I understand only text messages'));
}
}
define('WEBHOOK_URL', 'https://my-site.example.com/secret-path-for-webhooks/');
if (php_sapi_name() == 'cli') {
// if run from console, set or delete webhook
apiRequest('setWebhook', array('url' => isset($argv[1]) && $argv[1] == 'delete' ? '' : WEBHOOK_URL));
exit;
}
$content = file_get_contents("php://input");
$update = json_decode($content, true);
if (!$update) {
// receive wrong update, must not happen
exit;
}
if (isset($update["message"])) {
processMessage($update["message"]);
}
?>
I had similar problem. Now solved.
The problem is possibly in a wrong public certificate. Please follow with attention instructions I propose in my project:
https://github.com/solyaris/BOTServer/blob/master/wiki/usage.md#step-4-create-self-signed-certificate
openssl req -newkey rsa:2048 -sha256 -nodes -keyout /your_home/BOTServer/ssl/PRIVATE.key -x509 -days 365 -out /your_home/BOTServer/ssl/PUBLIC.pem -subj "/C=IT/ST=state/L=location/O=description/CN=your_domain.com"
Telegram setWebhooks API do not check data inside your self-signed digital certificate, returning "ok" even if by example you do not specify a valid /CN! So be carefull to generate a public .pem certificate containing /CN=your_domain corresponding to your REAL HOST domain name!
It may be the SSL cert. I had the same problem: Webhook confirmed but actually SSL cert borked.
This reddit thread was helpful: https://www.reddit.com/r/Telegram/comments/3b4z1k/bot_api_recieving_nothing_on_a_correctly/
This may help who works with Laravel Telegram SDK.
I had a problem with self-signed webhook in Laravel 5.3.
After setup and getting OK result from Telegram with "Webhook was set" message, it didn't work.
The problem was related to CSRF verification. So I added the webhook url to CSRF exceptions and now everything works like a charm.
I had this problem too, after somehow the telegram didn't run my bot, so I tried to renew the certificate and set web hooks again, but again it didn't work, so I updated my VPS(yum update) and then renew my certificate and set web hooks again. after these it started working again.
This is because you are not setting the certificate like this
curl -F "url=https://bot.sapamatech.com/tg" -F "certificate=#/etc/apache2/ssl/bot.pem" https://api.telegram.org/bot265033849:AAHAs6vKVlY7UyqWFUHoE7Toe2TsGvu0sf4/setWebhook
Check this link on how to set Telegram Self Signed Certificate
Try this code. If you have a valid SSL on your web host and you have properly run the setWebhook, it should work (does for me). Make sure you create a file called "log.txt" and give write permission to it:
<?php
define('BOT_TOKEN', '????');
define('API_URL', 'https://api.telegram.org/bot'.BOT_TOKEN.'/');
// read incoming info and grab the chatID
$content = file_get_contents("php://input");
$update = json_decode($content, true);
$chatID = $update["message"]["chat"]["id"];
$message = $update["message"]["text"];
// compose reply
$reply ="";
switch ($message) {
case "/start":
$reply = "Welcome to Siamaks's bot. Type /help to see commands";
break;
case "/test":
$reply = "test complete";
break;
case "/hi":
$reply = "hey there";
break;
case "/help":
$reply = "commands: /start , /test , /hi , /help ";
break;
default:
$reply = "NoNo, I don't understand you";
}
// send reply
$sendto =API_URL."sendmessage?chat_id=".$chatID."&text=".$reply;
file_get_contents($sendto);
// Create a debug log.txt to check the response/repy from Telegram in JSON format.
// You can disable it by commenting checkJSON.
checkJSON($chatID,$update);
function checkJSON($chatID,$update){
$myFile = "log.txt";
$updateArray = print_r($update,TRUE);
$fh = fopen($myFile, 'a') or die("can't open file");
fwrite($fh, $chatID ."nn");
fwrite($fh, $updateArray."nn");
fclose($fh);
}
I had this problem too. In my case was mistake in declaring my API method. I created GET method instead of POST at first.
#api.route('/my-webhook-url')
class TelegramWebhook(Resource):
def post(self): # POST, Carl!
# ...
return response
In my case the error was due to the PHP configuration ( using cPanel )
[26-Jan-2021 09:38:17 UTC] PHP Warning: file_get_contents(): https:// wrapper is disabled in the server configuration by allow_url_fopen=0 in /home/myUsername/public_html/mydomain.com/my_bot_file.php on line 40
and
[26-Jan-2021 09:38:17 UTC] PHP Warning: file_get_contents(https://api.telegram.org/bot<my-bot-id>/sendmessage?chat_id=647778451&text=hello charlie ! k99 ): failed to open stream: no suitable wrapper could be found in /home/myUsername/public_html/myDomain.com/my_bot_file.php on line 40
so - it is pretty self explanatory.
The allow_url_fopen=0 var in the php configuration actually disables the requiered action.
But anyhow your best bet is to look at the error log on your server and see if there are any other errors in the script or server config.