Curl In Codeigniter - Error Code 22, HTTP GET - php

I want to fetch data from Third_party API called BirdEye. I was using Core PHP Inbuilt Functions of CURL to fetch data, it was working fine, Now When I switched to Library I am bit confused because it doesn't gives me any response in return.
I have Downloaded Curl Libray from Here : Curl Library Download and Example
I tried to create a demo just to check my Library is working fine or not, it worked. Now If I fetch data from Bird-Eye Api I don't know It gives me nothing in response.
My Code is here:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends CI_Controller {
public function index()
{
$this->load->library('curl');
$get_url = "https://api.birdeye.com/resources/v1/business/147802929307762?api_key=ApiKeyGoesHere";
echo $this->curl->simple_get($get_url, false, array(CURLOPT_USERAGENT => true));
echo $this->curl->error_code;
$this->load->view('welcome_message');
}
}
I don't know where I am going wrong I am passing all the required parameters to the Api and when I try to echo error code it gives me 22. I even searched on birdeye documentation but nothing found.
Link to Api Documentation is : Link to BirdEye Api Documentation

So according to the BirdEye API your cURL script should be like the following:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.birdeye.com/resources/v1/business/businessId ");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Content-Type: application/json",
"Accept: application/json"
));
$response = curl_exec($ch);
curl_close($ch);
Now, when I'm comparing your library usage code to the example above, I see you're missing the definitions of several options.
Before adding those options to your code, try to follow this part:
In the example they're not using the APIKEY, but when you do use it, you might need to pass it as a parameter and not in the get_url variable.
Which means:
$get_url = "https://api.birdeye.com/resources/v1/business/147802929307762";
echo $this->curl->simple_get($get_url, array('api_key' => 'YourApiKeyGoesHere'), array(..));
If it still doesn't work, try to add the options to your code:
$this->load->library('curl');
$get_url = "https://api.birdeye.com/resources/v1/business/147802929307762?api_key=ApiKeyGoesHere";
echo $this->curl->simple_get($get_url, false, array(CURLOPT_USERAGENT => true, CURLOPT_RETURNTRANSFER => TRUE, CURLOPT_HEADER => FALSE, CURLOPT_HTTPHEADER => array("Content-Type: application/json", "Accept: application/json")));
echo $this->curl->error_code;
$this->load->view('welcome_message');

Related

Using CURLOPT_HTTPHEADER with an Object

When using PHP's curl API, if I accidentally use a string with the CURLOPT_HTTPHEADER curl option
curl_setopt($ch, CURLOPT_HTTPHEADER, 'User-Agent: php-curl');
PHP will scold me
Warning: curl_setopt(): You must pass either an object or an array with the CURLOPT_HTTPHEADER argument in /path/to/test.php on line 32
I know I can fix this using an array
$headers = [];
$headers[] = 'User-Agent: php-curl';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
However, the warning seems to indicate I could also be passing curl_setopt an object. Is this possible?
I've tried with both an stdClass and ArrayObject, but neither seems to work. Is this just a misleading warning message, or is there a way to use curl_setopt with an object?
Update Turns out I had a PHP extension installed that was blocking the standard behavior. ArrayObjects work fine in this function. I can't close or delete this question, so hopefully this warning will avoid confusion.
You need to pass an object that implements JsonSerializable.
class Testing implements JsonSerializable
{
protected $headers = [];
public function __construct($headers)
{
$this->headers = $headers;
}
public function jsonSerialize()
{
return $this->headers;
}
}
Then you can pass it to your CURLOPT_HTTPHEADER parameter:
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, new Testing(['User-Agent: php-curl']));

Sending Media Files using CURL - Laravel PHP

