Fetch data from our merchant center using the PHP sdk v2 - php

Just give an example like fetching product info or fetching categories. I am using this code. As I am running this code I am not getting any categories. Please provide any example of fetching the data
<?php
namespace Commercetools;
use Commercetools\Api\Client\ClientCredentialsConfig;
use Commercetools\Api\Client\Config;
use Commercetools\Client\ClientCredentials;
use Commercetools\Client\ClientFactory;
require_once __DIR__ . '/vendor/autoload.php';
/** #var string $clientId */
/** #var string $clientSecret */
$clientId = "";
$clientSecret="";
$authConfig = new ClientCredentialsConfig(new ClientCredentials($clientId, $clientSecret));
$client = ClientFactory::of()->createGuzzleClient(
new Config(),
$authConfig
);
use Commercetools\Client\ApiRequestBuilder;
use Commercetools\Client\ImportRequestBuilder;
use Commercetools\Client\MLRequestBuilder;
use GuzzleHttp\ClientInterface;
/** #var ClientInterface $client */
$builder = new ApiRequestBuilder('project-key', $client);
$request = $builder->with()->categories()->get();
$importBuilder = new ImportRequestBuilder('project-key', $client);
$request = $importBuilder->with()->importSinks()->get();
$mlBuilder = new MLRequestBuilder('project-key', $client);
$request = $mlBuilder->with()->recommendations()->generalCategories()->get();
**echo "<pre>";
print_r($request);**

The request has to be executed finally to retrieve the categories.
print_r($request->execute());
Before the execute command the request object is still a RequestBuilder as it's possible to add additional parameters to the Get-Request. In the full example below the configuration for the ML and Import API client has been adjusted as they use a different API Url
<?php
namespace Commercetools;
require_once __DIR__ . '/vendor/autoload.php';
use Commercetools\Api\Client\ClientCredentialsConfig;
use Commercetools\Api\Client\Config;
use Commercetools\Client\ClientCredentials;
use Commercetools\Client\ClientFactory;
/** #var string $clientId */
/** #var string $clientSecret */
$clientId = "";
$clientSecret="";
$projectKey = "";
$authConfig = new ClientCredentialsConfig(new ClientCredentials($clientId, $clientSecret));
$apiClient = ClientFactory::of()->createGuzzleClient(
new Config(),
$authConfig
);
use Commercetools\Client\ApiRequestBuilder;
use Commercetools\Client\ImportRequestBuilder;
use Commercetools\Client\MLRequestBuilder;
use GuzzleHttp\ClientInterface;
/** #var ClientInterface $client */
$builder = new ApiRequestBuilder($projectKey, $apiClient);
$request = $builder->with()->categories()->get();
//$importClient = ClientFactory::of()->createGuzzleClient(
// new Import\Client\Config(),
// $authConfig
//);
//$importBuilder = new ImportRequestBuilder($projectKey, $importClient);
//$request = $importBuilder->with()->importSinks()->get();
//
//$mlClient = ClientFactory::of()->createGuzzleClient(
// new Ml\Client\Config(),
// $authConfig
//);
//
//$mlBuilder = new MLRequestBuilder($projectKey, $mlClient);
//$request = $mlBuilder->with()->recommendations()->generalCategories()->get()->withProductName("test");
echo "<pre>";
print_r($request->execute());

Related

I'm trying PHP Amp client but it's not working, keeps returning error

I'm trying Amp client to return page content but it keeps failing. I've installed the package, and trying the example given by the docs.. but I can't figure out why it's not working. Here's the code:
namespace App\Http\Controllers;
use Amp\Http\Client\HttpClientBuilder;
use Amp\Http\Client\Request;
use Amp\Http\Client\Response;
//use Illuminate\Http\Request;
class AmpConcurrentRequestsController extends Controller
{
public function ampTest1()
{
$httpClient = HttpClientBuilder::buildDefault();
$request = new Request('GET', 'http://example.com');
$promise = $httpClient->request($request);
/** #var Response $response */
$response = Amp\wait($promise);
$statusCode = $response->getStatus();
$body = yield $response->getBody()->buffer();
}
}
I get this error:
Symfony\Component\HttpFoundation\Response::setContent(): Argument #1
($content) must be of type ?string, Generator given, called in
C:\xampp\htdocs\laundarySaaS\vendor\laravel\framework\src\Illuminate\Http\Response.php
on line 72
What eventually worked for me is below code.
public function ampTest1()
{
// Create a new HTTP client
$httpClient = HttpClientBuilder::buildDefault();
// Send a GET request to the specified URL
$request = new Request( 'https://example.com');
$promise = $httpClient->request($request);
/** #var Response $response */
$response = Promise\wait($promise);
// Get the response code
$code = $response->getStatus();
// Do something with the response code
echo $code;
}

