Aweber integration using PHP - 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?

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;
}

Fetch data from our merchant center using the PHP sdk v2

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());

Use Authenticated Google Client instance for multiple services

I am creating google client instance and authenticating it once and fetching required data. Afterwards if I want to use that same instance of Google client for some other service , how can I achieve it ?
webmasterMain route is my redirect uri registered in google webmaster .
public function webmasterMain(Request $request)
{
$requestData = $request->all();
if ($request->isMethod('POST') || isset($requestData['code'])) {
$google_redirect_url = env('APP_URL') . '/user/webmasterMain';
$gClient = new \Google_Client();
$gClient->setAccessType("offline");// to get refresh token after expiration of access token
$gClient->setIncludeGrantedScopes(true); // incremental auth
$gClient->setApplicationName(config('services.google.app_name'));
$gClient->setClientId(config('services.google.client_id'));
$gClient->setClientSecret(config('services.google.client_secret'));
$gClient->setRedirectUri($google_redirect_url);
$gClient->setDeveloperKey(config('services.google.api_key'));
$gClient->setScopes(array(
'https://www.googleapis.com/auth/plus.me',
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile',
'https://www.googleapis.com/auth/webmasters.readonly',
'https://www.googleapis.com/auth/webmasters',
));
$google_oauthV2 = new \Google_Service_Oauth2($gClient);
if ($request->get('code')) {
$gClient->authenticate($request->get('code'));
$request->session()->put('token', $gClient->getAccessToken());
}
if ($request->session()->get('token')) {
$gClient->setAccessToken($request->session()->get('token'));
}
if ($gClient->getAccessToken()) {
$inst = new Google_Service_Webmasters($gClient);
$res = $inst->sites->listSites();
$sites = $res->getSiteEntry();
$siteUrl = [];
foreach ($sites as $key => $site) {
$siteUrl = array_add($siteUrl, $key, ['site_name'=>$site['siteUrl'], 'site_permission_level' => $site['permissionLevel']]);
}
$sites = (((array)$siteUrl));
return view('User::webmasterMain')->with(['data' => $sites]);
} else {
//For Guest user, get google login url
$authUrl = $gClient->createAuthUrl();
return redirect()->to($authUrl);
}
}
return view('User::webmasterMain');
}
Now suppose I want to get the authenticated $gClient for service like Google_Service_Webmasters_SearchAnalyticsQueryRequest , then how can I make $client = $gClient for this next request ?
public function query(Request $request){
//suppose $client is the same instance which was previously authenticated and stored in $gClient
$website = "http://example.com/";
$searchAnalytics = new \Google_Service_Webmasters_SearchAnalyticsQueryRequest();
$searchAnalytics->setStartDate('2017-03-01');
$searchAnalytics->setEndDate('2017-03-31');
$searchAnalytics->setDimensions(['page']);
$searchAnalytics->setSearchType('web');
`$results = $client->searchanalytics->query($website, $searchAnalytics);`
return $results->getRows();
I got the answer , no need to save the instance or do anything but, follow this :
Create a Google Client Object.
At first time authenticating save the accessToken from google client object by getAccessToken().
Use the same access token and set Access token in this google client.
now you can use this google client object for any service.
First time authenticating:
$gClient = new \Google_Client();
//after authenticating
$request->session()->put('token', $gClient->getAccessToken());
Now we can use this access token in any google service call:
$gClient = new \Google_Client();
if ($request->session()->get('token')) {
$gClient->setAccessToken($request->session()->get('token'));
}
$client = new Google_Service_Webmasters($gClient);

oAuthRequest returns empty array

I have created a Twitter application for a website. I would like to integrate the possibility of logging in/registering with Twitter. I am using php files as helpers, which are named TwitterOAuth.php and OAuth.php, respectively. When a user clicks on the Twitter button, he/she is redirected to a page called twitter.php, which has the following source-code:
<?php
/* Build TwitterOAuth object with client credentials. */
$connection = Common::twitter();
/* Get temporary credentials. */
$request_token = $connection->getRequestToken(App::env()->get('url'));
/* Save temporary credentials to session. */
$token = $request_token['oauth_token'];
$_SESSION['twitter'] = array('id' => $request_token['oauth_token'], 'token' => $request_token['oauth_token_secret']);
/* If last connection failed don't display authorization link. */
switch ($connection->http_code) {
case 200:
/* Build authorize URL and redirect user to Twitter. */
$url = $connection->getAuthorizeURL($token);
header('Location: ' . $url);
break;
default:
/* Show notification if something went wrong. */
var_dump($request_token);
echo 'Could not connect to Twitter. Refresh the page or try again later.';
}
The Common::twitter() function is as follows:
/**
* Returns the twitter OAuth service.
*
* #return TwitterOAuth
*/
public static function twitter() {
if (!self::$tw) {
if ((User::isLoggedIn()) && (User::current()->hasTwitterAccount())) {
self::$tw = new TwitterOAuth(
App::env()->get('twitter', 'consumerKey'),
App::env()->get('twitter', 'consumerSecret'),
App::CurrentUser()->getTwitterId(),
App::CurrentUser()->getTwitterUserAccessToken()
);
} else {
self::$tw = new TwitterOAuth(
App::env()->get('twitter', 'consumerKey'),
App::env()->get('twitter', 'consumerSecret')
);
}
}
return self::$tw;
}
In the scenario I am testing with, the else branch is executed. However, I get an exception:
Exception 'PHPErrorException' with message 'Notice [8] Undefined
index: oauth_token Error on line 81 in file ...\lib\TwitterOAuth.php
The function where the problem occurs is as follows:
/**
* Get a request_token from Twitter
*
* #returns a key/value array containing oauth_token and oauth_token_secret
*/
function getRequestToken($oauth_callback) {
$parameters = array();
$parameters['oauth_callback'] = $oauth_callback;
$request = $this->oAuthRequest($this->requestTokenURL(), 'GET', $parameters);
$token = OAuthUtil::parse_parameters($request);
$this->token = new OAuthConsumer($token['oauth_token'], $token['oauth_token_secret']);
return $token;
}
The problem is that OAuthUtil::parse_parameters($request) returns an empty array. This is happening, because $request is false, however, $this->requestTokenURL is https://api.twitter.com/oauth/request_token, $parameters has an oauth_callback, which holds the callback URL defined in the Twitter application. What could be the cause of this issue?
EDIT:
Source of `$this->oAuthRequest`:
/**
* Format and sign an OAuth / API request
*/
function oAuthRequest($url, $method, $parameters) {
if (strrpos($url, 'https://') !== 0 && strrpos($url, 'http://') !== 0) {
$url = "{$this->host}{$url}.{$this->format}";
}
$request = OAuthRequest::from_consumer_and_token($this->consumer, $this->token, $method, $url, $parameters);
$request->sign_request($this->sha1_method, $this->consumer, $this->token);
switch ($method) {
case 'GET':
return $this->http($request->to_url(), 'GET');
default:
return $this->http($request->get_normalized_http_url(), $method, $request->to_postdata());
}
}
This method is inside of TwitterOAuth.php.
In OAuth.php there was a code chunk in the get_normalized_http_url method, namely:
$port = #$parts['port'];
This caused some errors, so I have fixed it like this:
$port = (array_key_exists('port', $parts) ? $parts['port'] : 80);
However, apparently port number 80 was the problem and after I changed the chunk to this:
$port = (array_key_exists('port', $parts) ? $parts['port'] : 443);
it worked like a spell.

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