Laravel GoCardless - php

I'm integrating Laravel with GoCardless to allow my users to take card payments however I'm struggling installing the GoCardless php wrapper.
I've followed the following doc:
https://developer.gocardless.com/getting-started/partners/building-an-authorisation-link/
It says to use the following, am I right in saying this will go in my controller? surely with Laravel I wouldnt need to require the vendor/autoload?
<?php
require 'vendor/autoload.php';
// You should store your client ID and secret in environment variables rather than
// committing them with your code
$client = new OAuth2\Client(getenv('GOCARDLESS_CLIENT_ID'), getenv('GOCARDLESS_CLIENT_SECRET'));
$authorizeUrl = $client->getAuthenticationUrl(
// Once you go live, this should be set to https://connect.gocardless.com. You'll also
// need to create a live app and update your client ID and secret.
'https://connect-sandbox.gocardless.com/oauth/authorize',
'https://acme.enterprises/redirect',
['scope' => 'read_write', 'initial_view' => 'login']
);
// You'll now want to direct your user to the URL - you could redirect them or display it
// as a link on the page
header("Location: " . $authorizeUrl);
Apologies, if someone can point me in the right direction I would appreciate.
My controller currently looks like.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
class goCardlessController extends Controller
{
public function index()
{
$client = new OAuth2\Client(env('GOCARDLESS_CLIENT_ID'), env('GOCARDLESS_CLIENT_SECRET'));
$authorizeUrl = $client->getAuthenticationUrl(
'https://connect-sandbox.gocardless.com/oauth/authorize',
'REDIRECT_URL',
['scope' => 'read_write', 'initial_view' => 'login']
);
header("Location: " . $authorizeUrl);
}
}
but I get the error:
Class 'App\Http\Controllers\OAuth2\Client' not found
Which makes sense because I haven't defined it in my controller but Im wondering how I would do this?

