send message to telegram channel by bot - php

i make a telegram bot with telegram botfather and i make my bot as admin in my public telegram channel , now i want to send message in channel by bot, this is my code for this work :
send.php code is :
<?php
require('telegram-bot-api.php');
$token = '10**************************************jM';
$bot = new telegram_bot($token);
$to = '#myChannel';
$rs = $bot->send_message($to , 'test' , null, null);
print_r($rs);
?>
and telegram-bot-api.php code is :
<?php
class ReplyKeyboardMarkup{
public $keyboard;
public $resize_keyboard;
public $one_time_keyboard;
public $selective;
function __construct($resize_keyboard=FALSE, $one_time_keyboard = FALSE, $selective=FALSE){
$this->keyboard=array();
$this->keyboard[0]=array();
$this->resize_keyboard=$resize_keyboard;
$this->one_time_keyboard=$one_time_keyboard;
$this->selective=$selective;
}
public function add_option($option){
$this->keyboard = $option;
}
}
class ReplyKeyboardHide{
public $hide_keyboard;
public $selective;
function __construct($hide_keyboard=TRUE, $selective = FALSE){
$this->hide_keyboard=$hide_keyboard;
$this->selective=$selective;
}
}
class ForceReply{
public $force_reply;
public $selective;
function __construct($force_reply=TRUE, $selective = FALSE){
$this->force_reply=$force_reply;
$this->selective=$selective;
}
}
class telegram_bot{
private $token;
private function open_url($url, $method="GET", $data=null){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
if($method==="POST"){
if(isset($data)){
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
}
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
return curl_exec($ch);
}
private function control_api($action, $data=NULL){
$token = $this->token;
$response = json_decode($this->open_url("https://api.telegram.org/bot$token$action", "POST", $data));
return $response;
}
function __construct($token){
$this->token=$token;
}
public function status(){
$response = $this->control_api("/getme");
return($response);
}
public function get_updates(){
$response = $this->control_api("/getUpdates");
return($response);
}
public function send_action($to, $action){
$data = array();
$data["chat_id"]=$to;
$data["action"]=$action;
$response = $this->control_api("/sendChatAction", $data);
return $response;
}
public function send_message($to, $msg, $id_msg=null, $reply=null){
$data = array();
$data["chat_id"]=$to;
$data["text"]=$msg;
$data["disable_web_page_preview"]="true";
if(isset($id_msg))
$data["reply_to_message_id"]=$id_msg;
if(isset($reply))
$data["reply_markup"]=$reply;
$response = $this->control_api("/sendMessage", $data);
return $response;
}
public function send_location($to, $lat, $lon, $id_msg=null, $reply=null){
$data = array();
$data["chat_id"]=$to;
$data["latitude"]=$lat;
$data["longitude"]=$lon;
if(isset($id_msg))
$data["reply_to_message_id"]=$id_msg;
if(isset($reply))
$data["reply_markup"]=$reply;
$response = $this->control_api("/sendLocation", $data);
return $response;
}
public function send_sticker($to, $sticker, $id_msg=null, $reply=null){
$data = array();
$data["chat_id"]=$to;
if(file_exists($sticker))$sticker="#".$sticker;
$data["sticker"]=$sticker;
if(isset($id_msg))
$data["reply_to_message_id"]=$id_msg;
if(isset($reply))
$data["reply_markup"]=$reply;
$response = $this->control_api("/sendSticker", $data);
return $response;
}
public function send_video($to, $video, $id_msg=null, $reply=null){
$data = array();
$data["chat_id"]=$to;
if(file_exists($video))$video="#".$video;
$data["video"]=$video;
if(isset($id_msg))
$data["reply_to_message_id"]=$id_msg;
if(isset($reply))
$data["reply_markup"]=$reply;
$response = $this->control_api("/sendVideo", $data);
return $response;
}
public function send_photo($to, $photo, $caption, $id_msg=null, $reply=null){
$data = array();
$data["chat_id"]=$to;
if(file_exists($photo))$photo="#".$photo;
$data["photo"]=$photo;
if(isset($caption)){
$data["caption"]=$caption;
}
if(isset($id_msg)){
$data["reply_to_message_id"]=$id_msg;
}
if(isset($reply))
$data["reply_markup"]=$reply;
$response = $this->control_api("/sendPhoto", $data);
return $response;
}
public function send_audio($to, $audio, $id_msg=null, $reply=null){
$data = array();
$data["chat_id"]=$to;
if(file_exists($audio))$audio="#".$audio;
$data["audio"]=$audio;
if(isset($id_msg)){
$data["reply_to_message_id"]=$id_msg;
}
if(isset($reply))
$data["reply_markup"]=$reply;
$response = $this->control_api("/sendAudio", $data);
return $response;
}
public function send_document($to, $document, $id_msg=null, $reply=null){
$data = array();
$data["chat_id"]=$to;
if(file_exists($audio))$document="#".$audio;
$data["document"]=$document;
if(isset($id_msg)){
$data["reply_to_message_id"]=$id_msg;
}
if(isset($reply))
$data["reply_markup"]=$reply;
$response = $this->control_api("/sendDocument", $data);
return $response;
}
public function forward_message($to, $from, $msg_id){
$data = array();
$data["chat_id"]=$to;
$data["from_chat_id"]=$from;
$data["message_id"]=$msg_id;
$response = $this->control_api("/forwardMessage", $data);
return $response;
}
public function set_webhook($url=null){
$data = array();
$data["url"]=$url;
$response = $this->control_api("/setWebhook", $data);
return $response;
}
public function get_user_profile_photos($id_user, $offset=null, $limit=null){
$data = array();
$data["user_id"]=$id_user;
if(isset($offset)){
$data["offset"]=$offset;
}
if(isset($limit)){
$data["limit"]=$limit;
}
$response = $this->control_api("/getUserProfilePhotos", $data);
return $response;
}
public function read_post_message(){
return json_decode(file_get_contents('php://input'));
}
}
?>
but when run send.php not send message to channel but when i replace chat_id with private chat_id or group chat_id , this code done very cool and send a message to group or my contact
Excuse me for my English language , sory :)