I am posting data(including a media file (.wav)) from my app to an API with curl. When submitting my data, i check for the data including the mediafile submitted in my API. From the response i get from my API, see below
Response
{"status":"success","media":false,"data":{"message":"Media Campaign","recipient":["34505140704"],
"file":{"name":"\/Users\/path\/to\/folder\/public\/Voice\/aaaah.wav","mime":null,"postname":null}}}true
In the response, the file is being retrieved as well but when i check for the file using $request->hasFile('file') or $request->file('file'), I get false and null respectively.
Can someone let me know why this is happening in my code please ?
Controller
public function test()
{
$file_name_with_full_path = '/Users/path/to/folder/public/Voice/aaaah.wav';
if(function_exists('curl_file_create'))
{
$cFile = curl_file_create($file_name_with_full_path);
}
else
{
$cFile = '#' . realpath($file_name_with_full_path);
}
$post = array('message' => 'Media Campaign', 'recipient' => ['34505140704'],'file' => $cFile);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
$result=curl_exec ($ch);
curl_close ($ch);
}
APIController
public function campaign(Request $request)
{
if (($request->get('message')) {
return response()->json([
'status' => 'success',
'data' => $request->all()
]);
}
}
To be honest, I'd use Guzzle to hide the details of cURL requests in PHP. The way PHP's cURL extension handles file transfers changed a couple of years ago, which broke a lot of legacy code at the company I was working for. By using a third-party wrapper like Guzzle, you can let the Guzzle developers worry about changes in the underlying extension - all you need to do is keep your Guzzle package up to date.
PHP - Why Use Guzzle Instead of cURL?

Laravel Wordpress JSON REST API gives strange Curl error

I'm trying to use laravel-wp-api to get the posts from a blog. When I use Postman with http://idareyou.ee/blog//wp-json/wp/v2/posts I get a 200 OK HTTP response and Postman shows the JSON result.
The following Laravel BlogController getPosts() method prints in the browser this Curl error:
{"error":{"message":"cURL error 6: Couldn't resolve host '\u003Cwp_location\u003E' (see http:\/\/curl.haxx.se\/libcurl\/c\/libcurl-errors.html)"},"results":[],"total":0,"pages":0}
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use WpApi;
class BlogController extends Controller
{
public function getPosts()
{
$posts = WpApi::posts('http://idareyou.ee/blog//wp-json/wp/v2/posts');
echo json_encode($posts,true);
//return view('pages.blog', ['active'=>'navBlog'])->with('posts', $posts );
}
}
Elsewhere in my app I am fetching successfully some pictures from Instagram API using the following. Do I need a similar 'fetchData' function in my BlogController?
function fetchData($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
$result = fetchData("https://api.instagram.com/v1/users/.......");
$result = json_decode($result, true);
$lastFive = array_slice($result['data'], 0, 5); // returns last 5 instagram pics
Can anybody give me any tips on what I'm doing wrong?
I would check the config file for this service - my guess is you need to set-up the endpoint (blog domain) for your calls. So once you run php artisan vendor:publish you should have a specific config file under app/config - see if there's a setting there you need to change.
Hope this helps!

Fabric Digits oauth authentication in PHP

I've got an app which works with Digits as authentication.
Client-side works perfectly, but I'm not able to make the server user authentication through oAuth.
My server is developed with Laravel, so it's PHP.
My endpoint is under https, so everything should be ready to make the call.
I solved by myself!
Here's the code that makes correctly the authentication through Digits O-Auth.
The function that makes authentication is inside an AuthManager class and I call in this way:
$obj = AuthManager::verifyUser($request->header('X-Auth-Service-Provider'),$request->header("X-Verify-Credentials-Authorization"));
And here's the function that makes the magic:
public static function verifyUser ($xAuthServiceProvider, $xVerifyCredentialsAuthorization)
{
$curl = curl_init();
curl_setopt($curl,CURLOPT_URL, $xAuthServiceProvider);
curl_setopt($curl,CURLOPT_HTTPHEADER, array(
'Content-length: 0',
'Content-type: application/json',
'Authorization: '.$xVerifyCredentialsAuthorization,
));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$content = curl_exec($curl);
$info = curl_getinfo($curl);
curl_close($curl);
$obj = json_decode($content, true);
return $obj;
}
If you have any problem, don't hesitate to write here!
EDIT WITH EXAMPLE FUNCTION ABOUT HOW TO GET DATA FROM O-AUTH
public function authenticate (Request $request)
{
$obj = AuthManager::verifyUser($request->header('X-Auth-Service-Provider'),$request->header("X-Verify-Credentials-Authorization"));
if(isset($obj["errors"]))
{
return "error!";
}
$digits_token = $obj["access_token"]["token"];
$digitsId = $obj["id"];
/*
the variables above are returned by O-auth server-server authentication
*/
}

Connecting Nav Web Service in php

I am trying to connect the Nav Web Services in Php (followed by this Blog).
but it's returning an error:
SOAP-ERROR: Parsing WSDL: Couldn't load from
'http://NavIP.com:7047/DynamicsNAV/WS/SystemService' : Start tag
expected, '<' not found.
Could you tell me where I went wrong?
thanks in advance..
my code is:
//client.php
<?php
require_once("NTLMStream.php");
require_once("NTLMSoapClient.php");
try
{
// we unregister the current HTTP wrapper
stream_wrapper_unregister('http');
// we register the new HTTP wrapper
stream_wrapper_register('http', 'NTLMStream') or die("Failed to register protocol");
// Initialize Soap Client
$baseURL = 'http://NavIp.Com:7047/DynamicsNAVPMS/WS/';
$client = new NTLMSoapClient($baseURL.'SystemService');
// Find the first Company in the Companies
$result = $client->Companies();
$companies = $result->return_value;
echo "Companies:<br>";
if (is_array($companies)) {
foreach($companies as $company) {
echo "$company<br>";
}
$cur = $companies[0];
}
else {
echo "$companies<br>";
$cur = $companies;
}
}
catch(Exception $ex)
{
echo $ex->getMessage();
}
?>
I am dealing with the exact same problem, but have not found a solution because they all come back to this same script. Your problem is that you are getting no result back because of a 401 error code (could not authenticate), which is exactly I where I am stuck as well. The script ends up using CURL to connect, but somehow that fails.
Use this
$client = new NTLMSoapClient(null, $baseURL.'SystemService');
You are wrongly providing baseURL which is being taken as WSDL location. In your code, seems like you are trying to provide the service endpoint. Try that.
You could also use a packet sniffer like 'Wireshark' to see what response you are getting. The expected response is an xml, which seems like it is not returning. Maybe it is returning a 401 unauthorized? That's not an XML response, that also could be a cause.
Also, where is define('USERPWD','user:pass'); in your code? Didn't you use authentication? I have a strong feeling you just need to define it. Make sure you define the 'domain' part in the username field if you are using a domain. So, 'domain\user:pass'.
This post is good: http://blogs.msdn.com/b/freddyk/archive/2010/01/19/connecting-to-nav-web-services-from-php.aspx
Instead of using NTLM, try using Basic Authentication which is quite straight forward and then use cURL. It is easy peasy. See code below for a simple implementation. You can use SOAP or ODATA
You should also use a Chrome extension known as Wizdler
See sample code below for a Basic implementation
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://navdynamicsip.com:port/WebService/WS/COMPANY NAME/Page/webservice",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_POSTFIELDS =>"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Envelope xmlns=\"http://schemas.xmlsoap.org/soap/envelope/\">\n<Body>\n<Read xmlns=\"urn:microsoft-dynamics-schemas/page/webservice\"></Read>\n</Body>\n</Envelope>",
CURLOPT_HTTPHEADER => array(
"Content-Type: text/xml; charset=utf-8",
"SoapAction: urn:microsoft-dynamics-schemas/page/webservice",
"Authorization: Basic " .base64_encode('username:password')
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);

Categories