Telegram Bot doesn't respond messages - php

i use server on Debian 8 with ISP 5. I have installed that lib: https://github.com/akalongman/php-telegram-bot. Webhook was set but bot doesn't respond messages and commands. Server hadn't logs, I do not know what the problem is :(
I received a SSL from Let's Encrypt in ISP Manager for IP adress.
enter image description here
Here is my set.php
<?php
// Load composer
require __DIR__ . '/vendor/autoload.php';
$API_KEY = 'key';
$BOT_NAME = 'evtepo_bot';
$hook_url = 'https://213./hook.php';
try {
// Create Telegram API object
$telegram = new Longman\TelegramBot\Telegram($API_KEY, $BOT_NAME);
// Set webhook
$result = $telegram->setWebhook($hook_url);
if ($result->isOk()) {
echo $result->getDescription();
}
} catch (Longman\TelegramBot\Exception\TelegramException $e) {
echo $e;
}
And hook.php
<?php
// Load composer
require __DIR__ . '/vendor/autoload.php';
$API_KEY = 'key';
$BOT_NAME = 'evtepo_bot';
$commands_path = __DIR__ . '/Commands/';
try {
// Create Telegram API object
$telegram = new Longman\TelegramBot\Telegram($API_KEY, $BOT_NAME);
// Handle telegram webhook request
$telegram->handle();
} catch (Longman\TelegramBot\Exception\TelegramException $e) {
echo $e;
\Longman\TelegramBot\TelegramLog::initErrorLog(__DIR__ . '/' . $BOT_NAME . '_error.log');
\Longman\TelegramBot\TelegramLog::initDebugLog(__DIR__ . '/' . $BOT_NAME . '_debug.log');
\Longman\TelegramBot\TelegramLog::initUpdateLog(__DIR__ . '/' . $BOT_NAME . '_update.log');
}
$telegram->addCommandsPath($commands_path);

You should use getWebhookInfo method to check if the updates were delivered to the hook and if there were any errors.

The problem was that I needed to buy a domain and get a SSL from Lets'Encrypt.

Related

cURL error 7: Failed to connect to oauth2.googleapis.com port 443