Aweber integration using PHP

I am trying to create an auto-login. I don't want my client to login with credentials for this. I am using this library
https://github.com/aweber/public-api-examples/tree/master/php
Created a credentials.ini file like this
clientId = 'xxx'
clientSecret = 'xxx'
accessToken = 'https://auth.aweber.com/oauth2/token'
redirect_uri = 'http://localhost:8080/php-aweber/'
when I try to access the index.php file, It shows an error like this.
//index.php
<?php
require 'vendor/autoload.php';
use GuzzleHttp\Client;
const BASE_URL = 'https://api.aweber.com/1.0/';
// Create a Guzzle client
$client = new GuzzleHttp\Client();
// Load credentials
$credentials = parse_ini_file('credentials.ini');
$accessToken = $credentials['accessToken'];
/**
* Get all of the entries for a collection
*
* #param Client $client HTTP Client used to make a GET request
* #param string $accessToken Access token to pass in as an authorization header
* #param string $url Full URL to make the request
* #return array Every entry in the collection
*/
function getCollection($client, $accessToken, $url) {
$collection = array();
while (isset($url)) {
$request = $client->get($url,
['headers' => ['Authorization' => 'Bearer ' . $accessToken]]
);
$body = $request->getBody();
$page = json_decode($body, true);
$collection = array_merge($page['entries'], $collection);
$url = isset($page['next_collection_link']) ? $page['next_collection_link'] : null;
}
return $collection;
}
// get all of the accounts
$accounts = getCollection($client, $accessToken, BASE_URL . 'accounts');
// get all sharing integration uri's for twitter and facebook
// these are used to create a broadcast that will post to twitter or facebook
// see broadcast example here: https://github.com/aweber/public-api-examples/blob/master/php/create-schedule-broadcast
$integrations = getCollection($client, $accessToken, $accounts[0]['integrations_collection_link']);
echo("Integrations:\n");
foreach ($integrations as $integration) {
if (in_array(strtolower($integration['service_name']), ['twitter', 'facebook'], true)) {
echo "{$integration['service_name']} {$integration['login']} {$integration['self_link']}\n";
}
}
What am I missing or doing wrong?

How to mock in Symfony functionnal tests?

