I've created two method in my controller in Laravel to fetch data from another website using PHP CURL and pass to view.
I will used httpData method for initial ID and URL and getHttpCode method to get HTTP_code to find any errors will happen when I fetch data from another website But I don't much understand about this below code performance and how can I testing In PHPstrom to make sure with performance
Here is my function
private function httpData($url =null, $id = null)
{
if($id){
$url = 'http://assignment.gae.golgek.mobi/api/v1/items/'.$id;
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLINFO_PRETRANSFER_TIME, 30);
curl_setopt($ch, CURLINFO_HTTP_CODE, true);
curl_setopt($ch, CURLOPT_PRIVATE, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
if (!$executed = curl_exec($ch)) {
$res = $executed;
$data = false;
curl_close($ch);
} else {
if ($this->http_code = $this->getHttpCode(curl_getinfo($ch))) {
$res = $this->http_code;
$data = $executed;
} else {
$res = false;
}
}
return ['s_respond' => $res, 'data' => $executed];
}
private function getHttpCode($http)
{
if (is_array($http)) {
if (!empty($http['http_code'] || $http['http_code'] != 0)) {
return $http['http_code'];
} else {
return false;
}
} else {
return false;
}
}
And I will call this method as below
public function sendData()
{
$url = 'website/api/v1/products';
$data = $this->httpData($url);
return view('products.list', ['data'=>$data]);
}
Thanks for help
I suggest you to addopt the 'early return pattern'.
I did a rewrite in you getHttpCode, it seems more clear to me:
private function getHttpCode($http)
{
if ( !is_array($http)
|| empty($http['http_code'])
|| $http['http_code'] === 0)
{
return false;
}
return $http['http_code'];
}
Related
Im using custom payment method for payments with credit and debit cards in OpenCart 2.1.0.1 but I am facing a problem. When I make a successful purchase and I redirected to succsess.tpl page, after that when i continue shopping (in the same browser session) and make a second successful purchase - its not recording as new order with new order id! I will attach my controller, which can be the code for clearing session?
class ControllerPaymentFibank extends Controller {
public function index() {
$this->load->model('checkout/order');
$this->language->load('payment/fibank');
$data['button_confirm'] = $this->language->get('button_confirm');
if (!$this->config->get('fibank_test')) {
$communication_url = "https://mdpay.fibank.bg:9443/ecomm/MerchantHandler";
$payment_url = "https://mdpay.fibank.bg/ecomm/ClientHandler";
} else {
$communication_url = "https://mdpay-test.fibank.bg:9443/ecomm/MerchantHandler";
$payment_url = "https://mdpay-test.fibank.bg/ecomm/ClientHandler";
}
$order_info = $this->model_checkout_order->getOrder($this->session->data['order_id']);
if ($order_info) {
$data['action'] = $this->session->data['order_id'];
if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/payment/fibank.tpl')) {
return $this->load->view($this->config->get('config_template') . '/template/payment/fibank.tpl', $data);
} else {
return $this->load->view('default/template/payment/fibank.tpl', $data);
}
}
}
public function make_payment() {
$this->load->model('checkout/order');
$this->language->load('payment/fibank');
$data['button_confirm'] = $this->language->get('button_confirm');
if (!$this->config->get('fibank_test')) {
$communication_url = "https://mdpay.fibank.bg:9443/ecomm/MerchantHandler";
$payment_url = "https://mdpay.fibank.bg/ecomm/ClientHandler";
} else {
$communication_url = "https://mdpay-test.fibank.bg:9443/ecomm/MerchantHandler";
$payment_url = "https://mdpay-test.fibank.bg/ecomm/ClientHandler";
}
$order_info = $this->model_checkout_order->getOrder($this->session->data['order_id']);
if ($order_info) {
$ip = $this->get_client_ip();
$amount = $this->currency->format($order_info['total'], 'BGN', '', false);
$amount *= 100;
$post_request="command=v&amount=".$amount."¤cy=975&client_ip_addr=".$ip."&description=".$this->session->data['order_id']."&msg_type=SMS";
$res = $this->execute_fibank_query($communication_url, $post_request);
$result = str_replace("TRANSACTION_ID: ", "", $res);
$this->model_checkout_order->addOrderHistory($this->session->data['order_id'], '1', $result);
$_SESSION['order_id']=$this->session->data['order_id'];
header("location:".$payment_url."?trans_id=".rawurlencode($result));
}
exit();
}
public function callback() {
if (isset($this->request->post['trans_id'])) {
$tranz_id = $this->request->post['trans_id'];
} else {
$tranz_id = '';
}
if (!$this->config->get('fibank_test')) {
$communication_url = "https://mdpay.fibank.bg:9443/ecomm/MerchantHandler";
$payment_url = "https://mdpay.fibank.bg/ecomm/ClientHandler";
} else {
$communication_url = "https://mdpay-test.fibank.bg:9443/ecomm/MerchantHandler";
$payment_url = "https://mdpay-test.fibank.bg/ecomm/ClientHandler";
}
if ($tranz_id!="" && $_SESSION['order_id']>0) {
$ip = $this->get_client_ip();
$request="command=c&trans_id=".rawurlencode($tranz_id)."&client_ip_addr=".$ip;
$result = $this->execute_fibank_query($communication_url, $request);
$res = explode("\n", $result);
$fibank_info = str_replace("RESULT: ", "", $res[0]);
$this->load->model('checkout/order');
$order_info = $this->model_checkout_order->getOrder($_SESSION['order_id']);
if ($fibank_info=="OK") {
$order_status = $this->config->get('fibank_order_status_id');
$this->model_checkout_order->addOrderHistory($_SESSION['order_id'], $order_status, $result);
$this->cart->clear();
header("location:/successfull-transaction");
}
else{
$order_status = $this->config->get('fibank_order_status_denied_id');
$this->model_checkout_order->addOrderHistory($_SESSION['order_id'], $order_status, $result);
$this->cart->clear();
header("location:/transaction-error");
}
}
}
function execute_fibank_query($url, $request){
// debug
$fp = fopen(dirname(__FILE__).'/errorlog.txt', 'w');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
// debug
curl_setopt($ch, CURLOPT_STDERR, $fp);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_SSLCERT, $this->config->get('fibank_certificate_path'));
curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');
curl_setopt($ch, CURLOPT_SSLCERTPASSWD, $this->config->get('fibank_certificate_pass'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
$result = curl_exec($ch);
return $result;
}
function get_client_ip(){
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
}
else {
$ip = $_SERVER['REMOTE_ADDR'];
}
return $ip;
}
If you look at the file catalog/controller/checkout/success.php you will see the standard process that follows a successful order. If you've modified this at all, it's possible OpenCart isn't unsetting the session data. In that file, the controller checks if there is data set in the session:
if (isset($this->session->data['order_id'])) {
If it's true, the cart will be cleared with this line:
$this->cart->clear();
And, following the UserActivity logging, the session data is unset with this code:
unset($this->session->data['shipping_method']);
unset($this->session->data['shipping_methods']);
unset($this->session->data['payment_method']);
unset($this->session->data['payment_methods']);
unset($this->session->data['guest']);
unset($this->session->data['comment']);
unset($this->session->data['order_id']);
unset($this->session->data['coupon']);
unset($this->session->data['reward']);
unset($this->session->data['voucher']);
unset($this->session->data['vouchers']);
unset($this->session->data['totals']);
I am trying to let a Telegram bot send a message to a group without the need of a message by a user to trigger it. To be more specific i am trying to set up a birthday reminder where the bot querys a database, compares entries to the current date and broadcaststs a "Happy birthday" message in the group. As said i would like to do it via a cronjob that opens up the PHP script everyday and lets the bot broadcast it.
My problem is I checked all of Telegrams documentations and demo codes (https://core.telegram.org/bots/samples) but all of it are based on a User triggering the bot by sending a message.
My question is, if anyone was already able to implement a similar functionality and could aid me in extending my code? What might be worth mentioning is that the Bot is already integrated into the Group Chat and i have the chat id that would be needed for the bot to target the chat.
My code is as follows (i have to admit i copied it over from the demo examples):
<?php
define('BOT_TOKEN', 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX');
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'])) {
apiRequest("sendChatAction", array('chat_id' => $chat_id, "action" => "typing"));
// incoming text message
$text = $message['text'];
//Command for intializing the backend code for the birthday check (just to check its functionality but would prefer the code to run without a command)
if (strpos($text, "/geburtstagscheck") === 0) {
include 'skripte/start.php';
}
}}
define('WEBHOOK_URL', 'XXXXXXXXXXXXXX');
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"]);
} ?>
here is my sample code. my developer mode is already enabled but there is no menu tabs options.
you can also add me on wechat so I can elaborate my problems in this matter, here is my wechat ID VinceZen. I badly need some help guys. Thank you in advance.
<?php
$data[] = '772134292672v';
$data[] = $_GET['timestamp'];
$data[] = $_GET['nonce'];
asort($data);
$strData = '';
$d = '';
$authString = '';
foreach($data as $d)
{
$authString .= $d;
}
//verify the signature
if(sha1($authString) == $_GET['signature'])
{
//check the echostr
if(!empty($_GET['echostr']))
{
echo $_GET['echostr'];
die();
}
else
{
//logic
//Getting access_token from customize menus
static function get_access_token($appid,$secret){
$url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret;
$json=http_request_json($url);//here cannot use file_get_contents
$data=json_decode($json,true);
if($data['access_token']){
return $data['access_token'];
}else{
return "Error occurred while geting the access_token";
}
}
//Though URL request is https',cannot use file_get_contents.Using CURL while asking the JSON data
function http_request_json($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
$return = "<xml>
<ToUserName><![CDATA['.$toUser.']]</ToUserName>
<FromUserName><![CDATA['.$fromUser.']]</FromUserName>
<CreateTime>'.time.'</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA['.text.']]</Content>
<FuncFlag>0</FuncFlag>
</xml>";
echo $return;
{
"button":[
{
"type":"click",
"name":"Daily Song",
"key":"V1001_TODAY_MUSIC"
},
{
"type":"click",
"name":" Artist Profile",
"key":"V1001_TODAY_SINGER"
},
{
"name":"Menu",
"sub_button":[
{
"type":"view",
"name":"Search",
"url":"http://www.soso.com/"
},
{
"type":"view",
"name":"Video",
"url":"http://v.qq.com/"
},
{
"type":"click",
"name":"Like us",
"key":"V1001_GOOD"
}]
}]
}
}
}
else
{
die('Access Denied');
}`enter code here`
?>
I'm using google maps api v2 and I am sending coordinates to my program. The localisation on the map works fine but I never get the adress...
Here is my class:
class reverseGeoCoding {
//put your code here
private $result;
private $latitude=null;
private $longitude=null;
private $adresse=null;
private $config;
public $contents;
function xml2ary(&$string) {
$parser = xml_parser_create();
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
xml_parse_into_struct($parser, $string, $vals, $index);
xml_parser_free($parser);
$mnary=array();
$ary=&$mnary;
foreach ($vals as $r) {
$t=$r['tag'];
if ($r['type']=='open') {
if (isset($ary[$t])) {
if (isset($ary[$t][0])) $ary[$t][]=array(); else $ary[$t]=array($ary[$t], array());
$cv=&$ary[$t][count($ary[$t])-1];
} else $cv=&$ary[$t];
if (isset($r['attributes'])) {
foreach ($r['attributes'] as $k=>$v) $cv['_a'][$k]=$v;
}
$cv['_c']=array();
$cv['_c']['_p']=&$ary;
$ary=&$cv['_c'];
} elseif ($r['type']=='complete') {
if (isset($ary[$t])) { // same as open
if (isset($ary[$t][0])) $ary[$t][]=array(); else $ary[$t]=array($ary[$t], array());
$cv=&$ary[$t][count($ary[$t])-1];
} else $cv=&$ary[$t];
if (isset($r['attributes'])) {
foreach ($r['attributes'] as $k=>$v) $cv['_a'][$k]=$v;
}
$cv['_v']=(isset($r['value']) ? $r['value'] : '');
} elseif ($r['type']=='close') {
$ary=&$ary['_p'];
}
}
$this->del_p($mnary);
return $mnary;
}
// _Internal: Remove recursion in result array
function del_p(&$ary) {
foreach ($ary as $k=>$v) {
if ($k==='_p') unset($ary[$k]);
elseif (is_array($ary[$k])) $this->del_p($ary[$k]);
}
}
// Array to XML
function ary2xml($cary, $d=0, $forcetag='') {
$res=array();
foreach ($cary as $tag=>$r) {
if (isset($r[0])) {
$res[]=ary2xml($r, $d, $tag);
} else {
if ($forcetag) $tag=$forcetag;
$sp=str_repeat("\t", $d);
$res[]="$sp<$tag";
if (isset($r['_a'])) {
foreach ($r['_a'] as $at=>$av) $res[]=" $at=\"$av\"";
}
$res[]=">".((isset($r['_c'])) ? "\n" : '');
if (isset($r['_c'])) $res[]=ary2xml($r['_c'], $d+1);
elseif (isset($r['_v'])) $res[]=((!is_numeric($r['_v'])&&$r['_v']) ? '<![CDATA[' : false).$r['_v'].((!is_numeric($r['_v'])&&$r['_v']) ? ']]>' : false);
$res[]=(isset($r['_c']) ? $sp : '')."</$tag>\n";
}
}
return implode('', $res);
}
function formatGmapXML($xml,$returnXML=false,$error=false) {
$tmp = array();
$tmp['request']= $xml['kml']['_c']['Response']['_c']['name']['_v'];
$tmp['status']= $xml['kml']['_c']['Response']['_c']['Status']['_c']['code']['_v'];
// check our Response code to ensure success
if($tmp['status']=='200') {
$tmp['addressFull'] = $xml['kml']['_c']['Response']['_c']['Placemark']['_c']['address']['_v'];
$tmp['accuracy'] = $xml['kml']['_c']['Response']['_c']['Placemark']['_c']['AddressDetails']['_a']['Accuracy'];
$tmp['country'] = $xml['kml']['_c']['Response']['_c']['Placemark']['_c']['AddressDetails']['_c']['Country']['_c']['CountryName']['_v'];
$tmp['state'] = $xml['kml']['_c']['Response']['_c']['Placemark']['_c']['AddressDetails']['_c']['Country']['_c']['AdministrativeArea']['_c']['AdministrativeAreaName']['_v'];
$tmp['suburb'] = $xml['kml']['_c']['Response']['_c']['Placemark']['_c']['AddressDetails']['_c']['Country']['_c']['AdministrativeArea']['_c']['Locality']['_c']['LocalityName']['_v'];
$tmp['address'] = $xml['kml']['_c']['Response']['_c']['Placemark']['_c']['AddressDetails']['_c']['Country']['_c']['AdministrativeArea']['_c']['Locality']['_c']['Thoroughfare']['_c']['ThoroughfareName']['_v'];
$tmp['postcode'] = $xml['kml']['_c']['Response']['_c']['Placemark']['_c']['AddressDetails']['_c']['Country']['_c']['AdministrativeArea']['_c']['Locality']['_c']['PostalCode']['_c']['PostalCodeNumber']['_v'];
$tmp['coordinates'] = $xml['kml']['_c']['Response']['_c']['Placemark']['_c']['Point']['_c']['coordinates']['_v'];
if($tmp['addressFull']==null) {
$tmp['addressFull'] = $xml['kml']['_c']['Response']['_c']['Placemark'][0]['_c']['address']['_v'];
$tmp['accuracy'] = $xml['kml']['_c']['Response']['_c']['Placemark'][0]['_c']['AddressDetails']['_a']['Accuracy'];
$tmp['country'] = $xml['kml']['_c']['Response']['_c']['Placemark'][0]['_c']['AddressDetails']['_c']['Country']['_c']['CountryName']['_v'];
$tmp['state'] = $xml['kml']['_c']['Response']['_c']['Placemark'][0]['_c']['AddressDetails']['_c']['Country']['_c']['AdministrativeArea']['_c']['AdministrativeAreaName']['_v'];
$tmp['suburb'] = $xml['kml']['_c']['Response']['_c']['Placemark'][0]['_c']['AddressDetails']['_c']['Country']['_c']['AdministrativeArea']['_c']['Locality']['_c']['LocalityName']['_v'];
$tmp['address'] = $xml['kml']['_c']['Response']['_c']['Placemark'][0]['_c']['AddressDetails']['_c']['Country']['_c']['AdministrativeArea']['_c']['Locality']['_c']['Thoroughfare']['_c']['ThoroughfareName']['_v'];
$tmp['postcode'] = $xml['kml']['_c']['Response']['_c']['Placemark'][0]['_c']['AddressDetails']['_c']['Country']['_c']['AdministrativeArea']['_c']['Locality']['_c']['PostalCode']['_c']['PostalCodeNumber']['_v'];
$tmp['coordinates'] = $xml['kml']['_c']['Response']['_c']['Placemark'][0]['_c']['Point']['_c']['coordinates']['_v'];
}
$latlng = explode(',',$tmp['coordinates']);
$tmp['latitude'] = $latlng[1];
$tmp['longitude'] = $latlng[0];
}
// optional outputs
if($error) $tmp['error'] = $error;
if($returnXML) $tmp['xml'] = ary2xml($xml);
return $tmp;
}
/*
$q=$_GET['q'];
$latitude=$_GET['latitude'];
$longitude=$_GET['longitude'];
*/
function reverseGeoCoding() {
$this->config=new configInt();
}
function setLongitude($longitude) {
$this->longitude=$longitude;
}
function setLatitude($latitude) {
$this->latitude=$latitude;
}
function setadresse($adresse) {
$this->adresse=$adresse;
}
function getLongitude() {
return $this->longitude;
}
function getLatitude() {
return $this->latitude;
}
function getadresse() {
return $this->adresse;
}
function exec() {
if($this->longitude && $this->latitude ) {
$ch = curl_init("http://maps.google.com/maps/geo?output=xml&ll={$this->latitude},{$this->longitude}&key={$this->config->clefGoogle}");
}else {
$adresse=rawurlencode($this->adresse);
$ch = curl_init("http://maps.google.com/maps/geo?output=xml&q={$adresse}&key={$this->config->clefGoogle}");
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; pl; rv:1.9) Gecko/2008052906 Firefox/3.0");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_HTTPGET, true);
//curl_setopt($ch, CURLOPT_COOKIEJAR, "cookie.txt");
curl_setopt($ch, CURLOPT_VERBOSE, false);
$this->contents=curl_exec($ch);
$this->contents=$this->xml2ary($this->contents);
$this->result=$this->formatGmapXML($this->contents,false);
curl_close($ch);
if($this->longitude && $this->latitude ) {
$this->adresse=utf8_decode($this->result['addressFull']);
}else {
$this->latitude=$this->result['latitude'];
$this->longitude=$this->result['longitude'];
}
return $this->result;
}
}
?>
I'm using getAdress in my programm to save the adress in the database, but it never seems to work properly even though the coordinates are correct...
Try this:
$result = json_decode(file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=true'));
echo $result->results[0]->formatted_address;
function getaddress($lat, $lng) {
$url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng=' . trim($lat) . ',' . trim($lng) . '&sensor=false';
$json = #file_get_contents($url);
$data = json_decode($json);
$status = $data->status;
if ($status == "OK")
return $data->results[0]->formatted_address;
else
return false;
}
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);