solved , i tested with httpRequster plugin for send a post request to this link :
https://api.telegram.org/bot1*******************************M/sendMessage
and posted parameters is :
chat_id = #myChannel_username
text = myMessage
i don't know why not worked my old code but work this request :D
any way thanks.

Bot has to be an admin of the channel for it to be able to send messages. None of the clients can help you make a bot an admin of a channel. Are you sure your bot is an admin of the channel?
Source: https://core.telegram.org/bots/api-changelog#october-8-2015

curl has this problem for SSL.
add this code to Solve problem :
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

You can also use numeric chat_id of your channel/group/account to make bot sent messages.
Easy way to get chat_id is to forward any message from your channel to bot called #userinfobot.

Related

cURL code to unfollow instagram unfollowers

<?php
Class Instagram
{
public $username;
public $password;
private $guid;
private $my_uid;
private $userAgent = 'Instagram 6.21.2 Android (19/4.4.2; 480dpi; 1152x1920; Meizu; MX4; mx4; mt6595; en_US)';
private $instaSignature ='25eace5393646842f0d0c3fb2ac7d3cfa15c052436ee86b5406a8433f54d24a5';
private $instagramUrl = 'https://i.instagram.com/api/v1/';
public function Login($username, $password) {
$this->username = $username;
$this->password = $password;
$this->guid = $this->GenerateGuid();
$device_id = "android-" . $this->guid;
$data = '{"device_id":"'.$device_id.'","guid":"'.$this->guid.'","username":"'. $this->username.'","password":"'.$this->password.'","Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"}';
$sig = $this->GenerateSignature($data);
$data = 'signed_body='.$sig.'.'.urlencode($data).'&ig_sig_key_version=6';
$myid = $this->Request('accounts/login/', true, $data, false);
$decode = json_decode($myid[1], true);
$this->my_uid = $decode['logged_in_user']['pk'];
print_r($this->my_uid);
return $myid;
}
public function PostFollow($user_id) {
$device_id = "android-".$this->guid;
$data = '{"device_id":"'.$device_id.'","guid":"'. $this->guid .'","uid":"'.$this->my_uid.'","module_name":"feed_timeline","user_id":"'.$user_id.'","source_type":"5","filter_type":"0","extra":"{}","Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"}';
$sig = $this->GenerateSignature($data);
$new_data = 'signed_body='.$sig.'.'.urlencode($data).'&ig_sig_key_version=6';
return $this->Request('friendships/create/'.$user_id.'/', true, $new_data, true);
}
public function PostUnFollow($user_id) {
$device_id = "android-".$this->guid;
$data = '{"device_id":"'.$device_id.'","guid":"'. $this->guid .'","uid":"'.$this->my_uid.'","module_name":"feed_timeline","user_id":"'.$user_id.'","source_type":"5","filter_type":"0","extra":"{}","Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"}';
$sig = $this->GenerateSignature($data);
$new_data = 'signed_body='.$sig.'.'.urlencode($data).'&ig_sig_key_version=6';
return $this->Request('friendships/create/'.$user_id.'/', false, $new_data, true);
}
}
?>
return $this->Request('friendships/create/'.$user_id.'/', false, $new_data, true) - is this a correct cURL request?
Please refer to postfollow function (my follow code).
I want that the postUnfollow function will trigger auto unfollow users.
Please check my below code and check it's work or not
public function PostUnFollow($user_id,$username) {
$device_id = "android-".$this->guid;
$data = '{"device_id":"'.$device_id.'","guid":"'. $this->guid .'","uid":"'.$this->my_uid.'","module_name":"feed_timeline","user_id":"'.$user_id.'","source_type":"5","filter_type":"0","extra":"{}","Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"}';
$sig = $this->GenerateSignature($data);
$new_data = 'signed_body='.$sig.'.'.urlencode($data).'&ig_sig_key_version=6';
return $this->Request('friendships/destroy/'.$user_id.'/', true, $new_data, true,$username);
}

Shopify private app- php

