Laravel Wordpress JSON REST API gives strange Curl error - php

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!

Related

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?

I am trying to hit a certain local MPESA Payment API but am getting an error

I am trying to get a response from MPESA payment API using laravel but I am getting an error . My code is as below
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class MPESA_AUTH extends Controller
{
public function Authorize(){
$url = 'https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials';
$CONSUMER_KEY= 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$CONSUMER_SECRET= 'xxxxxxxxxxxx';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
$credentials = base64_encode($CONSUMER_KEY,$CONSUMER_SECRET);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: Basic '.$credentials)); //setting a custom header
curl_setopt($curl, CURLOPT_HEADER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$curl_response = curl_exec($curl);
$curl_json=json_decode($curl_response);
return $curl_json;
}
}
The error am getting is as below
The Base controller uses Illuminate\Routing\Controller trait which has an 'authorize()' function. Your function declaration is clashing with it.
Change your controller method name to anything else(other than 'authorize') and you should be good to go
You should use a different function name in place of "Authorize". This is because "authorize" in controllers is a preserved name used in the parent class Controller.

Curl In Codeigniter - Error Code 22, HTTP GET

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');

Laravel: HTTPrequest to another server

How to make http request to another server through Laravel?
I'll be pleased to provide whatever information you need
any help is much appreciated
Depends how complex the request needs to be. You can use curl or even, file_get_contents for simple get requests, or install a package like Guzzle for more complex things.
https://github.com/guzzle/guzzle
With 'normal' PHP, you can use Curl to work with the http protocol (POST/GET). If you are using Laravel, you can either build your own curl methods or you can use a 3rd party curl library compatible with composer/Laravel:
https://packagist.org/packages/unikent/curl
You can use Guzzle
add the dependency package in the composer.json file
{
"require": {
"guzzlehttp/guzzle": "~4.0" //you can change the version
}
}
make composer install or update
To create your very first request with guzzle, a code snippet as simple as below will work:
use GuzzleHttp\Client;
use GuzzleHttp\Message\Request;
use GuzzleHttp\Message\Response;
$client = new Client();
$response = $client->get("https://api.github.com/");
retrun $response;
If for some reason you are running an old Laravel version or don't want to bother with guzzle, you can always use php-curl:
sudo apt-get install php-curl
Then create a function for your needs eg POST:
function httpPost($url, $data){
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
curl_close($curl);
return $response;
}
or GET
public function httpGet($url){
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
curl_close($curl);
return $response;
}
Simply call your function in controller:
$response = $this->httpPost($url, $data);
$response = $this->httpget($url);
Where $url is your endpoint where you need to send request and $data - parameters required.
First of all run this command
composer require guzzlehttp/guzzle
use GuzzleHttp\Client;
$client = new Client();
$response = $client->get("http://www.somewebsite.com/getSmth");
$response = (string) $response->getBody();
return $response;
getBody() function will return object.
You can use via converting to string and after that if you want you can change it to integer also
$response = (int) (string) $response->getBody();

how to call restful zend controller usin curl in php?

<?php
require_once 'Zend/Session/Namespace.php';
class ApiController extends Zend_Rest_Controller
{
public function init()
{
$this->_helper->layout->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
}
public function indexAction()
{
$query=$this->getRequest()->getParam('query');
$this->getResponse()
->appendBody("hi");
$this->getResponse()->setHttpResponseCode(200);
}
public function getAction()
{
$query=$this->getRequest()->getParam('id');
$this->getResponse()
->appendBody($query);
}
public function postAction()
{
$this->getResponse()
->setHttpResponseCode(200)
->appendBody("From postAction() creating the requested article");
}
public function putAction()
{
$this->getResponse()
->appendBody("From putAction() updating the requested article");
}
public function deleteAction()
{
$this->getResponse()
->appendBody("From deleteAction() deleting the requested article");
}
}
Above is my REST API I am trying to call it from php curl but I don't know how to call post method.
I have also made entry in bootsrap to default module\ using rest route.
Here is a snippet of my code:
<?php
$ch = curl_init('http://apanel3.newfront.local/api');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 4);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
$curlresult = curl_exec($curl_connection);
print_r($curlresult);
?>
I am trying to call my api using following curl code. It is calling indexAction. Even thought i have set curlopt_post to true, I am not getting desired output.
I believe there are lot of examples for php curl + post. Do you know how to access your actions (make http calls generally, without curl) ?
Here is another answer to the link to the similar question.
If you are trying to access your API from another zend based application and want to use zend inbuilt method then, you should check Zend_Http_Client there is an adapter for curl if you want to specifically use curl adapter.
EDIT:
On your client side:
<?php
//
// A very simple PHP example that sends a HTTP POST to a remote site
//
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "'http://apanel3.newfront.local/api'");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "query='where post_parameter = query'");
// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec($ch);
curl_close($ch);
// further processing ....
if($server_output == 'OK') {
echo 'Test passed';
} else {
echo $server_output;
}
?>
On your API side for indexAction:
public function indexAction()
{
$query=$this->getRequest()->getParam('query');
if($this->getRequest()->isPost()) {
// method == post, do your processing whatever required here ....
$this->_forward('post',null,null,$query);
} elseif ($this->getRequest()->getMethod() == 'GET') {
// method == get
$this->_forward('get',null,null,$query);
}else {
// bad request response code 400
$this->getResponse()
->appendBody("not a valid request");
$this->getResponse()->setHttpResponseCode(400);
}
}
Edit:
My mistake I didn't realize you were extending Zend_Rest_Controller, your code for controller seems fine. Now you probably know about making curl request via PHP.
On how to make PUT Request please check this question

Categories