Try this in your controller:
use Oauth2;
Or alternatively, $client = new \OAuth2\Client(.... Do note the \ before Oauth2

Related

Cannot get oAuth to work with Laravel and BigCommerce App

I am having issues setting up the "One-Click-App" oAuth on Bigcommerce with the BC PHP API library.
The issue at the moment is getting the actual auth token. I've tried various methods and believe it's down to the (Code/Context/Scope) get requests. They return as null every time.
I've tried both:
$request->query('code');
$request->get('code');
On the BC app launch screen I am presented with:
Trying to get property 'access_token' of non-object
Which of course is because the token is returning null.
Here is my controller in Laravel
namespace App\Http\Controllers;
use \Illuminate\Http\Request;
use Bigcommerce\Api\Client as Bigcommerce;
class BController extends Controller
{
//
public function index(Request $request)
{
$object = new \stdClass();
$object->client_id = 'xxxxxxxxxxxxxx';
$object->client_secret = 'xxxxxxxxxxxxxxxx';
$object->redirect_uri = 'https://linkto/process_oauth_result';
$object->code = $request->query('code');
$object->context = $request->query('context');
$object->scope = $request->query('scope');
Bigcommerce::useJson();
$authTokenResponse = Bigcommerce::getAuthToken($object);
// configure BC App
Bigcommerce::configure([
'client_id' => env('xxxxxxxxxxxxxx'),
'auth_token' => $authTokenResponse->access_token,
'store_hash' => 'xxxxxxx'
]);
Bigcommerce::verifyPeer(false);
return 'Success!';
}
}
Well it turns out that this works fine. I am using Runcloud to manage the app and the click-jacking option was blocking the iframe on the app screen!

Basic auth with Slim no response

I am implementing a basic auth with Slim and REST. I have installed the basic auth via Composer and used the below code.
<?php
require 'confing.php';
require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim;
$app->add(new \Slim\Middleware\HttpBasicAuthentication([
"path" => "/admin", /* or ["/admin", "/api"] */
"realm" => "Protected",
"users" => [
"root" => "t00r",
"user" => "passw0rd"
],
"callback" => function ($request, $response, $arguments) {
print_r($arguments);
}
]));
$app->get('/getLaboorState/:laboor_id', function($laboor_id) use ($app) {
$db =getDB();
$sql="SELECT status FROM laboor WHERE laboor_id='".$laboor_id."'";
$stmt = $db->query($sql);
$items = $stmt->fetchAll();
echo json_encode($items);
});
$app->run();
?>
When I am trying now to connect the /getLaboorState with Postman it returns nothing. I used same username and password in postman and nothing shows, but when I take the basic auth it works fine.
Other questions is, after implement the basic auth, how can I restrict all slim api to go throw each api before run the query?
This is a pic from Postman:
Note: then I want to use the API with AJAX.
you need to use $authenticate($app) to restrict all slim api to go throw each api before run the query
$app->get('/profile(/)(:id)', $authenticate($app), function($laboor_id) use ($app) {
//Your logic here
})->name('profile');
$authenticate = function ($app) {
return function () use ($app) {
//your logic here
if (!isset($_SESSION['ID'])) {
$app->redirect($app->urlFor('loginpage'));
}
};
};
Use bellow code to display the exact error coming while calling Ajax request
header('Access-Control-Allow-Origin: *');
ini_set('display_errors', 1);
error_reporting(E_ALL);
Hope this helps, Accept the answer if it works.. or comment
You have configured two users:
Username root with password t00r
Username user with password passw0rd
According to your screenshot you are trying to use username t00r with password passw0rd. This does not exist in your configuration. Use one of the username password combinations mentioned above.

How to a users Google+ cover programticly

I had a problem with updating user cover pic using php(zend framework) and Oauth.
I have added to my composer.json the following lines:
"require" : {
"google/auth": "0.7",
"google/apiclient" : "^2.0.0#RC"
}
After that I made composer-install + composer-update using and oppp I get the library inside my vendor.
I have configured my application inside google developing console, following the official tutorial by google :D
Now inside my controller I could easily request google web service using this method :
public function googleplusAction()
{
Zend_Loader::loadFile("HttpPost.class.php");
$client_id = "id_here";
$client_secret = "secret_here";
$application_name = "application_name_here";
$redirect_uri = "redirection_uri_here";
$oauth2_server_url = 'https://accounts.google.com/o/oauth2/auth';
$query_params = array(
'response_type' => 'code',
// The app needs to use Google API in the background
'client_id' => $client_id,
'redirect_uri' => $redirect_uri,
'scope' => 'https://www.googleapis.com/auth/userinfo.profile'
);
$forward_url = $oauth2_server_url . '?' . http_build_query($query_params);
header('Location: ' . $forward_url);
}
After that I get redirected to my redirection URI , and in the bar address I get a new variable 'code'.
Until now, I hope everything is fine , coming to the most important part , the controller of the redirection URI page , using the 'code' variable that I have talked about it before I tried to get an access token, but I was failed.
This is the method that should set a new cover picture on google plus :
$client_id = "client-id";
$client_secret = "g+-secret";
$application_name = "my-app-name";
$redirect_uri = "my-uri-on-g+";
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$service = new Google_Service_Oauth2($client);
$client->addScope(Google_Service_Oauth2::USERINFO_PROFILE);
$client->authenticate($_GET['code']); // I have the right code, and I am being authenticated
$plus = new Google_Service_Plus($client);
$person = $plus->people->get('me');
var_dump($person);
$pic = $this->session->image['generatedAbs'];
$gimg = new Google_Service_Plus_PersonCover();
$source = new Google_Service_Plus_PersonCoverCoverPhoto();
$source ->setUrl("$photo-that-i-wanted-to-put-on-g+");
$gimg->setCoverPhoto($source);
$person->setCover($gimg);}
So my questions are :
How can I change my google plus cover picture to a new png or JPEG picture that I have already in my project ?
inside the G+ library I found this method :
Google_Service_Plus_PersonCoverCoverPhoto();
inside a class called
Google_Service_Plus_PersonCover();
But how can I use it ?
I think that methods Google_Service_Plus_PersonCoverCoverPhoto() and Google_Service_Plus_PersonCover() are used by the client library to set it when the information is retrieved. It is not meant for you to be able to update the users cover on Google+, if that does work it will only update the class object which really there is no point in doing (IMO).
var_dump($person->Cover);
If you check the Plus.People documentation you will notice there are no update or patch methods. This is because its not possible to update a users information programmatically at this time.
Answer: Your inability to update the users cover picture has nothing to do with Oauth it has to do with the fact that this is not allowed by the API. Unfortunately it looks like you have done a lot of work for nothing this is why it is good to always consult the documentation before you begin you would have seen that it was not possible, and could have avoided a lot of unnecessary stress on yourself.

Facebook API Real Time updates for Page/Feed no response

