I would like to call a rest function of my api with the GET protocol but I didn't succeed to put the security key of restler as a post parameter.
example:
/index.php/myrestapi/method.json?name=test
post field : Array('key'=>'mykey')
$session = curl_init('<mydomainurl>/index.php/myrestapi/method.json?name=test');
// Tell curl that this is the body of the POST
curl_setopt ($session, CURLOPT_POSTFIELDS, array('key'=>'mykey');
// Tell curl not to return headers, but do return the response
curl_setopt($session, CURLOPT_HEADER, false);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($session);
Myrestapi.php function:
protected function getMethod($name){
return $name;
}
What is wrong?!
Thanks in advance for your help!
Kevin
security key should also be part of get parameter
<mydomainurl>/index.php/myrestapi/method.json?name=test&key=mykey
Then need to handle that with iAuthenticate.
For more details see e.g. Protected API of restler.
Related
I am newbie, working on codeigniter and I am using the razorpay payment gateway apis for transferring the amount using route concept as defined in the razorpay documentation. When I am calling the api using curl I am getting the error:
{
"error": {
"code": "BAD_REQUEST_ERROR",
"description": "Please provide your api key for authentication purposes.",
"source": null,
"step": null,
"reason": null,
"metadata": {}
}
}
the code i used is :
$url = 'https://api.razorpay.com/v1/payments/pay_E8JR8E0XyjUSZd/transfers';
/* Array Parameter Data */
$data = ['account' => 'va_FWSvFCwsaV1w5K', 'amount' => 90, 'currency' => 'INR'];
/* pass encoded JSON string to the POST fields */
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
/* set the content type json */
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json','YOUR_KEY_ID','YOUR_KEY_SECRET'));
/* set return type json */
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
/* execute request */
$result = curl_exec($ch);
/* close cURL resource */
curl_close($ch);
print_r($result);
How should I place my key and secret in curl so that error does not occur.
Please help me out. Thanks in advance.
The error message is pretty self-explanatory. This line:
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json','YOUR_KEY_ID','YOUR_KEY_SECRET'));
Should contain your actual key and secret, not your_key_id and your_key_secret placeholder strings. Otherwise, authorization will fail
You will require to encode key:secret in base64 format. And then add another header Authorization to make this API working.
headers = {
"Content-Type": "application/json",
"Authorization": "Basic " + encode_base64(Key:Secret)
}
In your case,
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json','Authorization:Basic (encoded_string)'));
Let me know if it works for you!
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.
I am using the curl option CURLOPT_HEADERFUNCTION along with a closure to perform some basic data manipulation. As per the php docs, the function / callback must return the length of the header on each call.
$headers = [];
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADERFUNCTION, function($curl, $headerLine) use (&$headers) {
$headers[] = $headerLine;
return strlen($headerLine);
});
$response = curl_exec($curl);
curl_close($curl);
return $headers;
I am using references to return the value which works fine. I am just curious if there are other ways to return this value without using references or using a callback?
You can specify the callback function to be a class method:
curl_setopt($curl, CURLOPT_HEADERFUNCTION, array($this, 'someOtherFunction'));
In that other function, you can have access to anything $this has access to:
protected function someOtherFunction($curl, $headerLine)
{
$this->headers[] = $headerLine;
return strlen($headerLine);
}
* This answer assumes you're inside of a class context to begin with
How i Can add or somethink do with csrftoken when paypal send post on my website.
My error code:
TokenMismatchException in VerifyCsrfToken.php line 53.
Here code:
public function getPaypal(Request $request)
{
$uri = $request->all();
if(isset($uri['tx']))
{
$pp_hostname = "www.sandbox.paypal.com"; // Change to www.sandbox.paypal.com to test against sandbox
// read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-synch';
$tx_token = $uri['tx'];
$auth_token = "EHNebv....e";
$req .= "&tx=$tx_token&at=$auth_token";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://$pp_hostname/cgi-bin/webscr");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
//set cacert.pem verisign certificate path in curl using 'CURLOPT_CAINFO' field here,
//if your server does not bundled with default verisign certificates.
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Host: $pp_hostname"));
$res = curl_exec($ch);
curl_close($ch);
}
According to Laravel Docs: http://laravel.com/docs/5.1/routing#csrf-protection.
Excluding URIs From CSRF Protection
Sometimes you may wish to exclude a set of URIs from CSRF protection.
For example, if you are using Stripe to process payments and are
utilizing their webhook system, you will need to exclude your webhook
handler route from Laravel's CSRF protection.
You may exclude URIs by adding them to the $except property of the
VerifyCsrfToken middleware:
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;
class VerifyCsrfToken extends BaseVerifier
{
/**
* The URIs that should be excluded from CSRF verification.
*
* #var array
*/
protected $except = [
'paypal/*',
];
}
Let me know if it is still not clear.
You don't need to completely disable the middleware just go to VerifyCrsfToken file in app\Http\Middle then edit the protected array $except and include and entry of the route paypal is posting to.
protected $except = [
/paypal/data,
];
TokenMismatchException is a Laravel error, not PayPal. With every POST request, you need to send a _token value through with it.
If you are sending this through a form, simply echo csrf_field() into your form template.
If you are sending the request from something other than Laravel, you can disable the CSRF protection on that route. Read more about Middleware here: http://laravel.com/docs/5.1/middleware
Read more about it here: http://laravel.com/docs/5.1/routing#csrf-protection
<?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