Cannot read data from Patreon JSON API - php

Using the code given from Packagist (https://packagist.org/packages/patreon/patreon?q=&p=6), I am unable to get the expected results. My code now logs the user in, and returns their data (which I can view via var_dump), but I'm having issues actually reading it.
According to the Patreon API documentation, the data received from the API is automatically set as an array, unless specified otherwise. I'm running the exact code from their website but their API is returning an object, and I'm not sure how to read the user's data and pledge information from it. I've tried setting the return data as an array or json without any luck. I'm just getting this jumbled mess when I convert the API response into an array.
Screenshot - https://i.gyazo.com/3d19f9422c971ce6e082486cd01b0b92.png
require_once __DIR__.'/vendor/autoload.php';
use Patreon\API;
use Patreon\OAuth;
$client_id = 'removed';
$client_secret = 'removed';
$redirect_uri = "https://s.com/redirect";
$href = 'https://www.patreon.com/oauth2/authorize?response_type=code&client_id=' . $client_id . '&redirect_uri=' . urlencode($redirect_uri);
$state = array();
$state['final_page'] = 'http://s.com/thanks.php?item=gold';
$state_parameters = '&state=' . urlencode( base64_encode( json_encode( $state ) ) );
$href .= $state_parameters;
$scope_parameters = '&scope=identity%20identity'.urlencode('[email]');
$href .= $scope_parameters;
echo 'Click here to login via Patreon';
if (isset($_GET['code']))
{
$oauth_client = new OAuth($client_id, $client_secret);
$tokens = $oauth_client->get_tokens($_GET['code'], $redirect_uri);
$access_token = $tokens['access_token'];
$refresh_token = $tokens['refresh_token'];
$api_client = new API($access_token);
$campaign_response = $api_client->fetch_campaign();
$patron = $api_client->fetch_user();
$patron = (array)$patron;
die(var_dump($patron));
}
I want to be able to view the user's data and pledge information. I've tried things such as $patron->data->first_name, $patron['data']['first_name'], etc. which have all thrown errors about the index of the array not being found.

You've probably already figured something out but I ran into the same thing and thought I'd share a solution here.
The JSONAPIResource object that the patreon library returns has a few specific methods that can return the individual pieces of data in a readable format.
import patreon
from pprint import pprint
access_token = <YOUR TOKEN HERE> # Replace with your creator access token
api_client = patreon.API(access_token)
campaign_response = api_client.fetch_campaign()
campaign = campaign_response.data()[0]
pprint(campaign.id()) # The campaign ID (or whatever object you are retrieving)
pprint(campaign.type()) # Campaign, in this case
pprint(campaign.attributes()) # This is most of the data you want
pprint(campaign.attribute('patron_count')) # get a specific attribute
pprint(campaign.relationships()) # related entities like 'creator' 'goals' and 'rewards'
pprint(campaign.relationship('goals'))
pprint(campaign.relationship_info())
# This last one one ends up returning another JSONAPIResource object with it's own method: .resource() that returns a list of more objects
# for example, to print the campaign's first goal you could use:
pprint( campaign.relationship_info('goals').resource()[0].attributes() )
Hope that helps someone!

Related

How to Return List of Project Tasks in ActiveCollab

Sorry this may be a trivial question but I am new to PHP. In the documentation to retrieve project tasks, the following code is provided to connect to an Active Collab cloud account:
<?php
require_once '/path/to/vendor/autoload.php';
// Provide name of your company, name of the app that you are developing, your email address and password.
$authenticator = new \ActiveCollab\SDK\Authenticator\Cloud('ACME Inc', 'My Awesome Application', 'you#acmeinc.com', 'hard to guess, easy to remember');
// Show all Active Collab 5 and up account that this user has access to.
print_r($authenticator->getAccounts());
// Show user details (first name, last name and avatar URL).
print_r($authenticator->getUser());
// Issue a token for account #123456789.
$token = $authenticator->issueToken(123456789);
// Did we get it?
if ($token instanceof \ActiveCollab\SDK\TokenInterface) {
print $token->getUrl() . "\n";
print $token->getToken() . "\n";
} else {
print "Invalid response\n";
die();
}
This works fine. I can then create a client to make API calls:
$client = new \ActiveCollab\SDK\Client($token);
and get the list of tasks for a given project as shown in the documentation.
$client->get('projects/65/tasks'); // PHP object
My question is, what methods/attributes are available to get the list of tasks? I can print the object using print_r() (print will obviously not work), and what I really want is in the raw_response header. This is private however and I cannot access it. How do I actually get the list of tasks (ex: the raw_response either has a string or json object)?
Thanks in advance.
There are several methods to work with body:
$response = $client->get('projects/65/tasks');
// Will output raw JSON, as string.
$response->getBody();
// Will output parsed JSON, as associative array.
print_r($response->getJson());
For full list of available response methods, please check ResponseInterface.
If you wish to loop through tasks, use something like this:
$response = $client->get('projects/65/tasks');
$parsed_json = $response->getJson();
if (!empty($parsed_json['tasks'])) {
foreach ($parsed_json['tasks'] as $task) {
print $task['name'] . "\n"
}
}

Get the first free column in a Google Sheet via PHP API

I'm using the Google Sheets API to write some data into the sheets, but so far either I clear it all and write everything again or I write in new rows (which Sheets API does by default).
I am now writing a single column per run, but I need to get the first available column in the sheet, so I can pass it as the range of writing.
This is my code so far:
$sheet = new \Google_Service_Sheets($this->client);
$range = "'" . $sheetName . "'!" . $rangeArg . (strlen($rangeArg) == 2 ? '' : count($data) + 1000);
$response = $sheet->spreadsheets_values->get($this->sheetId, $range);
if (!$clear && $response && $response->values) {
$c = count($response->values);
$newRange = (intval(substr($rangeArg, 1, 1)) + $c);
$newRange = substr($rangeArg, 0, 1) . $newRange . substr($rangeArg, 2);
$range = "'" . $sheetName . "'!" . $newRange . (count($data) + 1000);
}
$options = ['valueInputOption' => 'RAW'];
if ($clear) {
$sheet->spreadsheets_values->clear($this->sheetId, $range, new \Google_Service_Sheets_ClearValuesRequest);
}
$body = new \Google_Service_Sheets_ValueRange(['values' => $data, 'majorDimension' => $columns ? 'COLUMNS' : 'ROWS']);
$ok = $sheet->spreadsheets_values->append($this->sheetId, $range, $body, $options);
}
I saw someone on the internet mentioning getLastColumn() as a function, but it's not available in my version of sheets API apparently or it's just not in this package.
google/apiclient v2.5.0
google/apiclient-services v0.138
google/auth v1.9.0
getLastColumn is an appscript method. Something like that is not available with the php client library is only going to give you google sheets api methods,
The only way to find out whats on the sheet is to buffer it and scan though as you are already doing. Unfortunately with PHP there is really no easy way of doing it.
$response = $service->spreadsheets_values->batchGet($spreadsheetId);
I dont use PHP, but I am 100% sure, that in Google API its closest things on PHP and Python, just syntax of languages would be different
So for get the first free column through Google Sheet API (using Python):
import httplib2
from googleapiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
DOCUMENT_ID = '1ma8DG3IQJ377900iaFUPu9qXoThuP22buLgEILVfO1M'
def get_service_sacc():
creds_json = 'param-param-1344-fae81984f8a8.json'
scopes = ['https://www.googleapis.com/auth/spreadsheets']
creds_service = ServiceAccountCredentials.from_json_keyfile_name(creds_json, scopes).authorize(httplib2.Http())
return build('sheets', 'v4', http=creds_service)
sheet_values = get_service_sacc().spreadsheets().values()
_range = "A1:A9"
# or use _range = "Name of List!A1:A9", if u want to take info not from first list of sheets.
write = sheet_values.append(spreadsheetId=DOCUMENT_ID, range=_range, valueInputOption="USER_ENTERED",body={}).execute()
deal_id = str(write['updates']['updatedRange']).split('!')
little info about how get creds.json, if you wanna make thru this method (its from Service Account (https://cloud.google.com/iam/docs/service-accounts), create it, go to you Cloud Developer Console, create a some project, create service account, append it to project, and also after creation, click on three dots at actions (in account line), click Manage keys -> Add key -> Create new key -> json and end it, than download that json, and put it together in one directory of you project where u start you language logic.)
info about, how append works (https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/append)

How to invoke the demo url using VinceG php-first-data-api

I am trying to integrate First Data e4 Gateway using PHP. I downloaded the VinceG/php-first-data-api PHP First Data Service API class. The code comes with some examples.
I have my Terminal ID (API_LOGIN) and Password (32 character string).
What confuses me is that when I use one of the examples, I don't know how to tell the class that I want to use the demo url, not the production url.
The class comes with two constants:
const LIVE_API_URL = 'https://api.globalgatewaye4.firstdata.com/transaction/';
const TEST_API_URL = 'https://api.demo.globalgatewaye4.firstdata.com/transaction/';
In the First Data console, when I generated my password, it said to use the v12 api, /transaction/v12, so I changed the protected $apiVersion = 'v12';
All I want to do is write my first development transaction using First Data e4. I have yet to get any kind of response. Obviously I need a lot of hand holding to get started.
When I set up a website to use BalancedPayments, they have a support forum that's pretty good, and I was able to get that running fairly quickly. First Data has a lot of documentation, but for some reason not much of it has good PHP examples.
My hope is that some expert has already mastered the VinceG/php-first-data-api, and can help me write one script that works.
Here's the pre-auth code I'm using, that invokes the FirstData class:
// Pre Auth Transaction Type
define("API_LOGIN", "B123456-01");
define("API_KEY", "xxxxxxxxxxyyyyyyyyyyyyzzzzzzzzzz");
$data = array();
$data['type'] = "00";
$data['number'] = "4111111111111111";
$data['name'] = "Cyrus Vance";
$data['exp'] = "0618";
$data['amount'] = "100.00";
$data['zip'] = "33333";
$data['cvv'] = "123";
$data['address'] = "1111 OCEAN BLVD MIAMI FL";
$orderId = "0001";
require_once("FirstData.php");
$firstData = new FirstData(API_LOGIN, API_KEY, true);
// Charge
$firstData->setTransactionType(FirstData::TRAN_PREAUTH);
$firstData->setCreditCardType($data['type'])
->setCreditCardNumber($data['number'])
->setCreditCardName($data['name'])
->setCreditCardExpiration($data['exp'])
->setAmount($data['amount'])
->setReferenceNumber($orderId);
if($data['zip']) {
$firstData->setCreditCardZipCode($data['zip']);
}
if($data['cvv']) {
$firstData->setCreditCardVerification($data['cvv']);
}
if($data['address']) {
$firstData->setCreditCardAddress($data['address']);
}
$firstData->process();
// Check
if($firstData->isError()) {
echo "!!!";
// there was an error
} else {
echo "###";
// transaction passed
}
My number one problem was that I had not created (applied for, with instant approval) a
demo account on First Data. I didn't realize this was a separate thing on First Data. On Balanced Payments, for instance, you have one account, and you can run your script on a test url with test values.
From the Administration panel, click "Terminals", then your Gateway number on the ECOMM row (will look something like AH1234-03), then you have to click "Generate" on password save it to your personal notes), then click UPDATE.
Now replace your parameter values in your test scripts. I use a variable assignment block that looks something like this:
define("API_LOGIN", "AH1234-05"); //fake
define("API_KEY", "44p7797xxx790098z1z2n6f270ys1z0x"); //fake
$data = array();
$data['type'] = "03";
$data['number'] = "4111111111111111";
$data['name'] = "Cyrus Vancce";
$data['exp'] = "0618";
$data['amount'] = "100.00";
$data['zip'] = "33320";
$data['cvv'] = "123";
$data['address'] = "1234 N OCEAN BLVD MIAMI BEACH FL";
$orderId = "0001";
require_once("FirstData.php");
$firstData = new FirstData(API_LOGIN, API_KEY, true);
at the end of the VinceG test scripts, I output my gateway response with a print_r, like this:
$firstData->process();
// Check
if($firstData->isError()) {
echo "!!!";
// there was an error
} else {
echo "###";
// transaction passed
}
echo "<pre>";
print_r($firstData);

Twitter request token

I'm trying to work with the examples on the Twitter dev site but can't seem to get to the same signature as they have.
I am trying to complete step 3 on https://dev.twitter.com/docs/auth/implementing-sign-twitter because I am getting an error "Invalid or expired token" but I know it isn't because I've only just been given it, so it must be something wrong with my data packet.
The code I am using to try and generate this is:
// testing bit
$oauth = array(
'oauth_consumer_key'=>'cChZNFj6T5R0TigYB9yd1w',
'oauth_nonce'=>'a9900fe68e2573b27a37f10fbad6a755',
'oauth_signature_method'=>'HMAC-SHA1',
'oauth_timestamp'=>'1318467427',
'oauth_token'=>'NPcudxy0yU5T3tBzho7iCotZ3cnetKwcTIRlX0iwRl0',
'oauth_version'=>'1.0'
);
$this->o_secret = 'LswwdoUaIvS8ltyTt5jkRh4J50vUPVVHtR2YPi5kE';
$this->c_secret = 'kAcSOqF21Fu85e7zjz7ZN2U4ZRhfV3WpwPAoE3Z7kBw';
ksort($oauth);
$string = rawurlencode(http_build_query($oauth));
$new_string = strtoupper($http_method).'&'.rawurlencode($main_url[0]).'&'.$string;
// The request_token request doesn't need a o_secret because it doesn't have one!
$sign_key = strstr($fullurl,'request_token') ? $this->c_secret.'&' : $this->c_secret.'&'.$this->o_secret;
echo urlencode(base64_encode(hash_hmac('sha1',$new_string,$sign_key,true)));exit;
And I'm assuming that the keys listed on this page are in fact correct: https://dev.twitter.com/docs/auth/creating-signature. So in that case the signature should be 39cipBtIOHEEnybAR4sATQTpl2I%3D.
If you can spot what I'm missing that would be great.
Your consumer secret and token secret are incorrect for the page you reference. If you look further up the page you can see that they should be:
Consumer secret: L8qq9PZyRg6ieKGEKhZolGC0vJWLw8iEJ88DRdyOg
Token secret: veNRnAWe6inFuo8o2u8SLLZLjolYDmDP7SzL0YfYI
Also in Step 3 you need to include the oauth_verifier in the list of parameters when calculating your signature base string.
I'm not familiar with PHP so I haven't checked your code to calculate the signature.
This code has now worked - I will tidy it up from there :)
// This function is to help work out step 3 in the process and why it is failing
public function testSignature(){
// testing bit
$oauth = array(
'oauth_consumer_key'=>'cChZNFj6T5R0TigYB9yd1w',
'oauth_nonce'=>'a9900fe68e2573b27a37f10fbad6a755',
'oauth_signature_method'=>'HMAC-SHA1',
'oauth_timestamp'=>'1318467427',
'oauth_token'=>'NPcudxy0yU5T3tBzho7iCotZ3cnetKwcTIRlX0iwRl0',
'oauth_version'=>'1.0'
);
$this->o_secret = 'LswwdoUaIvS8ltyTt5jkRh4J50vUPVVHtR2YPi5kE';
$this->c_secret = 'kAcSOqF21Fu85e7zjz7ZN2U4ZRhfV3WpwPAoE3Z7kBw';
ksort($oauth);
$string = http_build_query($oauth);
$new_string = strtoupper($http_method).'&'.$main_url[0].'&'.$string;
$new_string = 'POST&https%3A%2F%2Fapi.twitter.com%2F1%2Fstatuses%2Fupdate.json&include_entities%3Dtrue%26oauth_consumer_key%3Dxvz1evFS4wEEPTGEFPHBog%26oauth_nonce%3DkYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1318622958%26oauth_token%3D370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb%26oauth_version%3D1.0%26status%3DHello%2520Ladies%2520%252B%2520Gentlemen%252C%2520a%2520signed%2520OAuth%2520request%2521';
// The request_token request doesn't need a o_secret because it doesn't have one!
$sign_key = $this->c_secret.'&'.$this->o_secret;
echo 'Should be: tnnArxj06cWHq44gCs1OSKk/jLY=<br>';
echo 'We get: '.base64_encode(hash_hmac('sha1',$new_string,$sign_key,true));
exit;
}
you want to access token from twitter and sign in implementation you can see in this example.
1) http://www.codexworld.com/login-with-twitter-using-php/
and this one for timeline tweets
2) http://www.codexworld.com/create-custom-twitter-widget-using-php/
may be this help you .

facebook graph api don´t publish to news feed

im trying to update my news feed on facebook. Im using the new graph api. I can connect to graph, but when i try to publish some content to the feed object, nothing happens.
here´s my code:
<?php
$token = "xxxx";
$fields = "message=test&access_token=$token";
$c = curl_init("http://graph.facebook.com/me/feed");
curl_setopt($c,"CURLOPT_POST", true);
curl_setopt($c,"CURLOPT_POSTFIELDS",$fields);
$r = curl_exec($c);
print_r($r);
this returns:
{"error":{"type":"QueryParseException","message":"An active access token must be used to query information about the current user."}}1
then I try to pass access_token via GET:
$c = curl_init("http://graph.facebook.com/me/feed?access_token=$token");
this returns:
{"data":[]}1
Am I doing something wrong?
thanks
I found my error!
I was putting CURL options as a string rather than constants.
oopps...

Categories