I have a return object coming from instagram.
I am trying to skate the entire build DB table structure process, I understand Mongo is the ideal DB to use for this task.
I am using the regular instagram libraries https://github.com/cosenary/Instagram-PHP-API
and my test code runs without error.
I don have the PhP PECL mongo libraries installed, I should be good to go.
session_start();
require 'vendor/autoload.php';
use MetzWeb\Instagram\Instagram;
$instagram = new Instagram(array(
'apiKey' => 'xxx',
'apiSecret' => 'xxx',
'apiCallback' => 'http://103.238.173.97/success.php'
));
$accessToken = $instagram->getAccessToken();
$_SESSION['InstagramAccessToken'] = $accessToken;
$instagram->setAccessToken($_SESSION['InstagramAccessToken']);
$popular = $instagram->getPopularMedia();
// After getting the response, let's iterate the payload
var_dump($popular);
added just now:
$conn = new MongoClient('mongodb://localhost/?w=1');
$db = $conn->instagram;
// access collection
$collection = $db->instagram1;
$collection->insert($popular);
How would I construct a PDO query to 'autobuild' the table structure just like the JSON object at reply from my request?
instagram JSON object
Repaste of object. Most got cut off due to size
Update:
I tried to insert straight into a collection, I get no error but the DB is still the same size
show dbs
Data 0.078GB
admin (empty)
instagram 0.078GB
local 0.078GB
test 0.078GB
week1 (empty)
Related
I have a store in Dutchie.com. I want to access it's products using API key.
This has to do via Dutchie API using GraphQL integrated with PHP.
This is the Sample API Key:
public-eyJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJBUEktQ0xJRU5UIiwiZXhwIjozMzE4NjM5Mjc0NSwiaWF0IjoxNjI5NDgzOTQ1LCJpc3MiOiJodHRwczovL2R1dGNoY29tIiwianRpIjoiNGMtOTMyOC00MjhkLWEyYTMtOWQzMTc2ZTUwODY0IiwiZW50ZXJwcmlzZV9pZChLWExYTctNDM3OC05NWY4LTNlYzVzBiNSIsInV1aWQiOiI0M2ZlMjdkNy1iZWU2LTQxOTgtYWNhMi03N2Y5Y2I3MjI5MGIifQ.hCQWpcQ5uhKnZOSVQDA5SCMkx5kopC7H3upeU-1jMpg
This is the GraphQL Ping mutation.
mutation Ping {
ping {
id,
time
}
}
Dutchie End Point: https://plus.dutchie.com/plus/2021-07/graphql
http header parameter
{
"Authorization":"Bearer API KEY HERE"
}
Ping output
Basically I want to run GraphQL query in my PHP page. I'll add into my WordPress page later.
I have tried php-graphql-client php library.
Can someone help me to do this using above library or another one really appreciate. I wasted too much time for this as I have only few knowledge of GraphQL.
This is the code what I have tried.
$client = new Client(
'https://plus.dutchie.com/plus/2021-07/graphql',
['Authorization => Bearer API Key here']
);
// Create the GraphQL mutation
$gql = (new Mutation('Ping'))
->setSelectionSet(
[
'id',
'time',
]
);
// Run query to get results
try {
$results = $client->runQuery($gql);
}
catch (QueryError $exception) {
// Catch query error and desplay error details
print_r($exception->getErrorDetails());
exit;
}
// Display original response from endpoint
var_dump($results->getResponseObject());
// Display part of the returned results of the object
var_dump($results->getData()->pokemon);
// Reformat the results to an array and get the results of part of the array
$results->reformatResults(true);
print_r($results->getData()['data']);
Error what I got.
https://github.com/guzzle/psr7/blob/master/src/MessageTrait.php
Instead of:
$client = new Client(
'https://plus.dutchie.com/plus/2021-07/graphql',
['Authorization => Bearer API Key here']
);
Try
$client = new Client(
'https://plus.dutchie.com/plus/2021-07/graphql',
['Authorization' => 'Bearer API Key here']
);
I'm trying out the ActiveCollab API for my first time. I had to use StackOveflow to figure out how to get the API token since the docs don't tell me this.
Below is my code:
/* GET INTENT */
$url = 'https://my.activecollab.com/api/v1/external/login';
$fields = array(
'email' => "email#email.com",
'password' => "****"
);
$intent = curl_post_connector($url, $fields);
$intent = $intent->user->intent;
/* GET TOKEN */
$url = 'https://app.activecollab.com/my_app_id/api/v1/issue-token-intent';
$fields = array(
'intent' => $intent,
'client_name' => 'My App Name',
'client_vendor' => 'My Company Name'
);
$token = curl_post_connector($url, $fields);
$token = $token->token;
Everything above works and get's the token properly. What I find really weird is that I have to use API v1 to get this, and the docs on ActiveCollab's site don't mention any URL for API v5. It seems like this is the approach everything is taking here on StackOverflow.
Now with the token, I try to get my list of projects:
/* GET PROJECT */
$url = 'https://app.activecollab.com/my_app_id/api/v1/users';
$headers = array (
"X-Angie-AuthApiToken" => $token
);
$projects = curl_get_connector($url, $headers);
var_dump($projects);
But this does not work. There is no error returned - it instead returns an array of languages for some reason! I don't want to paste the massive json object here, so instead I'll link you to a photo of it: https://www.screencast.com/t/7p5JuFB4Gu
UPDATE:
When attempting to use the SDK, it works up until I try getting the token (which is just as far as I got without the SDK). I'm getting Server Error 500, and when looking at the logs, it says:
/home/working/public_html/ac/index.php(21): ActiveCollab\SDK\Authenticator\Cloud->issueToken(123456789)
#1 {main}
thrown in /home/working/public_html/ac/SDK/Authenticator/Cloud.php on line 115
This is line 115 of Cloud.php:
throw new InvalidArgumentException("Account #{$account_id} not loaded");
I honestly don't think I did anything wrong... there must be something wrong with my account ID.
Just for kicks, I commented out that line, and the error disappears and the page loads fine - except now I have no token...
I am trying to post some form data to Google Datastore, using this documentation here and here. I am struggling with knowing how to post the form data to the datastore, but I thought I had cracked it when I got the following error.
Parse error: syntax error, unexpected 'use' (T_USE) in record-usage.php on line 23
So my question is in two parts:
how do I post data to the Datastore from my form? (the examples in the documentation seem to offer two different ways of posting to the store)
how do I fix this syntax error?
Here is my code (it's actually line 7 in the sample below):
if(isset($_POST['submit'])) {
# Includes the autoloader for libraries installed with composer
require __DIR__ . '/vendor/autoload.php';
# Imports the Google Cloud client library
use Google\Cloud\Datastore\DatastoreClient;
# Your Google Cloud Platform project ID
$projectId = 'room-usage';
# Instantiates a client
$datastore = new DatastoreClient([
'projectId' => $projectId
]);
# The kind for the new entity
$kind = 'RoomUsage';
# The name/ID for the new entity
$name = $roomname + $_POST('timestamp');
# The Cloud Datastore key for the new entity
$taskKey = $datastore->key($kind, $name);
if($_POST('countinput') == '') {
$formdata->Headcount = $_POST('countslider');
} else {
$formdata->Headcount = $_POST('countinput');
}
$formdata->Timestamp = $_POST('timestamp');
$formdata->EnteredBy = $_POST('userid');
$formdata->RoomID = $_POST('roomid');
$formdata->Activity = $_POST('activity');
$formdata->Estimate = $_POST('estimate');
$formdata->NotAudited = $_POST('notaudited');
$formdata->Reason = $_POST('reason');
function save_room_usage(DatastoreClient $datastore, $formdata) {
$RoomUsage = $datastore->RoomUsage();
$transaction->updateBatch([$formdata]);
$transaction->commit();
}
# Prepares the new entity
$task = $datastore->entity($taskKey,
['Timestamp' => $_POST('timestamp'),
'Headcount' => $formdata->Headcount,
'EnteredBy' => $_POST('userid'),
'RoomID' => $_POST('roomid'),
'Activity' => $_POST('activity'),
'Estimate' => $_POST('estimate'),
'NotAudited' => $_POST('notaudited'),
'Reason' => $_POST('reason')]);
# Saves the entity
$datastore->upsert($task);
$status = 'Saved ' . $task->key() . ': ' . $task['description'];
}
Use
You can't have use inside a function. Think of it like an import.
Instead, move it outside of the method but inside your namespace. Simplest way to get going is just move it to the top of your file.
Writing data
Looking at this code:
$transaction->updateBatch([$formdata]);
$transaction->commit();
I think you've misinterpreted the transaction documentation. In the code example it presents, it first reads entities from Datastore via a Batch Lookup, then writes them back as a batch with:
$transaction->updateBatch([$fromAccount, $toAccount]);
In that example $fromAccount and $toAccount are proper entities with keys.
In your example, you are trying to batch write just a bunch of random data. Since you are only writing one record, you should delete that code.
The second part of your code where you create an entity and then upsert it should work. If you did end up needing to write more than one entity in a transaction, it is $task that you would use in the updateBatch method rather than the raw data.
I have a bitcoin address created using blockcypher and I would like to transfer some bitcoins from it (already made a deposit) to another address.
I am using the blockcypher php client to create the transaction using the sample code https://www.blockcypher.com/dev/bitcoin/?php#creating-transactions and https://github.com/blockcypher/php-client/blob/master/sample/transaction-api/CreateTransaction.php, I get the error
Class 'Mdanter\Ecc\Math\Gmp' not found in C:\xampp\htdocs\cck\vendor\bitwasp\bitcoin\src\Math\Math.php on line 8
I checked file the vendor and there is Gmp file or class in Mdanter\Ecc\Math\Gmp, so i edited the math.php file and edited line 6 to use \Mdanter\Ecc\Math\GmpMath as Gmp; and now get the error like the one in https://github.com/blockcypher/php-client/issues/21
My code is as below
require_once __DIR__.'/vendor/autoload.php';
use BlockCypher\Auth\SimpleTokenCredential;
use BlockCypher\Rest\ApiContext;
use BlockCypher\Api\TX as DD;
use BlockCypher\Client\TXClient;
// ... other classes
$apiContext = ApiContext::create(
'main', 'btc', 'v1',
new SimpleTokenCredential('4e3a287e603f48c994d978dab061084a'),
array('log.LogEnabled' => true, 'log.FileName' => 'BlockCypher.log', 'log.LogLevel' => 'DEBUG') );
$tx = new DD();
// Tx inputs
$input = new \BlockCypher\Api\TXInput();
$input->addAddress("1DZR2kUCa5HTyVZLY8TWFf2ZfjhWgsgNtf");
$tx->addInput($input);
// Tx outputs
$output = new \BlockCypher\Api\TXOutput();
$output->addAddress("1Mye4sZmd9rzjY6yUw19etZhzeVU2q1kcj");
$output->setValue(1000); // Satoshis
$tx->addOutput($output);
// Tx amount
$txClient = new TXClient($apiContext);
$txSkeleton = $txClient->create($tx);
$privateKeys = array("3ed07ff3e458fabb8b99b723002f4817eebd5fc11f9c76fdd9c200090c04fd1c");
$txSkeleton = $txClient->sign($txSkeleton, $privateKeys);
$txSkeleton = $txClient->send($txSkeleton);
The problem was caused by a bad dependency configuration in one of the php-client dependencies. It was fixed. More info:
https://github.com/blockcypher/php-client/issues/21
You only need to update php-client to the latest release.
I am using cakePHP 2.x . Currently doing about the twitter OAuth, http://code.42dh.com/oauth/.
function twitter_authentication()
{
//assume above coding is all correct.
$this->Session->write('twitter_request_token', ($requestToken));
$this->redirect('http://api.twitter.com/oauth/authenticate?force_login=true&oauth_token='.$requestToken->key); //I able to get $requestToken.
}
function twitter_login()
{
$requestToken = $this->Session->read('twitter_request_token');
$accessToken = $this->OAuthConsumer->getAccessToken('Twitter','https://api.twitter.com/oauth/access_token', $requestToken);
At function_login(), I failed to read session and ended up with PhP Incomplete Class. If I do $this->Session->write('twitter_request_token', serialize($requestToken)); and $requestToken = $this->Session->read(unserialize('twitter_request_token'); it will work, but I will ended up error at other places which caused by using serialize and unserialize session.
"PHP Incomplete Class" means PHP doesn't have a class definition for the object you're loading.
Option A: figure out what class that object is when you write it into the session and ensure that class's definition is loaded before loading the object.
Option B: convert the object to an stdClass or array before writing it, and convert back after loading. This might be more complex than the first option.
OAuth.php's OauthToken class is quite simple with just two properties: key and secret. When you get the login url, you can store it to the session as an array:
CakeSession::write('Twitter.requestToken', array(
'key' => $requestToken->key,
'secret' => $requestToken->secret
));
Then, instantiate your own OAuthToken when calling OAuthClient->getAccessToken() like so:
$sessionRequestToken = CakeSession::read('Twitter.requestToken');
$accessToken = $twitterClient->getAccessToken('https://api.twitter.com/oauth/access_token',
new OAuthToken($sessionRequestToken['key'], $sessionRequestToken['secret']));
Should be ready to go:
if ($accessToken) {
$twitterClient->post($accessToken->key, $accessToken->secret,
'https://api.twitter.com/1/statuses/update.json', array('status' => 'My balls smells like A-1 sauce. #science'));
}