I have a problem with Facebook Real-time subscription from my facebook page.
When I POST a subscription, i get the message from facebook about it to my call back url.
Code:
$session = new FacebookSession('<APP ACCESS TOKEN>');
$request = new FacebookRequest(
$session,
'POST',
'/<APP ID>/subscriptions',
array(
'object' => 'page',
'callback_url' => 'http://*************/facebook/callback.php',
'fields' => 'conversation', // a try 'feed' to
'verify_token' => '<VERIFY TOKEN>',
)
);
$response = $request->execute();
BUT when someone add a post/conversation to my fb page, facebook don't send me any data.
callback.php code:
<?php
// Insert the path where you unpacked log4php
include('log4php/Logger.php');
// Tell log4php to use our configuration file.
Logger::configure('config.xml');
// Fetch a logger, it will inherit settings from the root logger
$log = Logger::getLogger('myLogger');
// Start logging
$log->warn($_REQUEST); // Logged because WARN >= WARN
require_once __DIR__ . '/facebook-php-sdk-v4-5.0-dev/src/Facebook/autoload.php';
use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\Authentication\AccessToken;
use Facebook\GraphUser;
use Facebook\FacebookRequestException;
//define('VERIFY_TOKEN', '*******');
$method = $_SERVER['REQUEST_METHOD'];
if ($method == 'GET' && $_GET['hub_mode'] == 'subscribe' && $_GET['hub_verify_token'] == '<VERIFY TOKEN>') {
echo $_GET['hub_challenge'];
$log->warn($_GET);
$log->warn($_POST);
} else if ($method == 'POST') {
$updates = json_decode(file_get_contents("php://input"), true);
// Here you can do whatever you want with the JSON object that you receive from FaceBook.
// Before you decide what to do with the notification object you might aswell just check if
// you are actually getting one. You can do this by choosing to output the object to a textfile.
// It can be done by simply adding the following line:
// file_put_contents('/filepath/updates.txt',$updates, FILE_APPEND);
$log->warn($updates);
$log->warn($_GET);
$log->warn($_POST);
error_log('updates = ' . print_r($obj, true));
}
Thank you for your help !
There is currently an open bug with Facebook support:
https://developers.facebook.com/bugs/709097499224897/
So it's possible that this is a temporary issue...
What's the output of /{your-app-id}/subscriptions?
According to your code you subscribed to /conversations which requires read_page_mailboxes permissions. You probably want to try a simple page feed subscription first to see if this works.
RTU updates seem to be back to normal since yesterday, but deleting your subscriptions and re-subscribing might be worth a try, too, since you probably subscribed to a black hole when RTU had issues yesterday.
I find answer with a big help from facebook developers forum friends :)
My code to make subscription and callback code is good. But to get conversations or feed it is not enough. I have to add my app to my page as a subscribed_app using request in graph api:
POST
{page-id}/subscribed_apps
the docs for this operation is on:
https://developers.facebook.com/docs/graph-api/reference/page/subscribed_apps/

How to get the iframe code for a private video with dailymotion api

I would like to use dailymotion api to get infos of my own private videos.
SO ...
I have a Dailymotion account
I have created an API key and secret key
I downloaded the PHP class
I would like to get infos of my privates videos to diplay it on my website...
So i think I need to authenticate my account and after get the code...
but it does not work :'(
Please could you give me a sample code to do this ?
my test code is like that for now
<?php
error_reporting(E_ALL & ~E_NOTICE);
ini_set('display_errors', 1);
$apiKey = 'xxxx';
$apiSecret = 'xxxx';
require_once 'Dailymotion.php';
// Instanciate the PHP SDK.
$api = new Dailymotion();
// Tell the SDK what kind of authentication you'd like to use.
// Because the SDK works with lazy authentication, no request is performed at this point.
$api->setGrantType(Dailymotion::GRANT_TYPE_AUTHORIZATION, $apiKey, $apiSecret);
$api = new Dailymotion();
try
{
$result = $api->get(
'/video/privateVideoId',
array('fields' => array('id', 'title', 'owner'))
);
}
catch (DailymotionAuthRequiredException $e)
{
echo $e->getMessage();
// If the SDK doesn't have any access token stored in memory, it tries to
// redirect the user to the Dailymotion authorization page for authentication.
//return header('Location: ' . $api->getAuthorizationUrl());
}
catch (DailymotionAuthRefusedException $e)
{
echo $e->getMessage();
// Handle the situation when the user refused to authorize and came back here.
// <YOUR CODE>
}
trace($result);
function trace($d) {
echo '<pre>';
var_dump($d);
echo '</pre>';
}
?>
and the result is :
This user is not allowed to access this video.
so i think there is a problem with authentication ... but i do not understant how to do that only with php
thanks a lot for your help
It looks like there are a couple of issues in your code and in the way you authenticate:
1) your code: you call $api = new Dailymotion(); and then set the authorization grant type with your api key and secret. But next line, you override all that by re-writing $api = new Dailymotion();. So I recommend you to remove this line, otherwise it is like you have not set any grant type!
2) There is an interesting code sample regarding authorization grant type in php, doing exactly what you're trying to do, at https://developer.dailymotion.com/tools/sdks#sdk-php-grant-authorization
Your code is very similar, why did you comment the return header('Location: ' . $api->getAuthorizationUrl()); part when catching DailymotionAuthRequiredException ? This part redirects the user to the auth page so he/she can authenticate.
I also recommend to have a look at others grant types for authentication, such as password grant type (https://developer.dailymotion.com/tools/sdks#sdk-php-grant-password)

Categories