updated shopify.php
<?php
include('shopify_api_config.php');
class ShopifyClient {
public $shop_domain;
private $token;
private $api_key;
private $secret;
private $last_response_headers = null;
public function __construct($shop_domain, $token, $api_key, $secret) {
$this->name = "ShopifyClient";
$this->shop_domain = 'https://#4ef34cd22b136c1a7b869e77c8ce8b3c:#fb2b17c283a27c65e4461d0ce8e5871b#discountshop-8.myshopify.com';
$this->token = $token;
$this->api_key = '4ef34cd22b136c1a7b869e77c8ce8b3c';
$this->secret = '28cdbeb0b925bba5b8c9a60cfbb8c3cb';
$client = new ShopifyClient($shop_domain, $token, $api_key, $secret);
}
// Get the URL required to request authorization
public function getAuthorizeUrl($scope, $redirect_url='') {
$url = "http://{$this->shop_domain}/admin/oauth/authorize?client_id={$this->api_key}&scope=" . urlencode($scope);
if ($redirect_url != '')
{
$url .= "&redirect_uri=" . urlencode($redirect_url);
}
return $url;
}
// Once the User has authorized the app, call this with the code to get the access token
public function getAccessToken($code) {
// POST to POST https://SHOP_NAME.myshopify.com/admin/oauth/access_token
$url = "https://{$this->shop_domain}/admin/oauth/access_token";
$payload = "client_id={$this->api_key}&client_secret={$this->secret}&code=$code";
$response = $this->curlHttpApiRequest('POST', $url, '', $payload, array());
$response = json_decode($response, true);
if (isset($response['access_token']))
return $response['access_token'];
return '';
}
public function callsMade()
{
return $this->shopApiCallLimitParam(0);
}
public function callLimit()
{
return $this->shopApiCallLimitParam(1);
}
public function callsLeft($response_headers)
{
return $this->callLimit() - $this->callsMade();
}
public function call($method, $path, $params=array())
{
$baseurl = "https://{$this->shop_domain}/";
$url = $baseurl.ltrim($path, '/');
$query = in_array($method, array('GET','DELETE')) ? $params : array();
$payload = in_array($method, array('POST','PUT')) ? stripslashes(json_encode($params)) : array();
$request_headers = in_array($method, array('POST','PUT')) ? array("Content-Type: application/json; charset=utf-8", 'Expect:') : array();
// add auth headers
$request_headers[] = 'X-Shopify-Access-Token: ' . $this->token;
$response = $this->curlHttpApiRequest($method, $url, $query, $payload, $request_headers);
$response = json_decode($response, true);
if (isset($response['errors']) or ($this->last_response_headers['http_status_code'] >= 400))
throw new ShopifyApiException($method, $path, $params, $this->last_response_headers, $response);
return (is_array($response) and (count($response) > 0)) ? array_shift($response) : $response;
}
public function validateSignature($query)
{
if(!is_array($query) || empty($query['signature']) || !is_string($query['signature']))
return false;
foreach($query as $k => $v) {
if($k == 'signature') continue;
$signature[] = $k . '=' . $v;
}
sort($signature);
$signature = md5($this->secret . implode('', $signature));
return $query['signature'] == $signature;
}
private function curlHttpApiRequest($method, $url, $query='', $payload='', $request_headers=array())
{
$url = $this->curlAppendQuery($url, $query);
$ch = curl_init($url);
$this->curlSetopts($ch, $method, $payload, $request_headers);
$response = curl_exec($ch);
$errno = curl_errno($ch);
$error = curl_error($ch);
curl_close($ch);
if ($errno) throw new ShopifyCurlException($error, $errno);
list($message_headers, $message_body) = preg_split("/\r\n\r\n|\n\n|\r\r/", $response, 2);
$this->last_response_headers = $this->curlParseHeaders($message_headers);
return $message_body;
}
private function curlAppendQuery($url, $query)
{
if (empty($query)) return $url;
if (is_array($query)) return "$url?".http_build_query($query);
else return "$url?$query";
}
private function curlSetopts($ch, $method, $payload, $request_headers)
{
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_USERAGENT, 'ohShopify-php-api-client');
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, $method);
if (!empty($request_headers)) curl_setopt($ch, CURLOPT_HTTPHEADER, $request_headers);
if ($method != 'GET' && !empty($payload))
{
if (is_array($payload)) $payload = http_build_query($payload);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $payload);
}
}
private function curlParseHeaders($message_headers)
{
$header_lines = preg_split("/\r\n|\n|\r/", $message_headers);
$headers = array();
list(, $headers['http_status_code'], $headers['http_status_message']) = explode(' ', trim(array_shift($header_lines)), 3);
foreach ($header_lines as $header_line)
{
list($name, $value) = explode(':', $header_line, 2);
$name = strtolower($name);
$headers[$name] = trim($value);
}
return $headers;
}
private function shopApiCallLimitParam($index)
{
if ($this->last_response_headers == null)
{
throw new Exception('Cannot be called before an API call.');
}
$params = explode('/', $this->last_response_headers['http_x_shopify_shop_api_call_limit']);
return (int) $params[$index];
}
}
class ShopifyCurlException extends Exception { }
class ShopifyApiException extends Exception
{
protected $method;
protected $path;
protected $params;
protected $response_headers;
protected $response;
function __construct($method, $path, $params, $response_headers, $response)
{
$this->method = $method;
$this->path = $path;
$this->params = $params;
$this->response_headers = $response_headers;
$this->response = $response;
parent::__construct($response_headers['http_status_message'], $response_headers['http_status_code']);
}
function getMethod() { return $this->method; }
function getPath() { return $this->path; }
function getParams() { return $this->params; }
function getResponseHeaders() { return $this->response_headers; }
function getResponse() { return $this->response; }
}
?>
I installed one private app in my shopify store for download csv file, after installed, when click download button, it will display like
Fatal error: Uncaught exception 'ShopifyCurlException' with message 'Could not
resolve host: http:; Host not found' in C:\xampp\htdocs\cat\lib\shopify.php:102
Stack trace: #0 C:\xampp\htdocs\cat\lib\shopify.php(67): ShopifyClient->curlHttpApiRequest('GET', 'https://http://...', Array, Array, Array)
#1 C:\xampp\htdocs\cat\index-oauth.php(26): ShopifyClient->call('GET', 'admin/orders.js...', Array)
#2 {main} thrown in C:\xampp\htdocs\cat\lib\shopify.php on line 102.
I dont know how to fix. If anybody know, please help.
Thank you!.
I had the same problem. Try this.
In your constructor pass the following argument as the $shop_domain.
https:// #apikey:#password#hostname
Replace #apiKey, #password and hostname with your values. Also leave '#' in hostname.
I.e. #yourshop.com
$shop_domain = 'https://#apikey:#password#hostname';
$token = 'your token';
$key = 'your key';
$secret = 'your secret';
$client = new ShopifyClient($shop_domain, $token, $api_key, $secret);