I'm trying to use the google calendar API (from a php script in cli mode) from an OVH shared server
( see: PHP quickstart )
After getting the code in the oAuthCallBack.php file, google gives me the following error:
cURL error 7: Failed to connect to oauth2.googleapis.com port 443: Connection refused
(see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
for https://oauth2.googleapis.com/token
OVH informs me that the concern does not come from them
and the server ip may be blacklisted
How can I resolve this problem ?
EDIT :
Minimal Example : (same problem with quick Start php code )
<?php
require __DIR__ . '/vendor/autoload.php';
if (php_sapi_name() != 'cli') {
throw new Exception('This application must be run on the command line.');
}
/**
* Returns an authorized API client.
* #return Google_Client the authorized client object
*/
function getClient() {
try {
$client = new Google_Client();
} catch (Exception $e) {
echo "Erreur getClient :" . $e->getMessage();
exit;
}
$client->setApplicationName('Google Calendar API PHP Quickstart');
$client->setScopes(Google_Service_Calendar::CALENDAR);
$client->setAuthConfig('credentials.json');
$client->setAccessType('offline');
$client->setPrompt('select_account consent');
$tokenPath = 'token.json';
if (file_exists($tokenPath)) {
$accessToken = json_decode(file_get_contents($tokenPath), true);
$client->setAccessToken($accessToken);
}
// If there is no previous token or it's expired.
if ($client->isAccessTokenExpired()) {
// Refresh the token if possible, else fetch a new one.
if ($client->getRefreshToken()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
} else {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open the following link in your browser:\n%s\n", $authUrl);
print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
$client->setAccessToken($accessToken);
// Check to see if there was an error.
if (array_key_exists('error', $accessToken)) {
throw new Exception(join(', ', $accessToken));
}
}
// Save the token to a file.
if (!file_exists(dirname($tokenPath))) {
mkdir(dirname($tokenPath), 0700, true);
}
file_put_contents($tokenPath, json_encode($client->getAccessToken()));
}
return $client;
}
try{
// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Calendar($client);
// Print the next 10 events on the user's calendar.
$calendarId = 'primary';
$optParams = array(
'maxResults' => 3,
'orderBy' => 'startTime',
'singleEvents' => true,
'timeMin' => '2021-03-18T10:22:53+01:00', // date('c')
);
$results = $service->events->listEvents($calendarId, $optParams);
$events = $results->getItems();
if (empty($events)) {
print "No upcoming events found.\n";
} else {
foreach ($events as $event) {
$start = $event->start->dateTime;
if (empty($start)) {
$start = $event->start->date;
}
$end = $event->end->dateTime;
if (empty($end)) {
$end = $event->end->date;
}
$id = trim($event->getId());
$etag = $event->etag;
$htmlLink = $event->htmlLink;
$summary = $event->summary;
$iCalUID = $event->iCalUID;
$description = str_replace("\r\n", "<br>", nl2br(htmlspecialchars($event->description)));
if ($description == "description test") {
//print_r($event);
echo " => ID: $id - iCalUID: $iCalUID | " . $etag . " | " . $summary . " | " . $htmlLink . " | " . $start . " - " . $end . " | " . $description . PHP_EOL;
}
}
}catch(Exception $e){
echo PHP_EOL . $e->getMessage() . PHP_EOL ;
}
Step 4: Run the sample
Run the sample using the following command:
php quickstart.php
The first time you run the sample, it will prompt you to authorize access:
Browse to the provided URL in your web browser.
If you are not already signed in to your Google account, you are be prompted to sign in. If you are signed in to multiple Google accounts, you are asked to select one account to use for the authorization.
Click the Accept button.
Copy the code you're given, paste it into the command-line prompt, and press Enter.
The error appears here!
To see it, I just added a try / catch block in the code
The problem is not related to the php code, but to the creation of the token.json which it cannot recover from the google servers.
It seems that it is related to an access denied to the ip of the ovh server on which the site is running.
NB: this code works perfectly from a dedicated server.
Thanks,
Jordane

Adding sites to Google Search Console via API

I have a site that has hundred of sub-domains. I need to add these sub-domains to google search console via api and using cron job with php language script.
Can you please take a look at my code bellow and let me know what is wrong with it. There is no error message but it does not add the sub-domain to the right account. Thank you!
<?php
if (!file_exists(__DIR__ . '/vendor/autoload.php')) {
throw new \Exception('please run "composer require google/apiclient:~2.0" in "' . __DIR__ .'"');
}
require_once __DIR__ . '/vendor/autoload.php';
$DEVELOPER_KEY = 'My_key';
$client = new Google_Client();
$client->setApplicationName("MyProjectName");
$client->setDeveloperKey($DEVELOPER_KEY);
$client->setAuthConfig('file.json');
$scopes = array('https://www.googleapis.com/auth/webmasters');
$client->setScopes($scopes);
$url = "http://sub.example.com";
$webmasters = new Google_Service_Webmasters($client);
$webmasters->sites->add($url); // my problem is here
print_r( $webmasters->sites->listSites()); //works fine, gets back sub-domain
?>

cURL error during making API call. cURL Error Number:[60] SSL certificate prob: self signed certificate in certificate chain

Good Day, I am new to server settings. I am currently using laravel 5.4 to integrate my quickbooks app on my live server http://qb.dagnum.com/connect but I continue to get this error
(1/1) SdkException
cURL error during making API call. cURL Error Number:[60] with error:[SSL certificate problem: self signed certificate in certificate chain]
I added the package using 'composer require quickbooks/v3-php-sdk'. the server has SSL certificated Installed as well but still my getting the error.
my code:
use App\Http\Controllers\Controller;
use QuickBooksOnline\API\DataService\DataService;
class Auth2Controller extends Controller
{
public function index()
{
$dataService = DataService::Configure(array(
'auth_mode' => 'oauth2',
'ClientID' => "Q0lCkcEshsGMHOEula2r5RKc2yhxvMsYEpKN1lw1WZwyfd1Si6",
'ClientSecret' => "gE0F9hLgwx9OBzRpNxyOvWJH6L2fIhzAwBugPJHq",
'accessTokenKey' => 'eyJlbmMiOiJBMTI4Q0JDLUhTMjU2IiwiYWxnIjoiZGlyIn0..4z4Assj4x1qt8H4DtQco6A.nmV2jTxaDMVdFWEUO16q5qhbd5aD6U-U-RYnSNywqg-HPC_3_jvwpMJU1a1S5X-PgPUy60WvVy_8p1awY7kIoFzTV4IhdFLrZpYtBUGCjcsvjxWeOSgP6oCayBEmCv7zzabtgB6vxU46jQqKX2IXYUGPPtyYO64hrgELFR4SKUK6boZiVnh8z19gnvsReKMmIINA3-NgC6QJqMRp6HWgzCa9RuDN9tCtrAK2dy5xmJRNSNgdv_gyg1bfdX4l4b30fLPzFk31fsTT9NTJq9PuGtdTsvUuCj7Hme6HPldD9TKYRXWU8TKrQQrQWEpdlbPr6F3rhP6IdmCv9t1XH_WzF_1IseRUoYhiTUjubig-j8gzwajIdYQTzpJQKJ92QiAEyt8k40WWg0v69hEC0w7WRBuUE-IJ50xWypqS_P28IWt1G14rovZ97soGOteSik-41g1icR2zxfNhXGq7zO7oU5B8r-ej5Pb52T0MCMktgd6y32bqwo2pcEzblL2bZs7DZ7LDx5peY4TIfGW21crTE6xjhRr7LdqB8K505pRqIOP20eaRgwtGHLZ3bdBt1_negw2AGjc409BM0nLzzmODxr3yo-YdGwkcOjm5QgbGAsrnpoSo9tSpxPHoN0vMRneRdsKCd6CZG5M1OIOMuj7spkm442tvwiAMCx2Fh-STG6fMnhOq7l_f8NW_3kscxtF2.obQxJKjPfi1KlaQQ_OUoNg',
'refreshTokenKey' => "L011509163184Q0K7DT40SVXhJXAfyoj6B6EbSr3Ty64yVvF5A",
'QBORealmID' => "123145857569084",
'baseUrl' => "https://sandbox-quickbooks.api.intuit.com"
));
$dataService->setMinorVersion("9");
$CompanyInfo = $dataService->getCompanyInfo();
$error = $dataService->getLastError();
if ($error != null) {
echo "The Status code is: " . $error->getHttpStatusCode() . "\n";
echo "The Helper message is: " . $error->getOAuthHelperError() . "\n";
echo "The Response message is: " . $error->getResponseBody() . "\n";
echo "The Intuit Helper message is: IntuitErrorType:{" . $error->getIntuitErrorType() . "} IntuitErrorCode:{" . $error->getIntuitErrorCode() . "} IntuitErrorMessage:{" . $error->getIntuitErrorMessage() . "} IntuitErrorDetail:{" . $error->getIntuitErrorDetail() . "}";
}
}
I also saw the curl function
private function setSSL(&$curl_opt, $verifySSL){
if($verifySSL){
$curl_opt[CURLOPT_SSL_VERIFYPEER] = true;
$curl_opt[CURLOPT_SSL_VERIFYHOST] = 2;
$curl_opt[CURLOPT_CAINFO] = dirname(dirname(__FILE__)) . "/OAuth/OAuth2/certs/apiintuitcom.pem"; //Pem certification Key Path
}
}
tried to replace
$curl_opt[CURLOPT_CAINFO] = dirname(dirname(__FILE__)) . "/OAuth/OAuth2/certs/apiintuitcom.pem";
to `$curl_opt[CURLOPT_CAINFO] ="/home/servername/public_html/quickbooks_app/resources/cert/cacert.pem";`
but I get this error
Http Status Code:[401] Http Response Body are null or Empty.
What should I do to fix this please..
I've dropped the apiintuitcom.pem file that comes with the SDK and started using the cacert.pem that you can find on PHP_OAuth2.0 example app. I was also using a wrong baseUrl but I changed with yours. That fixed the bug for me. My setSSL method looks like this now:
private function setSSL(&$curl_opt, $verifySSL){
if($verifySSL){
$curl_opt[CURLOPT_SSL_VERIFYPEER] = true;
$curl_opt[CURLOPT_SSL_VERIFYHOST] = 2;
$curl_opt[CURLOPT_CAINFO] = dirname(dirname(__FILE__)) . "/OAuth/OAuth2/certs/cacert.pem"; //Pem certification Key Path
}
}
My $dataService is pretty much the same as yours.
you go to /vendor/quickbooks/v3-php-sdk/src/Core/HttpClients and edit CurlHttpClient.php
find
// $curl_opt[CURLOPT_CAINFO] = dirname(dirname(__FILE__)) . "/OAuth/OAuth2/certs/apiintuitcom.pem"; //Pem certification Key Path
change it to
' $curl_opt[CURLOPT_CAINFO] ="/home/folder/public_html/quickbooks_app/resources/cert/cacert.pem";
note: you can put your cacert.pem anywhere just change the address where you link it.
you can get cacert.pem on this site https://curl.haxx.se/docs/caextract.html

An error comes in the code while using HybridAuth as extension in yii framework-"undefined variable-user_profile"

I used HybridAuth extension for the purpose of signing in as facebook.
The code which is causing error in Hybrid Auth is as follows:
try
{
$path1 = Yii::getPathOfAlias('ext.HybridAuth');
require_once ($path1 . '/hybridauth-' . HybridAuthIdentity::VERSION . '/hybridauth/Hybrid/Auth.php');
$config = $path1 . '/hybridauth-' . HybridAuthIdentity::VERSION . '/hybridauth/config.php';
// initialize Hybrid_Auth with a given file
$hybridauth = new Hybrid_Auth( $config );
// try to authenticate with the selected provider
$adapter = $hybridauth->authenticate( $provider_name );
// then grab the user profile
$user_profile = $adapter->getUserProfile();
}
catch(Exception $e)
{
}

How to configure app.yaml to load google-api-php-client on app engine?

I have been trying to get the google api php client to work on app engine. After reading the app.yaml configuration resources provided by the documentation, I have still not been able to get this to work. My app.yaml has the google-api-php-client as it follows:
- url: /google-api-php-client/(.*?)/(.*?)/(.*)
script: google-api-php-client/\3/\2/\1.php
And, the structure of the folder is:
google-api-php-client->(some_folders)->(some_folders+files)->(some_files)
| level1 | | level2 | | level3 | | level4 |
I would like to have the configuration set so that I would be able to access the files in level 3 and level 4 and be able to do require_once calls just like these:
require_once ('/google-api-php-client/src/Google_Client.php');
require_once ('/google-api-php-client/src/contrib/Google_DriveService.php');
I am able to do these require_once calls on localhost but not when I deploy the files to app engine. The logs on app engine dashboard show this:
PHP Fatal error: require_once(): Failed opening required '/google-api-php-client/src/Google_Client.php' (include_path='.;/base/data/home/apps/s~...
I would appreciate any and all input.
Thanks!
EDIT: I am adding the code where I'm using require_once
require_once ('google-api-php-client/src/Google_Client.php');
require_once ('google-api-php-client/src/contrib/Google_DriveService.php');
session_start();
$client = new Google_Client();
$client->setApplicationName("Drive Demo");
$client->setClientId('****');
$client->setClientSecret('****');
$client->setRedirectUri('http://localhost:8080');
$client->setDeveloperKey('****');
$client->setScopes(array(
'https://www.googleapis.com/auth/drive',
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile'));
$client->setAccessType('offline');
$service = new Google_DriveService($client);
$fileId = '****';
function printFile($service, $fileId) {
try {
$file = $service->files->get($fileId);
print_r($file);
print "Title: " . $file->getTitle();
print "Description: " . $file->getDescription();
print "MIME type: " . $file->getMimeType();
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}
function retrieveAllFiles($service) {
$result = array();
$pageToken = NULL;
do {
try {
$parameters = array('q'=>'', 'maxResults'=> '25', 'fields'=>'items(title,description,mimeType)');
if ($pageToken) {
$parameters['pageToken'] = $pageToken;
}
$files = $service->files->listFiles($parameters);
$result = array_merge($result, $files->getItems());
$pageToken = $files->getNextPageToken();
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
$pageToken = NULL;
}
} while ($pageToken);
return $result;
}
if (!isset($_REQUEST['code']) && !isset($_SESSION['access_token'])) {
$authUrl = $client->createAuthUrl();
print("<a href='".$authUrl."'>Authorize me</a>");
}else {
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
}
if (isset($_SESSION['access_token'])) {
$client->setAccessToken($_SESSION['access_token']);
}
if ($client->getAccessToken()) {
$_SESSION['access_token'] = $client->getAccessToken();
}
$files = retrieveAllFiles($service);
foreach($files as $file){
//print_r($file);
print "Title: " . $file->getTitle().'<br/>';
print "Description: " . $file->getDescription().'<br/>';
print "MIME type: " . $file->getMimeType().'<br/>';
}
}
Update: Removed the '/' as per #Stuart's comment, which solved the issue.
You don't need to configure app.yaml in this case - as you don't want to route any requests directly to these scripts.
Just put the source code for google-api-php-client in the same directory as your app and deploy it using appcfg.py.
Check my article on configuring the client here.

Categories