I have created a simple project to test sending photo to telegram bot in php 7, but nothing sends after starting the bot, however this project runs in php 5.3!
Is there anything different in php 7 that I should use it?
$message = file_get_contents("php://input");
$result = json_decode($message,true);
$token = "My_Robot_token";
if($result['message']['text']=='/start')
{
$target_url = "https://api.telegram.org/bot".$token."/sendPhoto";
$file_path = "./img/img1.jpg";
$file_name_with_full_path = realpath($file_path);
$chat_id = $result['message']['chat']['id'];
$photo_send = array(
'chat_id' => $chat_id,
'photo' => '#'.$file_name_with_full_path,
'caption' => 'photo sent!'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $photo_send);
$result=curl_exec ($ch);
file_put_contents('res.txt', $ch);
}
define('API_KEY','API Token');
function bot($method,$datas=[]){
$url = "https://api.telegram.org/bot" . API_KEY . "/" . $method;
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_POSTFIELDS,$datas);
$res = curl_exec($ch);
if(curl_error($ch)){
var_dump(curl_error($ch));
}else{
return json_decode($res);
}
}
function sendphoto($ChatId, $photo, $caption){
bot('sendphoto',[
'chat_id'=>$ChatId,
'photo'=>$photo,
'caption'=>$caption
]);
}
$update = json_decode(file_get_contents('php://input'));
var_dump($update);
$message=$update->message;
$chat_id=$message->chat->id;
$text =$message->text;
if ($text=='/start'){
sendphoto($chat_id,"Your file_id","photo sent!"); // send photo by file_id
sendphoto($chat_id,new CURLFILE("file path"),"photo sent!"); // send photo by url
}
Related
I have to add more details in my question, so here is my try to get orders from my seller central account:
$host = 'sellingpartnerapi-na.amazon.com'; // is this the right URL for REST API to get Orders from my seller central account?
$accessKey = 'AK...YOX.........';
$secretKey = 'K...........';
$region = 'us-east-1';
$service = 'execute-api';
$requestUrl = 'https://sandbox.sellingpartnerapi-na.amazon.com/orders/v0/orders'; // '<full url>';
$uri = '/orders/v0/orders'; // '<method path>';
$httpRequestMethod = 'GET'; // '<http verb>';
I used this sample files: https://github.com/avi-wish/aws4-signature-php
unfortunately there is no example URL for variable $host
If I test the connection, this is my response:
Response:403
{
"errors": [
{
"message": "Access to requested resource is denied.",
"code": "Unauthorized",
"details": "Access token is missing in the request header."
}
]
}
I found a possible solution here:
https://github.com/amzn/selling-partner-api-docs/issues/52#issuecomment-713522351
but it's not working for me.
Is that necessary to create a IAM User before? Here is the way I created it:
https://github.com/amzn/selling-partner-api-docs/blob/main/guides/developer-guide/SellingPartnerApiDeveloperGuide.md#registering-your-selling-partner-api-application
I think a lot of people have the same problem. Hope someone can give me a hint.
after getting the access token, the curl return the error :
[message] => Access to requested resource is denied. [code] => MissingAuthenticationToken
function get_orders(){
$this->host = 'https://sellingpartnerapi-na.amazon.com/orders/v0/orders';
debug('>>get list of orders');
$data = "x-amz-date&access_token={$this->access_token}";
$curl = curl_init($this->host . '/orders/v0/orders');
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json;charset=UTF-8')
);
$result = curl_exec($curl);
curl_close($curl);
$obj = json_decode($result,true);
debug($obj);
}
Unfortunately you give very little information about what you want to do. There are two ways to authorize the SP-API that is set via the grant-type.
I suppose you want to authorize yourself and not a vendor.
Then you have to send your request to the following endpoint:
api.amazon.com/auth/o2/token
You have to specify the $host with api.amazon.com.
The request method will be POST.
You pass the parameters to the http Body:
grant_type, refresh_token, client_id, client_secret
Please have a look at the following link:
Connecting to the Selling Partner API
After you have done all this the same way, you will get the following answer:
{
"access_token":"Atza|IwEBIJR-9fxxxxxxxxxxxxxxxxxxxxxx",
"refresh_token":"Atzr|IwEBIxxxxxxxxxxxxxxxxxxxxxxxx",
"token_type":"bearer",
"expires_in":3600
}
Now you can use the access_token to sign your requests.
In the following, I also recommend you to use my post from another answer to sign a request and successfully send a request.
Answer: 64858116
public function GetAcessToken()
{
$RefeshToken = $this->RefreshToken;
$data = "grant_type=refresh_token"
."&refresh_token=". $RefeshToken
."&client_id=".$this->ClientID
."&client_secret=".$this->ClientSecret;
$curl = curl_init($this->UrlForAmazonToken);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type: application/x-www-form-urlencoded;charset=UTF-8')
);
$result = curl_exec($curl);
curl_close($curl);
$obj = json_decode($result,true);
$this->AccessToken = $obj['access_token'] ;
return $this->AccessToken;
}
It works for me.
I have implemented app on adionisjs framework and I want to deploy it on godaddy shared server, is there is any way to do that?
You cannot deploy nodejs app on a shared server directly, because the shared server is configured with server name not with the port, so instead, you can use PHP to run nodejs app.
<?php
//Choose JS file to run
$file = 'node_modules/jt-js-sample/index.js';
//Spawn node server in the background and return its pid
$pid = exec('PORT=49999 node/bin/node ' . $file . ' >/dev/null 2>&1 & echo $!');
//Wait for node to start up
usleep(500000);
//Connect to node server using cURL
$curl = curl_init('http://127.0.0.1:49999/');
curl_setopt($curl, CURLOPT_HEADER, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
//Get the full response
$resp = curl_exec($curl);
if($resp === false) {
//If couldn't connect, try increasing usleep
echo 'Error: ' . curl_error($curl);
} else {
//Split response headers and body
list($head, $body) = explode("\r\n\r\n", $resp, 2);
$headarr = explode("\n", $head);
//Print headers
foreach($headarr as $headval) {
header($headval);
}
//Print body
echo $body;
}
//Close connection
curl_close($curl);
//Close node server
exec('kill ' . $pid);
I'm trying to download a docusign envelope with curl. I'm accessing the envelope but the pdf won't show. I see a web page with symbols and can't save the pdf of the envelope. Any help appreciated.
require_once('rest/autoload.php');
$url = "https://demo.docusign.net/restapi/v2/login_information";
$header = "<DocuSignCredentials><Username>" .
$config['username_docusign'] . "</Username><Password>" .
$config['password_docusign'] . "</Password><IntegratorKey>" .
$config['api_firmadoc'] . "</IntegratorKey></DocuSignCredentials>";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("X-DocuSign-Authentication:
$header"));
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ( $status != 200 ) {
echo "error calling webservice, status is:" . $status;
exit(-1);
}
$response = json_decode($json_response, true);
$accountId = $response["loginAccounts"][0]["accountId"];
$baseUrl = $response["loginAccounts"][0]["baseUrl"];
curl_close($curl);
$curl = curl_init("https://demo.docusign.net/restapi/v2/accounts/1319127/envelopes/cc4aa62f-506c-4ee4-b6a3-dc9ae3e5fa14/documents/combined" );
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type: application/pdf',
'X-DocuSign-Authentication: { "Username":"****", "Password":"****",
"IntegratorKey":"*****" }' )
);
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
echo $json_response;
I expected a pdf but i receive a web page with symbols
You're using the obsolete legacy authentication. Much better idea would be to use OAuth.
You're not setting the Content-Type of your php page, instead you're setting the Content-Type of your request to DocuSign. (Which is also wrong, you should be setting the Accept header to application/pdf)
To set the Content-Type of your page, add the following at the top of your php script: header("Content-type:application/pdf"); See this SO answer.
Check out the PHP JWT and Authorization Code Grant examples for more info.
Thank you for integrating with DocuSign!
Instagram Documentation: https://instagram.com/developer/secure-api-requests/
Goal: Comply with the [now mandatory] Enforce Signed Requests feature using Instagram API.
Functional issue: without compliance IG Like limits are 30 per hour. Complying allows for 100 Likes per hour
Technical issue: The following error is returned when making a simple call to the API for media:
{"code": 403, "error_type": "OAuthForbiddenException", "error_message": "Invalid signed-request: Signature does not match"}
Instagram Client Set Up: Client ID, Client Secret, Redirect URI have all been verified to match those used in all portions of the PHP code. Both "Disable implicit OAuth" and "Enforce signed requests" are checked.
Code Explanation: Three distinct pieces of code are needed to create the handshake with IG: 1. Header 2. Access Token [i.e. "access_token"] 3. Call with Sig [i.e. "sig" - not to be confused with "signature"]. I have confirmed that the same client_id, client_secret and access_token are used throughout all pieces of code. NOTE: Parts 1 and 2 work[ed] fine prior to the mandatory compliance. They still work fine, but I only get 30 Likes/hr [i.e. the main functional issue]
Header Code:
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
$this->signature = $ip .'|'. hash_hmac('sha256', $ip, $this->settings['client_secret'], false);
Access Token Code, which returns successfully with an array similar to {"access_token":"11deadbee7.7dded5e.c0d656eead134218beef31a61b45e4d9",...}
$apiData = array(
'grant_type' => 'authorization_code',
'client_id' => $this->getApiKey(),
'client_secret' => $this->getApiSecret(),
'redirect_uri' => $this->getApiCallback(),
'code' => $code
);
$ch = curl_init();
$xHeaderFront = 'X-Insta-Forwarded-For:';
$xHeader = $xHeaderFront.$this->signature;
curl_setopt($ch, CURLOPT_URL, $apiHost);
curl_setopt($ch, CURLOPT_POST, count($apiData));
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($apiData));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$jsonData = curl_exec($ch);
curl_close($ch);
Call with Sig. This returns the error {"code": 403, "error_type": "OAuthForbiddenException", "error_message": "Invalid signed-request: Signature does not match"}:
$params = array(); //temporary to force a simple set of parameters
$params['count']=10;
$params['access_token'] = $this->getAccessToken(); //11deadbee7.7dded5e.c0d656eead134218beef31a61b45e4d9 masked, but kept for ease of comparison]
$endpoint = '/media/657988443280050001_25025320'; //temporary
$sig = $endpoint;
ksort($params);
foreach ($params as $key => $val) {
$sig .= "|$key=$val";
}
$enforcedSig = hash_hmac('sha256', $sig, $secret, false);
$apiCall = 'https://api.instagram.com/v1/media/657988443280050001_25025320/likes?sig='.$enforcedSig.'&count=10&access_token='.$params['access_token'];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiCall);
$xHeaderFront = 'X-Insta-Forwarded-For:';
$xHeader = $xHeaderFront.$this->signature;
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json',$xHeader));
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$jsonData = curl_exec($ch);
curl_close($ch);
Your $endpoint seems to be wrong.
Add "/likes".
$endpoint = '/media/657988443280050001_25025320/likes'; //temporary
Any means of specifying the IP address we want to connect to send that mail.?
Use PHP`s PEAR library class Mail. It's really straightforward.
Example:
(it's using remote SMTP server with SMTP AUTH, you don't need to use it)
<?php
require_once "Mail.php";
// mail data
$from = "You <sender#example.com>";
$to = "Her <recipient#example.com>";
$subject = "Hi!";
$body = "Hi,\n\nHow are you?";
// SMTP server info
$host = "mail.example.com";
$username = "smtp_username";
$password = "smtp_password";
// create mail headers
$headers = array(
'From' => $from,
'To' => $to,
'Subject' => $subject);
// create PEAR Mail object passing SMTP server info
$smtp = Mail::factory('smtp',
array (
'host' => $host,
'auth' => true,
'username' => $username,
'password' => $password));
// send the email
$mail = $smtp->send($to, $headers, $body);
// check the result
if (PEAR::isError($mail)) {
echo("<p>" . $mail->getMessage() . "</p>");
} else {
echo("<p>Message successfully sent!</p>");
}
?>