DialMyCalls where do I put the API Key

I'm trying to pull data from the DialMyCalls database and add data to it. They sent me some code and I have found my API key but I don't know how to connect it all. I uploaded the PHP code onto my server and tried running it but I get no results because I'm not exactly sure what to edit. I know I need to edit the "null" areas I presume but I'm not entirely sure. Any help is welcomed.
here is the code they sent me, so if you could tell me what to edit to pull information from their database I'd be grateful. Thanks.
<?php
class RestRequest
{
protected $url;
protected $verb;
protected $requestBody;
protected $requestLength;
protected $apikey;
protected $acceptType;
var $responseBody;
protected $responseInfo;
public function __construct ($apikey = null) {
$this->url = null;
$this->verb = null;
$this->requestBody = null;
$this->requestLength = 0;
$this->apikey = $apikey;
$this->acceptType = 'application/json';
$this->responseBody = null;
$this->responseInfo = null;
}
public function flush ()
{
$this->requestBody = null;
$this->requestLength = 0;
$this->verb = 'POST';
$this->responseBody = null;
$this->responseInfo = null;
}
public function execute ($url = null, $verb = 'POST', $requestBody = null) {
$ch = curl_init();
$this->url = "https://www.dialmycalls.com/api".$url;
$this->verb = $verb;
$this->requestBody = $requestBody;
try
{
switch (strtoupper($this->verb))
{
case 'POST':
$this->doExecute($ch);
break;
default:
throw new InvalidArgumentException('Current verb (' . $this->verb . ') is an invalid REST verb.');
}
}
catch (InvalidArgumentException $e)
{
curl_close($ch);
throw $e;
}
catch (Exception $e)
{
curl_close($ch);
throw $e;
}
}
protected function doExecute (&$curlHandle) {
curl_setopt($curlHandle, CURLOPT_POST, 1);
$this->requestBody["apikey"] = $this->apikey;
curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $this->requestBody);
// curl_setopt($curlHandle, CURLOPT_TIMEOUT, 60);
curl_setopt($curlHandle, CURLOPT_URL, $this->url);
curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curlHandle, CURLOPT_VERBOSE, 0);
curl_setopt($curlHandle, CURLOPT_HTTPHEADER, array ('Accept: ' . $this->acceptType,'Expect:'));
$this->responseBody = curl_exec($curlHandle);
$this->responseInfo = curl_getinfo($curlHandle);
curl_close($curlHandle);
}
}
?>
Thanks again for any help,
Matt
From what it looks like, you would just throw it in the constructor.
Example:
<?php
$rest = new RestRequest("yourAPIkey");
?>
Then you can do the rest. I noticed this because in the constructor it has
public function __construct ($apikey = null) {
Which means when you open the new class whatever variable is in the function __construct is what you would send in the new class.
Hope this helps.

Call to undefined function that isn't undefined?

So, when I try and run this line of code, I'm getting the following error:
Fatal error: Call to undefined function curl_http_api_request_() in /Applications/XAMPP/xamppfiles/htdocs/CI/application/libraries/Shopify.php on line 58
Where line 58 is specifically this line:
$response = curl_http_api_request_($method, $url, $query, $payload, $request_headers, $response_headers);
I'm not really sure why it can't call the second function. The code is below. I've got no clue and am at a loss as to what the issue is.
class Shopify
{
public $_api_key;
public $_shared_secret;
public $CI; // To hold the CI superglobal
public function __construct ()
{
$this->_assign_libraries(); // Loads the CI superglobal and loads the config into it
// Get values from the CI config
$this->_api_key = $this->CI->config->item('api_key', 'shopify');
$this->_shared_secret = $this->CI->config->item('shared_secret', 'shopify');
}
public function shopify_app_install_url($shop_domain)
{
return "http://$shop_domain/admin/api/auth?api_key=". $this->_api_key;
}
public function shopify_is_app_installed($shop, $t, $timestamp, $signature)
{
return (md5($this->_shared_secret . "shop={$shop}t={$t}timestamp={$timestamp}") === $signature);
}
public function shopify_api_client($shops_myshopify_domain, $shops_token, $private_app=false)
{
$password = $private_app ? $this->_shared_secret : md5($this->_shared_secret.$shops_token);
$baseurl = "https://" . $this->_api_key . ":$password#$shops_myshopify_domain/";
return function ($method, $path, $params=array(), &$response_headers=array()) use ($baseurl)
{
$url = $baseurl.ltrim($path, '/');
$query = in_array($method, array('GET','DELETE')) ? $params : array();
$payload = in_array($method, array('POST','PUT')) ? stripslashes(json_encode($params)) : array();
$request_headers = in_array($method, array('POST','PUT')) ? array("Content-Type: application/json; charset=utf-8", 'Expect:') : array();
$response = curl_http_api_request_($method, $url, $query, $payload, $request_headers, $response_headers);
$response = json_decode($response, true);
if (isset($response['errors']) or ($response_headers['http_status_code'] >= 400))
throw new ShopifyApiException(compact('method', 'path', 'params', 'response_headers', 'response', 'shops_myshopify_domain', 'shops_token'));
return (is_array($response) and (count($response) > 0)) ? array_shift($response) : $response;
};
}
public function curl_http_api_request_($method, $url, $query='', $payload='', $request_headers=array(), &$response_headers=array())
{
$url = curl_append_query_($url, $query);
$ch = curl_init($url);
curl_setopts_($ch, $method, $payload, $request_headers);
$response = curl_exec($ch);
$errno = curl_errno($ch);
$error = curl_error($ch);
curl_close($ch);
if ($errno) throw new ShopifyCurlException($error, $errno);
list($message_headers, $message_body) = preg_split("/\r\n\r\n|\n\n|\r\r/", $response, 2);
$response_headers = $this->curl_parse_headers_($message_headers);
return $message_body;
}
private function curl_append_query_($url, $query)
{
if (empty($query)) return $url;
if (is_array($query)) return "$url?".http_build_query($query);
else return "$url?$query";
}
private function curl_setopts_($ch, $method, $payload, $request_headers)
{
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_USERAGENT, 'HAC');
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
if ('GET' == $method)
{
curl_setopt($ch, CURLOPT_HTTPGET, true);
}
else
{
curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, $method);
if (!empty($request_headers)) curl_setopt($ch, CURLOPT_HTTPHEADER, $request_headers);
if (!empty($payload))
{
if (is_array($payload)) $payload = http_build_query($payload);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $payload);
}
}
}
private function curl_parse_headers_($message_headers)
{
$header_lines = preg_split("/\r\n|\n|\r/", $message_headers);
$headers = array();
list(, $headers['http_status_code'], $headers['http_status_message']) = explode(' ', trim(array_shift($header_lines)), 3);
foreach ($header_lines as $header_line)
{
list($name, $value) = explode(':', $header_line, 2);
$name = strtolower($name);
$headers[$name] = trim($value);
}
return $headers;
}
public function shopify_calls_made($response_headers)
{
return shopify_shop_api_call_limit_param_(0, $response_headers);
}
public function shopify_call_limit($response_headers)
{
return shopify_shop_api_call_limit_param_(1, $response_headers);
}
public function shopify_calls_left($response_headers)
{
return shopify_call_limit($response_headers) - shopify_calls_made($response_headers);
}
private function shopify_shop_api_call_limit_param_($index, $response_headers)
{
$params = explode('/', $response_headers['http_x_shopify_shop_api_call_limit']);
return (int) $params[$index];
}
/**
* Shopify::_assign_libraries()
*
* Grab everything from the CI superobject that we need
*/
public function _assign_libraries()
{
$this->CI =& get_instance();
$this->CI->load->config('shopify', TRUE);
return;
}
UPDATE:
This whole line is started off by me calling this line of code:
$shopify = $this->shopify->shopify_api_client($shops_myshopify_domain, $shops_token);
I have also updated the code above to include the entire file.
You can achieve it only by passing $this as object to anonymous function, as it has its own context:
class example {
public function trigger() {
$func = $this->func();
$func($this);
}
public function func() {
return function($obj) {
$obj->inner();
};
}
public function inner() {
die('inside inner');
}
}
$obj = new example();
$obj->trigger();
EDIT: So in response to your problem:
Change this line:
return function ($method, $path, $params=array(), &$response_headers=array()) use ($baseurl)
into this:
return function ($instance, $method, $path, $params=array(), &$response_headers=array()) use ($baseurl)
Inside anonymous function change this line:
$response = curl_http_api_request_($method, $url, $query, $payload, $request_headers, $response_headers);
into this:
$response = $instance->curl_http_api_request_($method, $url, $query, $payload, $request_headers, $response_headers);
Now shopify_api_client function will return you this ANONYMOUS FUNCTION with no error:
$shopify = $this->shopify->shopify_api_client($shops_myshopify_domain, $shops_token);
You need to call this function in this way:
$shopify($this->shopify, ... AND HERE THE REST OF ARGUMENTS WHICH ANONYMOUS FUNCTION REQUIRE ...);
Is it clearer now? I have never used shopify, but general way it should work is as I wrote.
If your accessing a method from outside the class you need to state it, if your accessing the method from within the class you need use $this->methodname()
<?php
class shopify_api{
...
...
...
public function curl_http_api_request_($method, $url, $query='', $payload='', $request_headers=array(), &$response_headers=array())
{
$url = curl_append_query_($url, $query);
$ch = curl_init($url);
curl_setopts_($ch, $method, $payload, $request_headers);
$response = curl_exec($ch);
$errno = curl_errno($ch);
$error = curl_error($ch);
curl_close($ch);
if ($errno) throw new ShopifyCurlException($error, $errno);
list($message_headers, $message_body) = preg_split("/\r\n\r\n|\n\n|\r\r/", $response, 2);
$response_headers = $this->curl_parse_headers_($message_headers);
return $message_body;
}
}
$shopify = new shopify_api();
//--------V
$response=$shopify->curl_http_api_request_();
?>
Since you have updated your question have you tried changing:
$shopify = $this->shopify->shopify_api_client($shops_myshopify_domain, $shops_token);
too: (as it seems your adding extra shopify property, i cant see from yourcode where you have set & injected your methods to it)
$shopify = $this->shopify_api_client($shops_myshopify_domain, $shops_token);