I'm creating functionnal tests on a Symfony 3.4 application.
<?php
namespace AppBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\BrowserKit\Cookie;
use Symfony\Component\HttpFoundation\Response;
class UserControllerTest extends WebTestCase
{
/**
* Connect to the website while being logged in
* Logs in with (admin, password : a)
*/
public function connection()
{
$client = static::createClient();
$container = static::$kernel->getContainer();
$session = $container->get('session');
// Get the user (has to exist in the database)
$person = self::$kernel->getContainer()->get('doctrine')->getRepository('AppBundle:User')->findOneByUsername('admin');
$token = new UsernamePasswordToken($person, null, 'main', $person->getRoles());
$session->set('_security_main', serialize($token));
$session->save();
$client->getCookieJar()->set(new Cookie($session->getName(), $session->getId()));
// Return the client
return $client;
}
public function accessEditPage()
{
$client = $this->connection();
$crawler = $client->request('GET', '/user/');
$this->assertSame(Response::HTTP_OK, $client->getResponse()->getStatusCode());
$this->assertContains(
'Liste des utilisateurices',
$client->getResponse()->getContent()
);
// Select the button of the user created for the test
// Wont work if there are already more than 10 users in the database
$link = $crawler
->filter('tr > td > a:contains("")')
->last()
->link()
;
$crawler = $client->click($link);
return array($client,$crawler);
}
/**
* Create a new user
*/
public function testCreate()
{
$client = $this->connection();
$crawler = $client->request('GET', '/user/new');
$this->assertSame(Response::HTTP_OK, $client->getResponse()->getStatusCode());
// Vérifie si la page affiche le bon texte
$this->assertContains(
'Enregistrer',
$client->getResponse()->getContent()
);
// Select the form and fill its values
$form = $crawler->selectButton(' Créer')->form();
$values = $form->getPhpValues();
$values['appbundle_user']['username'] = 'Jean';
$values['appbundle_user']['plainPassword']['first'] = 'motdepasse';
$values['appbundle_user']['plainPassword']['second'] = 'motdepasse';
$crawler = $client->request($form->getMethod(), $form->getUri(), $values,$form->getPhpFiles());
$crawler = $client->followRedirect();
$this->assertContains(
'Jean',
$client->getResponse()->getContent()
);
}
}
Currently, my Controller tests create databases entries and depends on existing ones and that's a problem.
I want to mock the repositories used in the controller to avoid creating entries when I test my controllers but I haven't found helpful documentation about it. As I can't find documentation, I also wonder if what I want to do is a good practice or not.

Symfony 2.8 WebTestCase: Cannot create logged-in session

I am currently working on unit testing my symfony 2.8 based admin area.
So I wrote a small basic test for the dashboard: The tests checks that
a) If the user is currently not logged in, there should be a redirect to the login page.
b) If the user is logged in, the dashboard should be shown.
In order to "log in" the user ( = to create an active session) I came up with a small helper function that is based on the respective cookbook article from the symfony documentation: How to Simulate Authentication with a Token in a Functional Test
This however does not seem to work. My initial tests fails. So I have added another request to a dummy controller that only prints out session information. This shows that while the seems to be set correctly, the current user information and the security token storage seem to be incorrect - as I get the default "AnonymousToken" and a null return from the getUser method.
Here is my test code:
<?php
namespace GOC\Bundle\AdminBundle\Tests\Controller;
use FOS\RestBundle\Util\Codes;
use Symfony\Bundle\FrameworkBundle\Client;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\BrowserKit\Cookie;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\NullOutput;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use GOC\Bundle\FrameworkBundle\Model\ContextInterface;
use GOC\Bundle\FrameworkBundle\Tests\WebTestCase;
class DashboardControllerTest extends WebTestCase
{
const BASE_URL = '';
/**
* #var ContextInterface|null
*/
protected $context;
public static function setUpBeforeClass()
{
$client = static::createClient([
'environment' => 'test',
'debug' => false,
], [
'HTTP_HOST' => 'demo-cms.dev',
]);
$container = $client->getContainer();
$kernel = $container->get('kernel');
$application = new Application($kernel);
$application->setAutoExit(false);
$input = new ArrayInput(array(
'command' => 'doctrine:mongodb:fixtures:load',
));
$output = new NullOutput();
$application->run($input, $output);
}
/**
* Testing whether the backend is not publicly accessible
*/
public function testFirewallRedirect()
{
$client = static::createClient();
$client->request('GET', $this->buildUrl('/admin/dashboard'));
$response = $client->getResponse();
$this->assertTrue($client->getResponse()->isRedirect($this->buildUrl('http://localhost/admin/login')));
$crawler = $client->request('GET', $response->headers->get('location'));
$this->assertEquals(
1,
$crawler->filter('html:contains("Willkommen")')->count()
);
}
/**
* Testing whether the backend is not publicly accessible
*/
public function testFirewallAccess()
{
$client = static::createClient([
'environment' => 'test',
'debug' => false,
], [
'HTTP_HOST' => 'demo-cms.dev',
]);
$this->logIn($client);
$client->request('GET', $this->buildUrl('/admin/dashboard'));
$response = $client->getResponse();
// This fails...
//$this->assertEquals(Codes::HTTP_OK, $response->getStatusCode());
// Debug statements
$client->request('GET', $this->buildUrl('/forgot-password-sent'));
$response = $client->getResponse();
dump($response);
}
/**
* #param Client $client
*/
protected function logIn(Client $client)
{
$container = $client->getContainer();
$repository = $container->get('goc_account.user_manager')->getRepository();
$user = $repository->getUserByUsername('admin#gardenofconcepts.com', $this->getContext($client));
$firewall = 'main';
$token = new UsernamePasswordToken($user, null, $firewall, $user->getRoles());
$container->get('security.token_storage')->setToken($token);
$session = $container->get('session');
// Saw this somewhere else, makes no difference though
//$session = new Session(new MockArraySessionStorage());
//$session->start();
//$container->set('session', $session);
$session->set('_security_'.$firewall, serialize($token));
$session->save();
$cookie = new Cookie($session->getName(), $session->getId());
$client->getCookieJar()->set($cookie);
}
/**
* #param $url
*
* #return string
*/
protected function buildUrl($url)
{
return $this::BASE_URL . $url;
}
/**
* #param Client $client
*
* #return ContextInterface
*/
protected function getContext(Client $client)
{
if ($this->context) {
return $this->context;
}
$this->context = $client->getContainer()->get('goc_framework.context_manager')->getContextByName('demo');
return $this->context;
}
}
Thanks in advance for any help - it's highly appreciated !
We are not trying to mock the token but actually create one with the following function (which might be adaptable to your situation):
protected function createAuthenticatedClient($username, $password)
{
$client = static::createClient();
$client->request(
'POST',
'/api/v1/login_check',
array(
'username' => $username,
'password' => $password,
)
);
$data = json_decode($client->getResponse()->getContent(), true);
$client = static::createClient();
$client->setServerParameter('HTTP_Authorization', sprintf('Bearer %s', $data['token']));
return $client;
}
After using this like
$client = $this->createAuthenticatedClient('user', 'password');
every request sent will be attached with our actual Bearer.

