How to generate token for rest call in codeigniter? - rest

I have to call rest api function in codeigniter project . Data is returning from the api call using Postman . In Postman first i generate a token and put that generated token in the rest call. I have to do the same process in codeigniter. First i have to generate token and pass that token in second api call to get the desired result.
My Controller code :
public function getToken()
{
$url='http://localhost:8080/myapplication/rest/api/validate-request';
$key=$this->get_data($url);
}
public function get_data($url)
{
//create a new cURL resource
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
//curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_USERPWD, R_U_NAME.':'.R_U_PWD);
$result = curl_exec($ch);
$result = json_decode($result);
//var_dump($result);
//close cURL resource
curl_close($ch);
}
Here var_dump($result) is returning null value.

I donot had to pass username and password for authentication .Instead i had to post postman username and password in my function. Now I am getting the token back from the postman.
private function get_data($url)
{
$member_data = array(
'username' => R_U_NAME,
'password' => R_U_PWD
);
//create a new cURL resource
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $member_data);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}

Related

Magento 2 rest api Consumer is not authorized to access %resources<

I want to get the products from magento 2 that is in my localhost. but when i put /rest/V1/products? it gives me
<response>
<message>Consumer is not authorized to access %resources</message>
<parameters>
<resources>Magento_Catalog::products</resources>
</parameters>
</response>
i have made roles and also integration. i don't know how to access these resources. i have to get these products in my ionic app
That error is fairly self explanatory - you haven't authenticated.
Here's an example of how to authenticate with an admin user and fetch products using curl;
// Fetch the user auth token
$userData = array("username" => "USER", "password" => "PASS");
$ch = curl_init("http://DOMAINNAME.com/index.php/rest/V1/integration/admin/token");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($userData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Content-Lenght: " . strlen(json_encode($userData))));
$token = curl_exec($ch);
// Now use the token to get all products
$ch = curl_init("http://DOMAINNAME.com/index.php/rest/default/V1/products?searchCriteria");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Authorization: Bearer " . json_decode($token)));
// Here are the results
$result = curl_exec($ch);
$result = json_decode($result, 1);
echo '<pre>';
print_r($result);
echo '</pre>';

Paypal PDT error

I use this code to process Paypal payment data transfer (PDT):
$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 = $_GET['tx'];
$auth_token = "my_token";
$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);
if(!$res){
echo "HTTP ERROR";
}else{ ...
But it does not work, my code tells me that the request fails, and it outputs HTTP ERROR because $res is empty.
Why?

Translate cURL request to Guzzle

I am trying to use Guzzle instead of directly using cURL to achieve and HTTP request. How do I make this same type of request but with Guzzle? Or should I just stick to cURL?
$ch = curl_init();
// Set the URL
curl_setopt($ch, CURLOPT_URL, $url);
// don't verify SSL certificate
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
// Return the contents of the response as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// Follow redirects
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
// Set up authentication
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "$token:X");
I keep running into 401 Unauthorized error. I know I have correct credentials. What makes me think I am not on the right track is the Guzzle docs stating: auth is currently only supported when using the cURL handler, but creating a replacement that can be used with any HTTP handler is planned. But from my understanding Guzzle defaults with cURL.
$guzzleData = [
'auth' => [$token, 'X'],
'allow_redirects' => true,
'verify' => false,
];
$client = new \Guzzle\Http\Client();
$request = $client->get($url, $guzzleData);
$response = $request->send();
Here is the solution:
$client = new \Guzzle\Http\Client();
$request = $client->get($url);
$request->getCurlOptions()->set(CURLOPT_SSL_VERIFYHOST, false);
$request->getCurlOptions()->set(CURLOPT_SSL_VERIFYPEER, false);
$request->getCurlOptions()->set(CURLOPT_RETURNTRANSFER, true);
$request->getCurlOptions()->set(CURLOPT_FOLLOWLOCATION, true);
$request->getCurlOptions()->set(CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
$request->getCurlOptions()->set(CURLOPT_USERPWD, "$token:X");
$response = $request->send();
The solution I was able to get working for Guzzle6 is:
$headers = array();
$headers['grant_type'] = 'client_credentials';
$headers['client_id'] = $clientid;
$headers['client_secret'] = $clientSecret;
$response = $this->client->post($urlAuth, ['form_params' => $headers]);
$output = $response->getBody()->getContents();
ie the header array has to be wrapped in 'form_params'

POST data to AtTask's API?

I'm using AtTask's API with PHP and cURL.
Is there a way to POST data instead of appending it to the end of the URL with a question mark?
I know that I can change the request name itself like CURLOPT_CUSTOMREQUEST => 'POST' and I tried adding CURLOPT_POST => true
However, the CURLOPT_POSTFIELDS => array('name' => 'Untitled Project') is still ignored.
Did anyone work with this?
Pretty sure you need to wrap your postfields array with http_build_query(). Here is an example for logging in that works for me (when I put in my username and password):
$URL = 'https://hub.attask.com/attask/api/login';
$username = 'admin';
$password = 'user';
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $URL);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array(
'username'=>$username,
'password'=>$password
)));
$results = curl_exec($ch);
curl_close($ch);
print_r($results);
Hope that helps.
I just ran into the same problem you did. It's been a few months since you asked the question, but if you're still running into it (or for anyone else hitting this wall), the issue is that you need to set the proper CURL options for POST/GET.
For a GET you'll need to set CURLOPT_HTTPGET to "true". It just makes sure the headers are in the correct order for the AtTask API server.
I've just created a github repo for the changes I've made to their sample StreamClient class.
https://github.com/angrychimp/php-attask
Feel free to use that or just lift the code from it. For your login example, GreenJimmy's example is 100% accurate. For your search question, you'll need to do something like the following.
$URL = 'https://hub.attask.com/attask/api/v4.0/';
$username = 'admin';
$password = 'pass';
$URL .= "task/search/?sessionID=$sessionID&ID=$taskID";
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $URL);
curl_setopt($ch, CURLOPT_HTTPGET, true);
$results = curl_exec($ch);
curl_close($ch);
print_r($results);
The StreamClient in my github repo allows for arrays to be used for search params and response fields. It does make things a lot easier. For example.
require_once('StreamClient.php');
$client = new StreamClient('https://hub.attask.com', '4.0');
$client->login('admin', 'pass');
$records = $client->search('task', array('ID' => $taskID), array('assignedToID:emailAddr','actualWork'));
var_dump($records);

facebook, post comment via php curl

From one tutorials here:
Post a reply on a comment in Facebook using cURL PHP / Graph API
I tried to post comment to after one post, But return:
[type] => OAuthException [message] => (#200) The user hasn't authorized the application to perform this action
This is not my app acount wall's post id, I tried to my freinds wall, he have allowed my app, I can post a post to his wall, but failed in a comment, I got the post id via
https://graph.facebook.com/<his fid>/feed?access_token=140XXXXXXXXXXX, so the post id has no problem.
What steps have I missed?
$fbId = '100001102789652_233997699980321';
$accessToken = '140XXXXXXXXXXXX';
$url = "https://graph.facebook.com/{$fbId}/comments";
$attachment = array(
'access_token' => $accessToken,
'message' => "Hi comment",
);
// set the target url
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $attachment);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$comment = curl_exec($ch);
curl_close ($ch);
$comment = json_decode($comment, TRUE);
print_r($comment);
?>
curl_setopt($ch, CURLOPT_POSTFIELDS, $attachment);
should be
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($attachment));
as you can't post an array