I'm using https://github.com/Zizaco/entrust for my ReST API integration in Laravel 5.2
I can retrieve the token. Then, I try to pass it to some route which needs the token. But I get this error with status code 401:
Failed to authenticate because of bad credentials or an invalid authorization header.
This is the code I use:
$base_url = 'http://mysite/api/';
$fields = array(
'email' => urlencode('myEmail'),
'password' => urlencode('myPass'),
);
$fields_string = '';
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $base_url . 'login');
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
$result = curl_exec($ch);
$result = json_decode($result, true);
$token = false;
if ($result['result'] == 'success') {
$token = $result['token'];
}
if ($token) { //call the api by passing the token:
// var_dump($token);
curl_setopt($ch,CURLOPT_URL, $base_url . 'admin/sells');
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $token
]);
curl_setopt($ch,CURLOPT_POST, null);
curl_setopt($ch,CURLOPT_POSTFIELDS, null);
curl_setopt($ch, CURLOPT_HTTPGET, 1);
// var_dump(curl_getinfo($ch));
$result = curl_exec($ch);
$result = json_decode($result, true);
var_dump($result);
}
And this is my route:
$api = app('Dingo\Api\Routing\Router');
$app_controller = 'App\\Http\\Controllers\\';
$auth_controller = 'App\\Http\\Controllers\\Auth\\';
$api->version('v1', function ($api) use ($app_controller,$auth_controller) {
$api->post('login', ['as' => 'api_login', 'uses' => $auth_controller . 'AuthController#authenticate']);
});
$api->version('v1', ['middleware' => 'api.auth'], function ($api) use ($app_controller,$auth_controller) {
$api->get('admin/sells', ['as' => 'api_admin_sells', 'uses' => $app_controller . 'SellsController#apiIndex']);
});
Am I doing anything wrong?
Related
Update (Solution):
When the experience_context is added to the request body, the PayPal-Request-Id seems to be become mandatory in the Header of the curl Request.
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'Authorization: Bearer ' . $this->getAccessToken(),
'PayPal-Request-Id: ' . uniqid()
)
(In PHP) I try to create a simple (sample) order according to the documentation of the REST APIs (see Sample Request)
The request with the following simple data works fine:
{
"intent": "CAPTURE",
"purchase_units": [
{
"amount": {
"currency_code": "EUR",
"value": 100
}
}
]
}
When I try to add the experience_context (https://developer.paypal.com/docs/api/orders/v2/#definition-paypal_wallet_experience_context) according to the Sample Request of the documentation, I get the following answer
The requested URL returned error: 400 Bad Request
{
"intent": "CAPTURE",
"purchase_units": [
{
"amount": {
"currency_code": "EUR",
"value": 100
}
}
],
"payment_source": {
"paypal": {
"experience_context": {
"brand_name": "testmememe",
"cancel_url": "https://example.com/cancelUrl",
"return_url": "https://example.com/returnUrl"
}
}
}
}
What am I doing wrong?
My PayPal-Class:
<?php
class PayPal
{
const CLIENT_ID = 'client_id';
const CLIENT_SECRET = 'client_secret';
const BASE_URL = 'https://api-m.sandbox.paypal.com';
const SESSION_KEY = 'paypal_api';
public function __construct()
{
if(!isset($_SESSION[self::SESSION_KEY])) $_SESSION[self::SESSION_KEY] = array();
}
public function getAccessToken():string
{
if (isset($SESSION[self::SESSION_KEY]['access_token']) && isset($SESSION[self::SESSION_KEY]['access_token_expiration_time']) && $SESSION[self::SESSION_KEY]['access_token_expiration_time'] > time()) return $SESSION[self::SESSION_KEY]['access_token'];
$curl = curl_init();
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FAILONERROR => true,
CURLOPT_URL => self::BASE_URL . '/v1/oauth2/token',
CURLOPT_HTTPHEADER => array(
'Accept: application/json',
'Accept-Language: en_US'
),
CURLOPT_USERPWD => self::CLIENT_ID . ':' . self::CLIENT_SECRET,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => 'grant_type=client_credentials'
);
curl_setopt_array($curl, $options);
$result = curl_exec($curl);
if (curl_errno($curl))
{
print_r(curl_error($curl));
curl_close($curl);
return '';
}
curl_close($curl);
$data = json_decode($result, true);
if (!isset($data['access_token']) || !isset($data['expires_in'])) return '';
$access_token = $data['access_token'];
$SESSION[self::SESSION_KEY]['access_token'] = $access_token;
$SESSION[self::SESSION_KEY]['access_token_expiration_time'] = time() + $data['expires_in'];
return $access_token;
}
public function createOrder()
{
$amount_obj = new stdClass();
$amount_obj->currency_code = 'EUR';
$amount_obj->value = 100.00;
$object = new stdClass();
$object->amount = $amount_obj;
$experience_context = new stdClass();
$experience_context->brand_name = 'testmememe';
$experience_context->cancel_url = "https://example.com/cancelUrl";
$experience_context->return_url = "https://example.com/returnUrl";
$data = array(
'intent' => 'CAPTURE',
'purchase_units' => array(
$object
),
'payment_source' => array(
'paypal' => array(
'experience_context' => $experience_context
)
)
);
$data_string = json_encode($data);
$curl = curl_init();
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FAILONERROR => true,
CURLOPT_URL => self::BASE_URL . '/v2/checkout/orders',
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'Authorization: Bearer ' . $this->getAccessToken()
),
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $data_string
);
curl_setopt_array($curl, $options);
$result = curl_exec($curl);
if (curl_errno($curl))
{
print_r(curl_error($curl));
curl_close($curl);
return '';
}
curl_close($curl);
$data = json_decode($result, true);
if (isset($data['status']) && $data['status'] === 'CREATED' && is_array($data['links']))
{
foreach ($data['links'] as $link)
{
if ($link['rel'] === "approve")
{
$url = $link['href'];
break;
}
}
}
var_dump($data);
echo $url;
}
}
Aufruf:
$paypal_obj = new PayPal;
$paypal_obj->createOrder();
I used the following PayPal IPN script. The code works perfectly when testing using the IPN simulator, but the moment I make it live it doesn't work at all. I've been searching for a solution all over the net. Is there a way to see why it returns invalid? Any ideas?
<?php
$raw_post_data = file_get_contents('php://input');
$raw_post_array = explode('&', $raw_post_data);
$myPost = array();
foreach ($raw_post_array as $keyval) {
$keyval = explode ('=', $keyval);
if (count($keyval) == 2)
$myPost[$keyval[0]] = urldecode($keyval[1]);
}
// read the IPN message sent from PayPal and prepend 'cmd=_notify-validate'
$req = 'cmd=_notify-validate';
if(function_exists('get_magic_quotes_gpc')) {
$get_magic_quotes_exists = true;
}
foreach ($myPost as $key => $value) {
if($get_magic_quotes_exists == true && get_magic_quotes_gpc() == 1) {
$value = urlencode(stripslashes($value));
} else {
$value = urlencode($value);
}
$req .= "&$key=$value";
}
// Step 2: POST IPN data back to PayPal to validate
$ch = curl_init('https://www.paypal.com/cgi-bin/webscr');
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
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);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close'));
if( !($res = curl_exec($ch)) ) {
error_log("Got " . curl_error($ch) . " when processing IPN data", 1, "myemail");
curl_close($ch);
exit;
}
curl_close($ch);
if (strcmp ($res, "VERIFIED") == 0) {
$item_name = $_POST['item_name'];
$item_number = $_POST['item_number'];
$payment_status = $_POST['payment_status'];
$payment_amount = $_POST['mc_gross'];
$payment_currency = $_POST['mc_currency'];
$txn_id = $_POST['txn_id'];
$receiver_email = $_POST['receiver_email'];
$payer_email = $_POST['payer_email'];
$payment_id = $_POST['custom'];
$email_from = "from#email";
$subject = "Your Deep Democracy account has been activated!";
$headers = "From: DD Notifications\r\n";
$headers .= "Reply-To: notifications#deep-democracy.net\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
require_once("../includes/db_connection.php");
mail("myemail", $subject, $payment_id." ".$payer_email, $headers);
//Customs
$result = mysql_query("SELECT * FROM delegate_payments WHERE payment_id='$payment_id' AND payment_completed='No'");
if (mysql_num_rows($result) == 1) {
mysql_query("UPDATE delegate_payments SET payment_completed='Yes' WHERE payment_id='$payment_id'");
$row = mysql_fetch_array($result);
$amount = $row['payment_amount'];
$names_array = explode(', ', $row['payment_content']);
$result2 = mysql_query("SELECT * FROM users WHERE email='$payer_email'");
$row = mysql_fetch_array($result2);
$current_amount = $row['amount_due'];
$new_amount = $current_amount - $amount;
mysql_query("UPDATE users SET amount_due='$new_amount' WHERE email='$payer_email'");
foreach ($names_array as &$value) {
mysql_query("UPDATE users SET activated='1' WHERE email='$value'");
mail($value, $subject, $email_message, $headers);
mail("an#email.com", "Delegate Payment Notification", "Hi Britta, \n\nThis is a notification email to inform you that a new delegate has been paid for. The email address is: {$value}", $headers);
}
}
} else if (strcmp ($res, "INVALID") == 0) {
mail("myemail", "Failed", $res, $headers);}
?>
I am trying to develop a fb app that should send the news feed to a website;
I managed to subscribe using the app_id and app_secret but i don't get the news feed;
public function actionSubscription() {
$app_id = '691036934243090';
$app_secret = 'ca6e828f41c638dba4fb0864f7d9f6e8';
$app_url = 'http://www.ghidul-comercial.ro';
$fields = 'feed';
$verify_token = 'blabla';
// Fetching an App Token
$app_token_url = 'https://graph.facebook.com/oauth/access_token?client_id='
. $app_id . '&client_secret=' . $app_secret
. '&grant_type=client_credentials';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $app_token_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$res = curl_exec($ch);
parse_str($res, $token);
if (isset($token['access_token'])) {
// Let's register a callback
$params = array(
'object'
=> 'page',
'fields'
=> $fields,
'callback_url'
// This is the endpoint that will be called when
// a User updates the location field
=> $app_url . '/index.php/site/api',
'verify_token'
=> $verify_token,
);
curl_setopt($ch, CURLOPT_URL, 'https://graph.facebook.com/'
. $app_id . '/subscriptions?access_token='
. $token['access_token']);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
$res = curl_exec($ch);
if ($res && $res != 'null') {
print_r($res);
}
// Fetch list of all callbacks
curl_setopt($ch, CURLOPT_POST, 0);
$res = curl_exec($ch);
}
if ($res && $res != 'null') {
print_r($res);
}
curl_close($ch);
error_log('test');
}
This is how i intend to catch the feed:
public function actionApi() {
$data = new Data();
$data->info = '1';
$data->save(false);
$method = $_SERVER['REQUEST_METHOD'];
$data = new Data();
$data->info = $method;
$data->save(false);
$rawdata1 = file_get_contents('php://input');
$rawdata2 = json_decode($HTTP_RAW_POST_DATA,true);
$rawdata2 = json_decode(file_get_contents('php://input'),true);
$data = new Data();
$data->info = $rawdata1;
$data->save(false);
if ($method == 'GET' && isset($_GET['hub_mode']) && $_GET['hub_mode'] == 'subscribe' && isset($_GET['hub_verify_token']) && $_GET['hub_verify_token'] == 'blabla') {
echo $_GET['hub_challenge'];
exit;
} elseif ($method == 'POST') {
$post = file_get_contents("php://input");
$data = new Data();
$data->info = $post;
$data->save(false);
}
$data = new Data();
$data->info = '2';
$data->save(false);
}
go to link click Get Access Token , select by click everything from the 3 tabs , click get acccess token , then paste your group id ; also at your feed field and click submit.
That's all ! this will work
My paypalipn.php file looks like,
<?php
$raw_post_data = file_get_contents('php://input');
$raw_post_array = explode('&', $raw_post_data);
$myPost = array();
foreach ($raw_post_array as $keyval) {
$keyval = explode ('=', $keyval);
if (count($keyval) == 2)
$myPost[$keyval[0]] = urldecode($keyval[1]);
}
// read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-validate';
if(function_exists('get_magic_quotes_gpc')) {
$get_magic_quotes_exists = true;
}
foreach ($myPost as $key => $value) {
if($get_magic_quotes_exists == true && get_magic_quotes_gpc() == 1) {
$value = urlencode(stripslashes($value));
} else {
$value = urlencode($value);
}
$req .= "&$key=$value";
}
// STEP 2: Post IPN data back to paypal to validate
$ch = curl_init('https://www.paypal.com/cgi-bin/webscr');
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
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);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close'));
if( !($res = curl_exec($ch)) ) {
// error_log("Got " . curl_error($ch) . " when processing IPN data");
curl_close($ch);
exit;
}
curl_close($ch);
// STEP 3: Inspect IPN validation result and act accordingly
if (strcmp ($res, "VERIFIED") == 0) {
// assign posted variables to local variables
$item_name = $_POST['item_name'];
$item_number = $_POST['item_number'];
$payment_status = $_POST['payment_status'];
$payment_amount = $_POST['mc_gross'];
$payment_currency = $_POST['mc_currency'];
$txn_id = $_POST['txn_id'];
$receiver_email = $_POST['receiver_email'];
$payer_email = $_POST['payer_email'];
} else if (strcmp ($res, "INVALID") == 0) {
}
?>
I have implemented the Paypal into my application. where I can successfully got the profile Id for recurring payments but The response I got from Instant payment Notification was invalid. only that reason was I got ,and also I dont get any more error messages regarding that. so I was looking for your help to get this....
Are you using the Sandbox? The live site won't verify IPNs from the Sandbox, and vice-versa. If the IPN came from the Sandbox, you need to send it back to the Sandbox to verify it.
Try changing this code:
$ch = curl_init('https://www.paypal.com/cgi-bin/webscr');
To this:
if($myPost['test_ipn'] == "1") {
$ch = curl_init('https://www.sandbox.paypal.com/cgi-bin/webscr');
} else {
$ch = curl_init('https://www.paypal.com/cgi-bin/webscr');
}
i'm struggling really hard to implement Facebook connect into my codeigniter application - I have one issue right now. After downloading the PHP SDK from here: https://github.com/facebook/php-sdk/ I copied the /src files into my CI libraries (as everyone do : )).
Now I want to authenticate my users using this method:
https://developers.facebook.com/docs/authentication/server-side/
My controller is here (I think the problem is at the end, but pasted full file, cause i'm not sure):
<?php
class Fb25 extends CI_Controller {
function index()
{
$app_id = "MY APP ID";
$app_secret = "MY SECRET KEY";
$site_url = "http://devlocalhost.com/";
$this->load->library('facebook',array('appId' => $app_id, 'secret' => $app_secret));
$user = $this->facebook->getUser();
$data['user'] = $user;
if($user){
$data['user_profile'] = $this->facebook->api('/me');
$user_profile = $data['user_profile'];
} else{
$user = NULL;
}
if($user){
// Get logout URL
$data['logoutUrl'] = $this->facebook->getLogoutUrl(array(
'next' => 'http://devlocalhost.com/', // URL to which to redirect the user after logging out
));
}else{
// Get login URL
$data['loginUrl'] = $this->facebook->getLoginUrl(array(
'scope' => 'email', // Permissions to request from the user
'redirect_uri' => 'http://devlocalhost.com/fb25/good', // URL to redirect the user to once the login/authorization process is complete.
));
}
if($user){
// Save your method calls into an array
$data['queries'] = array(
array('method' => 'GET', 'relative_url' => '/'.$user),
array('method' => 'GET', 'relative_url' => '/'.$user.'/home?limit=50'),
array('method' => 'GET', 'relative_url' => '/'.$user.'/friends'),
array('method' => 'GET', 'relative_url' => '/'.$user.'/photos?limit=6'),
);
// POST your queries to the batch endpoint on the graph.
$batchResponse = $facebook->api('?batch='.json_encode($queries), 'POST');
//Return values are indexed in order of the original array, content is in ['body'] as a JSON
//string. Decode for use as a PHP array.
$data['user_info'] = json_decode($batchResponse[0]['body'], TRUE);
$data['feed'] = json_decode($batchResponse[1]['body'], TRUE);
$data['friends_list'] = json_decode($batchResponse[2]['body'], TRUE);
$data['photos'] = json_decode($batchResponse[3]['body'], TRUE);
}
echo 'user_info: '.$data['user_info'];
print_r($data);
$this->load->view('fb25_view', $data);
}
public function good(){
$app_id = "MY APP ID";
$app_secret = "MY SECRET KEY";
$site_url = "http://devlocalhost.com/";
echo '<br/><br/>SESJA:<br/>';
print_r($_SESSION);
echo '<br/><br/>GET:<br/>';
print_r($_GET);
echo '<br/><br/>REQUEST:<br/>';
print_r($_REQUEST);
echo '<br/><br/>najs<br/><br/>';
session_start();
$code = $_GET["code"];
//######IMO PROBLEM IS SOMEWHERE HERE:
$token_url = "https://graph.facebook.com/oauth/access_token?"
. "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url)
. "&client_secret=" . $app_secret . "&code=" . $code;
$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$graph_url = "https://graph.facebook.com/me?access_token="
. $params['access_token'];
$user = json_decode(file_get_contents($graph_url));
echo("Hello " . $user->name);
}
}
?>
My problem is: I'm pressing the login button and gets into facebook to authenticate myself, clicking "go to app" and want to go back into my website - it says:
Message: file_get_contents(https://graph.facebook.com/oauth/access_token? client_id=487560264592073&redirect_uri=http%3A%2F%2Fdevlocalhost.com%2F&client_secret=mysecretcode&code=AQAgnmNWwDub9yaRB6Vf73gg8Xvwo8KhIM077lB67_bu1Z3rAvyk3Ckl54qK7hh9o3VkG0rFIBTfRXwtrSBFVWEpqYfm1o7e5CQg3jVctq-EE1ZxWrgWrfesLpQ2oF3wlmEMb5o6ORobGmibT06kqe5f2N0ch4kSYBJ4SiTcdV-612fGOJHGcipeyU_GJJ0Jvsg)
[function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request
UPDATE
Look here, please:
I added function into your controller:
public function link(){
$fb_usr = $this->fb_connect->user;
$firstname = $fb_usr['first_name'];
$my_url="http://devlocal.pl";
echo 'user_id';
$token_url = "https://graph.facebook.com/oauth/access_token?"
. "client_id=myclientid&redirect_uri=" . urlencode($my_url)
. "&client_secret=mysecretcode&code=" . $_GET['code'];
redirect($token_url);
}
To get my access token - without access token I can't get my username..
I made your loginbyfacebook function redirecting into link function. And it doesn't show the fb username.
When I'm redirecting to my token_url It shows:
{
"error": {
"message": "Error validating verification code.",
"type": "OAuthException",
"code": 100
}
}
Follow these steps:
1.Put the facebook php sdk in library folder
2.create facebook config with app detail
3.Inherit facebook class in fb_connect
4.add these function in controller then it will work like charm.
fb_connect.php
<?php
include(APPPATH.'libraries/facebook/facebook.php');
class Fb_connect extends Facebook{
//declare public variables
public $user = NULL;
public $user_id = FALSE;
public $fb = FALSE;
public $fbSession = FALSE;
public $appkey = 0;
//constructor method.
public function __construct()
{
$CI = & get_instance();
$CI->config->load("facebook",TRUE);
$config = $CI->config->item('facebook');
parent::__construct($config);
$this->user_id = $this->getUser(); // New code
$me = null;
if ($this->user_id) {
try {
$me = $this->api('/me');
$this->user = $me;
} catch (FacebookApiException $e) {
error_log($e);
}
}
}
} // end class
Controller function
function loginByFacebook(){
$this->load->library('fb_connect');
$param = array(
'scope' =>'email,user_location,user_birthday,offline_access',
'redirect_uri' => base_url()
);
redirect($this->fb_connect->getLoginUrl($param));
}
function facebook() {
if (!$this->fb_connect->user_id) {
} else {
$fb_uid = $this->fb_connect->user_id;
$fb_usr = $this->fb_connect->user;
$firstname = $fb_usr['first_name'];
}
}
In this way
$fb_usr = $this->fb_connect->user;
$firstname = $fb_usr['first_name'];