Bigquery + PHP examples

Can somebody provide working example of using the Bigquery API with PHP. I see there are examples for python and java but could not find anything for PHP.
Here is the bigquery browser https://bigquery.cloud.google.com/?pli=1
For e.g You can run this SQL in the browser
SELECT corpus,count(*) FROM publicdata:samples.shakespeare
group by corpus limit 5;
I want to simulate similar call via PHP.
Even a rough example of how to use the PHP API will help a lot.
Use the Google API Client for PHP. Here's a simple example of a script that does a single synchronous query job. This uses the class names found in the downloadable API client. Note: the source pulled from SVN features different class names. Note where you must add your own values for client secret, client id, redirect URI, and project id.
<?php
require_once 'google-api-php-client/src/apiClient.php';
require_once 'google-api-php-client/src/contrib/apiBigqueryService.php';
session_start();
$client = new apiClient();
// Visit https://developers.google.com/console to generate your
// oauth2_client_id, oauth2_client_secret, and to register your oauth2_redirect_uri.
$client->setClientId('XXXXXXXXXXXXXXX.apps.googleusercontent.com');
$client->setClientSecret('XXXXXXXXXXXXXXXXXXX');
$client->setRedirectUri('http://www_your_domain.com/somescript.php');
// Your project id
$project_id = 'XXXXXXXXXXXXXXXXXXXX';
// Instantiate a new BigQuery Client
$bigqueryService = new apiBigqueryService($client);
if (isset($_REQUEST['logout'])) {
unset($_SESSION['access_token']);
}
if (isset($_SESSION['access_token'])) {
$client->setAccessToken($_SESSION['access_token']);
} else {
$client->setAccessToken($client->authenticate());
$_SESSION['access_token'] = $client->getAccessToken();
}
if (isset($_GET['code'])) {
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
?>
<!doctype html>
<html>
<head>
<title>BigQuery API Sample</title>
</head>
<body>
<div id='container'>
<div id='top'><h1>BigQuery API Sample</h1></div>
<div id='main'>
<?php
$query = new QueryRequest();
$query->setQuery('SELECT TOP( title, 10) as title, COUNT(*) as revision_count FROM [publicdata:samples.wikipedia] WHERE wp_namespace = 0;');
$jobs = $bigqueryService->jobs;
$response = $jobs->query($project_id, $query);
// Do something with the BigQuery API $response data
print_r($response);
?>
</div>
</div>
</body>
</html>
The previous answers have outdated code. The following example should work with the more recent API (https://github.com/google/google-api-php-client/blob/master/src/Google/Service/Bigquery.php) :
require_once '../source/application/libraries/Google/autoload.php';
public function createGClient(){
define("CLIENT_ID", "{PROJECT_ID}.apps.googleusercontent.com");
define("SERVICE_ACCOUNT_NAME","{SERVICE_ACCOUNT EMAIL FROM CONSOLE}");
define("KEY_FILE",'../{FILENAME}.p12');
define("PROJECT_ID","{PROJECT_ID}");
define("DATASET_ID","{DATASET_ID}");
define("TABLE_ID","");
$this->client = new Google_Client();
$this->client->setApplicationName("{NAME}");
$key = file_get_contents(KEY_FILE);
$this->client->setAssertionCredentials(new Google_Auth_AssertionCredentials(SERVICE_ACCOUNT_NAME, array('https://www.googleapis.com/auth/bigquery'), $key, "notasecret"));
$this->client->setClientId(CLIENT_ID);
$this->service = new Google_Service_Bigquery($this->client);
}
public function runQuery(){
// To see the a list of tables
print_r($this->service->tables->listTables(PROJECT_ID, DATASET_ID));
// To see details of a table
print_r($this->service->tables->get(PROJECT_ID, DATASET_ID, TABLE_ID));
// To query a table
$jobs = $this->service->jobs;
$query = new Google_Service_Bigquery_QueryRequest();
$query->setQuery("SELECT * FROM wherever;");
$response = $jobs->query(PROJECT_ID, $query);
print_r($response);
}
This is a modified version of the sample given at: http://michaelheap.com/using-the-php-sdk-with-google-bigquery/ for a service account. To use a client account you would need to use oauth2 and have a pingback address.
I had a lot of issues finding examples.
This is a basic async query, but can demonstrate current PHP API usage, you can see the Python/Java example of the API for async queries here: https://developers.google.com/bigquery/querying-data
Please note, I am not referencing how to setup $client credentials, as it is well documented elsewhere.
$bq = new Google_BigqueryService($client);
//build query
$sql = 'select * from example.table LIMIT 10';
$job = new Google_Job();
$config = new Google_JobConfiguration();
$queryConfig = new Google_JobConfigurationQuery();
$config->setQuery($queryConfig);
$job->setConfiguration($config);
$queryConfig->setQuery($sql);
$insert = new Google_Job($bq->jobs->insert(PROJECT_ID,$job));
$jr = $insert->getJobReference();
$jobId = $jr['jobId'];
$res = new Google_GetQueryResultsResponse($bq->jobs->getQueryResults(PROJECT_ID, $jobId));
//see the results made it as an object ok:
var_dump($results);
/**
* Executes and returns bigQuery response with 'INTERACTIVE' priority
* $this->service is the object of Google_Service_Bigquery
* $this->service = new Google_Service_Bigquery($this->client);
* #param String $sql
* #return Google_Service_Bigquery_GetQueryResultsResponse
*/
public function execute($sql) {
$job = new Google_Service_Bigquery_Job();
$config = new Google_Service_Bigquery_JobConfiguration();
$queryConfig = new Google_Service_Bigquery_JobConfigurationQuery();
$queryConfig->setQuery($sql);
/**
* Priority is set to INTERACTIVE for faster response options are 'BATCH'/'INTERACTIVE'
*/
$queryConfig->setPriority("INTERACTIVE");
$config->setQuery($queryConfig);
$job->setId(md5("$sql_{microtime()}"));
$job->setConfiguration($config);
$running = $this->service->jobs->insert('divine-builder-586', $job);
/* #var $running Google_Service_Bigquery_Job */
$jr = $running->getJobReference();
$jobId = $jr['jobId'];
$res = $this->service->jobs->getQueryResults('divine-builder-586', $jobId);
/* #var $res Google_Service_Bigquery_GetQueryResultsResponse */
return $res;
}

Categories