Has anyone worked with this Highrise API PHP Wrapper library? I need help authenticating

So I downloaded a wrapper class from this github link:
https://github.com/ignaciovazquez/Highrise-PHP-Api
and I'm just trying to get any response whatsoever. So far, I can't even authenticate with my credentials so I was wondering if any who has used the API could help me.
I tried running one of the test files on Terminal with no arguments and this is what it told me:
Usage: php users.test.php [account-name] [access-token]
Alright, so then decided to get my credentials. So this is what I understand, and, please, correct if I'm wrong:
the account-name is that part that goes in the url to your highrise account. So if your url is:
https://exampleaccount.highrisehq.com/
then your account name is: "exampleaccount"
and your access token is your authentication token that you can find by going clicking on My info > API token inside your Highrise account.
Is that right?
Well anyways, I enter this info and script terminates with a fatal error and this message:
Fatal error: Uncaught exception 'Exception' with message 'API for User returned Status Code: 0 Expected Code: 200' in /Users/me/Sites/sandbox/PHP/highrise_api_class/lib/HighriseAPI.class.php:137
Stack trace:
#0 /Users/me/Sites/sandbox/PHP/highrise_api_class/lib/HighriseAPI.class.php(166): HighriseAPI->checkForErrors('User')
#1 /Users/me/Sites/sandbox/PHP/highrise_api_class/test/users.test.php(13): HighriseAPI->findMe()
#2 {main}
thrown in /Users/me/Sites/sandbox/PHP/highrise_api_class/lib/HighriseAPI.class.php on line 137
I'm complete n00b and I don't really understand what it's saying so I was wondering if any could help. It would be greatly appreciated.
The source of the test script (users.test.php) is:
<?php
require_once("../lib/HighriseAPI.class.php");
if (count($argv) != 3)
die("Usage: php users.test.php [account-name] [access-token]\n");
$hr = new HighriseAPI();
$hr->debug = false;
$hr->setAccount($argv[1]);
$hr->setToken($argv[2]);
print "Finding my user...\n";
$user = $hr->findMe();
print_r($user);
print "Finding all users...\n";
$users = $hr->findAllUsers();
print_r($users);
?>
and the source to the Highrise API wrapper file (Highrise.API.class) is:
<?php
/*
* http://developer.37signals.com/highrise/people
*
* TODO LIST:
* Add Tasks support
* Get comments for Notes / Emails
* findPeopleByTagName
* Get Company Name, etc proxy
* Convenience methods for saving Notes $person->saveNotes() to check if notes were modified, etc.
* Add Tags to Person
*/
class HighriseAPI
{
public $account;
public $token;
protected $curl;
public $debug;
public function __construct()
{
$this->curl = curl_init();
curl_setopt($this->curl,CURLOPT_RETURNTRANSFER,true);
curl_setopt($this->curl, CURLOPT_HTTPHEADER, array('Accept: application/xml', 'Content-Type: application/xml'));
// curl_setopt($curl,CURLOPT_POST,true);
curl_setopt($this->curl,CURLOPT_SSL_VERIFYPEER,0);
curl_setopt($this->curl,CURLOPT_SSL_VERIFYHOST,0);
}
public function setAccount($account)
{
$this->account = $account;
}
public function setToken($token)
{
$this->token = $token;
curl_setopt($this->curl,CURLOPT_USERPWD,$this->token.':x');
}
protected function postDataWithVerb($path, $request_body, $verb = "POST")
{
$this->curl = curl_init();
$url = "https://" . $this->account . ".highrisehq.com" . $path;
if ($this->debug)
print "postDataWithVerb $verb $url ============================\n";
curl_setopt($this->curl, CURLOPT_URL,$url);
curl_setopt($this->curl, CURLOPT_POSTFIELDS, $request_body);
if ($this->debug == true)
curl_setopt($this->curl, CURLOPT_VERBOSE, true);
curl_setopt($this->curl, CURLOPT_HTTPHEADER, array('Accept: application/xml', 'Content-Type: application/xml'));
curl_setopt($this->curl, CURLOPT_USERPWD,$this->token.':x');
curl_setopt($this->curl, CURLOPT_SSL_VERIFYPEER,0);
curl_setopt($this->curl, CURLOPT_SSL_VERIFYHOST,0);
curl_setopt($this->curl, CURLOPT_RETURNTRANSFER,true);
if ($verb != "POST")
curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, $verb);
else
curl_setopt($this->curl, CURLOPT_POST, true);
$ret = curl_exec($this->curl);
if ($this->debug == true)
print "Begin Request Body ============================\n" . $request_body . "End Request Body ==============================\n";
curl_setopt($this->curl,CURLOPT_HTTPGET, true);
return $ret;
}
protected function getURL($path)
{
curl_setopt($this->curl, CURLOPT_HTTPHEADER, array('Accept: application/xml', 'Content-Type: application/xml'));
curl_setopt($this->curl, CURLOPT_USERPWD,$this->token.':x');
curl_setopt($this->curl, CURLOPT_SSL_VERIFYPEER,0);
curl_setopt($this->curl, CURLOPT_SSL_VERIFYHOST,0);
curl_setopt($this->curl, CURLOPT_RETURNTRANSFER,true);
$url = "https://" . $this->account . ".highrisehq.com" . $path;
if ($this->debug == true)
curl_setopt($this->curl, CURLOPT_VERBOSE, true);
curl_setopt($this->curl,CURLOPT_URL,$url);
$response = curl_exec($this->curl);
if ($this->debug == true)
print "Response: =============\n" . $response . "============\n";
return $response;
}
protected function getLastReturnStatus()
{
return curl_getinfo($this->curl, CURLINFO_HTTP_CODE);
}
protected function getXMLObjectForUrl($url)
{
$xml = $this->getURL($url);
$xml_object = simplexml_load_string($xml);
return $xml_object;
}
protected function checkForErrors($type, $expected_status_codes = 200)
{
if (!is_array($expected_status_codes))
$expected_status_codes = array($expected_status_codes);
if (!in_array($this->getLastReturnStatus(), $expected_status_codes))
{
switch($this->getLastReturnStatus())
{
case 404:
throw new Exception("$type not found");
break;
case 403:
throw new Exception("Access denied to $type resource");
break;
case 507:
throw new Exception("Cannot create $type: Insufficient storage in your Highrise Account");
break;
default:
throw new Exception("API for $type returned Status Code: " . $this->getLastReturnStatus() . " Expected Code: " . implode(",", $expected_status_codes));
break;
}
}
}
/* Users */
public function findAllUsers()
{
$xml = $this->getUrl("/users.xml");
$this->checkForErrors("User");
$xml_object = simplexml_load_string($xml);
$ret = array();
foreach($xml_object->user as $xml_user)
{
$user = new HighriseUser();
$user->loadFromXMLObject($xml_user);
$ret[] = $user;
}
return $ret;
}
public function findMe()
{
$xml = $this->getUrl("/me.xml");
$this->checkForErrors("User");
$xml_obj = simplexml_load_string($xml);
$user = new HighriseUser();
$user->loadFromXMLObject($xml_obj);
return $user;
}
/* Tasks */
public function findCompletedTasks()
{
$xml = $this->getUrl("/tasks/completed.xml");
$this->checkForErrors("Tasks");
return $this->parseTasks($xml);
}
public function findAssignedTasks()
{
$xml = $this->getUrl("/tasks/assigned.xml");
$this->checkForErrors("Tasks");
return $this->parseTasks($xml);
}
public function findUpcomingTasks()
{
$xml = $this->getUrl("/tasks/upcoming.xml");
$this->checkForErrors("Tasks");
return $this->parseTasks($xml);
}
private function parseTasks($xml)
{
$xml_object = simplexml_load_string($xml);
$ret = array();
foreach($xml_object->task as $xml_task)
{
$task = new HighriseTask($this);
$task->loadFromXMLObject($xml_task);
$ret[] = $task;
}
return $ret;
}
public function findTaskById($id)
{
$xml = $this->getURL("/tasks/$id.xml");
$this->checkForErrors("Task");
$task_xml = simplexml_load_string($xml);
$task = new HighriseTask($this);
$task->loadFromXMLObject($task_xml);
return $task;
}
/* Notes & Emails */
public function findEmailById($id)
{
$xml = $this->getURL("/emails/$id.xml");
$this->checkForErrors("Email");
$email_xml = simplexml_load_string($xml);
$email = new HighriseEmail($this);
$email->loadFromXMLObject($email_xml);
return $email;
}
public function findNoteById($id)
{
$xml = $this->getURL("/notes/$id.xml");
$this->checkForErrors("Note");
$note_xml = simplexml_load_string($xml);
$note = new HighriseNote($this);
$note->loadFromXMLObject($note_xml);
return $note;
}
public function findPersonById($id)
{
$xml = $this->getURL("/people/$id.xml");
$this->checkForErrors("Person");
$xml_object = simplexml_load_string($xml);
$person = new HighrisePerson($this);
$person->loadFromXMLObject($xml_object);
return $person;
}
public function findAllTags()
{
$xml = $this->getUrl("/tags.xml");
$this->checkForErrors("Tags");
$xml_object = simplexml_load_string($xml);
$ret = array();
foreach($xml_object->tag as $tag)
{
$ret[(string)$tag->name] = new HighriseTag((string)$tag->id, (string)$tag->name);
}
return $ret;
}
public function findAllPeople()
{
return $this->parsePeopleListing("/people.xml");
}
public function findPeopleByTagName($tag_name)
{
$tags = $this->findAllTags();
foreach($tags as $tag)
{
if ($tag->name == $tag_name)
$tag_id = $tag->id;
}
if (!isset($tag_id))
throw new Excepcion("Tag $tag_name not found");
return $this->findPeopleByTagId($tag_id);
}
public function findPeopleByTagId($tag_id)
{
$url = "/people.xml?tag_id=" . $tag_id;
$people = $this->parsePeopleListing($url);
return $people;
}
public function findPeopleByEmail($email)
{
return $this->findPeopleBySearchCriteria(array("email"=>$email));
}
public function findPeopleByTitle($title)
{
$url = "/people.xml?title=" . urlencode($title);
$people = $this->parsePeopleListing($url);
return $people;
}
public function findPeopleByCompanyId($company_id)
{
$url = "/companies/" . urlencode($company_id) . "/people.xml";
$people = $this->parsePeopleListing($url);
return $people;
}
public function findPeopleBySearchTerm($search_term)
{
$url = "/people/search.xml?term=" . urlencode($search_term);
$people = $this->parsePeopleListing($url, 25);
return $people;
}
public function findPeopleBySearchCriteria($search_criteria)
{
$url = "/people/search.xml";
$sep = "?";
foreach($search_criteria as $criteria=>$value)
{
$url .= $sep . "criteria[" . urlencode($criteria) . "]=" . urlencode($value);
$sep = "&";
}
$people = $this->parsePeopleListing($url, 25);
return $people;
}
public function findPeopleSinceTime($time)
{
$url = "/people/search.xml?since=" . urlencode($time);
$people = $this->parsePeopleListing($url);
return $people;
}
public function parsePeopleListing($url, $paging_results = 500)
{
if (strstr($url, "?"))
$sep = "&";
else
$sep = "?";
$offset = 0;
$return = array();
while(true) // pagination
{
$xml_url = $url . $sep . "n=$offset";
// print $xml_url;
$xml = $this->getUrl($xml_url);
$this->checkForErrors("People");
$xml_object = simplexml_load_string($xml);
foreach($xml_object->person as $xml_person)
{
// print_r($xml_person);
$person = new HighrisePerson($this);
$person->loadFromXMLObject($xml_person);
$return[] = $person;
}
if (count($xml_object) != $paging_results)
break;
$offset += $paging_results;
}
return $return;
}
}
Sorry it's such a long file but if it helps, then so be it.
EDIT: So I guess I got it to work. I should've said that I was trying to test this library out on my local server and for some reason it would keep failing but when I moved the script to my development server on Rackspace cloud then it would work. This just puzzles me. Both servers have support for PHP curl so I can't really understand where the problem is.
EDIT: I'm not sure what the difference between the two server configurations could be but anyways here's a couple of screenshots from my phpinfo function output from both servers of my curl configuration:
Localhost server:
and the rackspace cloud server:
The fork of the API at...
https://github.com/AppSaloon/Highrise-PHP-Api
...seems more developed and better maintained.
Not so much as to provide an answer, but more a better starting point.
Ah, since there is really no HTTP error code 0 I expect that your request isn't being made to Highrise's website, or you are not correctly passing in the account name and token to the class. Can you include the source of your users.test.php class?
EDIT: tested the class and your code, and it works for me. You probably either copied the library file wrong or have your token copied wrong.
I had the same issue. I definitely had the wrong account. I had https://foo.highrisehq.com instead of just foo.

Categories