i am trying to get the first release date of a song using Musicbrainz. To get this i am using the mikealmond musicBrainz library.
The problem i have is that when i try to execute exactly the same code as in this example (https://github.com/mikealmond/MusicBrainz/blob/master/examples/first-recording-search.php) i always get an authentication error.
Client error response [status code] 401 [reason phrase] Unauthorized [url] http://musicbrainz.org/ws/2/artist/0383dadf-2a4e-4d10-a46a-e9e041da8eb3?inc=releases+recordings+release-groups+user-ratings&fmt=json
Therefore i tried to add my username and password to the request:
$brainz = new MusicBrainz(new GuzzleHttpAdapter(new Client()),'myusername','mypassword');
$brainz->setUserAgent('myapplicationname', '0.2', 'http://localhost:443/');
If i call the url in the error message manually and enter my username and password i get the array i expect.
I just had a discovery: If I removed -"+ user - ratings"- it does not require authentication.
Therefore i commented the lines with "user - ratings" in my project
Now i think it works, but the performance of the query is very bad and often i get Error 503 // The MusicBrainz web server is currently busy. Please try again later. //
It takes a few seconds just for one song. Does someone know if this is normal or if i still have some kind of mistake?
My code....
//Create new MusicBrainz object
$brainz = new MusicBrainz(new GuzzleHttpAdapter(new Client()), 'username', 'password');
$brainz->setUserAgent('applicationname', '0.2', 'http://localhost:443/');
// set defaults
$artistId = null;
$songId = null;
$lastScore = null;
$firstRecording = array(
'releaseDate' => new DateTime()
);
// Set the search arguments to pass into the RecordingFilter
$args = array(
"recording" => 'we will rock you',
"artist" => 'Queen',
);
try {
// Find all the recordings that match the search and loop through them
$recordings = $brainz->search(new RecordingFilter($args));
$recorings i can print and in the loop i can print each $recording, but the error comes when i extract the informations
/** #var $recording \MusicBrainz\Recording */
foreach ($recordings as $recording) {
// if the recording has a lower score than the previous recording, stop the loop.
// This is because scores less than 100 usually don't match the search well
if (null != $lastScore && $recording->getScore() < $lastScore) {
break;
}
$lastScore = $recording->getScore();
$releaseDates = $recording->getReleaseDates();
$oldestReleaseKey = key($releaseDates);
if (strtoupper($recording->getArtist()->getName()) == strtoupper($args['artist'])
&& $releaseDates[$oldestReleaseKey] < $firstRecording['releaseDate']
) {
$firstRecording = array(
'releaseDate' => $recording->releases[$oldestReleaseKey]->getReleaseDate()
);
}
}
pr($firstRecording);
} catch (Exception $e) {
pr($e->getMessage());
}
$brainz = new MusicBrainz(new GuzzleHttpAdapter(new Client()), 'username', 'password');
You must set your MusicBrainz account credentials. Replace 'username' with your account username, and 'password' with the password used to login to MusicBrainz.org
Related
I am working customer relationship department and creating an app which is replying to every YouTube comment.
So what i am making right now is basically a script which pull comment data from YouTube Data API v3. This script is a looping script which is being called every 30 seconds, however you may know the YouTube API has a quota limit and I keep hitting it.
I am open for any solution:
Do I have to apply for more quota to YouTube
How much quota should i apply ( basically im only pulling comment data, from who, id , and timestamp ) or sis there any other way.
my code
<?php
if (!file_exists(__DIR__ . '/youtube_vendor/autoload.php')) {
throw new Exception(sprintf('Please run "composer require google/apiclient:~2.0" in "%s"', __DIR__));
}
require_once __DIR__ . '/youtube_vendor/autoload.php';
include "mysql.php";
$db = new db();
$client = new Google_Client();
$client->setAuthConfig('client_secret.json');
$client->addScope('https://www.googleapis.com/auth/youtube.readonly');
$client->addScope('https://www.googleapis.com/auth/youtube.force-ssl');
$client->setRedirectUri('your_url');
// offline access will give you both an access and refresh token so that
// your app can refresh the access token without user interaction.
$client->setAccessType('offline');
// Using "consent" ensures that your application always receives a refresh token.
// If you are not using offline access, you can omit this.
$client->setPrompt("consent");
$client->setIncludeGrantedScopes(true); // incremental auth
$auth_url = $client->createAuthUrl();
if(isset($_GET['code'])) {
// id index exists
$client->authenticate($_GET['code']);
$access_token = $client->getAccessToken();
// var_dump($access_token);
// echo "<br><br>";
// file_put_contents("received.txt",var_dump($access_token));
// $access_token = file_get_contents("received.txt");
// // $file = json_decode($fb);
// var_dump($access_token);
// serialize your input array (say $array)
$serializedData = serialize($access_token);
// save serialized data in a text file
file_put_contents('youtube_access_token.txt', $serializedData);
// at a later point, you can convert it back to array like:
$recoveredData = file_get_contents('youtube_access_token.txt');
// unserializing to get actual array
$access_token = unserialize($recoveredData);
// you can print your array like
print_r($access_token);
echo "<br>";
$client->setAccessToken($access_token);
$service = new Google_Service_YouTube($client);
// $channel = $youtube->channels->listChannels('snippet', array('mine' => $mine));
// var_dump($channel);
$queryParams = [
'maxResults' => 25,
'mine' => true
];
$arrayComment = array();
$arrayReplies = array();
$responseVideo = $service->activities->listActivities('snippet,contentDetails', $queryParams);
foreach($responseVideo['items'] as $video)
{
$db->insert_youtube_video($video['snippet']['channelId'],$video['snippet']['channelTitle'],$video['snippet']['publishedAt'],$video['snippet']['title'],$video['snippet']['description'],$video['snippet']['thumbnails']['standard']['url'],$video['contentDetails']['upload']['videoId']);
$queryParams = [
'videoId' => $video['contentDetails']['upload']['videoId']
];
$responseComment = $service->commentThreads->listCommentThreads('snippet,replies', $queryParams);
foreach($responseComment['items'] as $comment)
{
$db->insert_youtube_comment($comment['snippet']['topLevelComment']['snippet']['authorChannelUrl'],$comment['snippet']['topLevelComment']['snippet']['authorDisplayName'],$comment['snippet']['topLevelComment']['snippet']['authorProfileImageUrl'],$comment['snippet']['topLevelComment']['snippet']['publishedAt'],$comment['snippet']['topLevelComment']['snippet']['updatedAt'],$comment['snippet']['topLevelComment']['snippet']['textDisplay'],$comment['snippet']['topLevelComment']['snippet']['videoId'],$comment['snippet']['topLevelComment']['id']);
$queryParams = [
'parentId' => $comment['snippet']['topLevelComment']['id']
];
$responseReplies = $service->comments->listComments('snippet', $queryParams);
foreach ($responseReplies['items'] as $replies)
{
$db->insert_youtube_replies($replies['snippet']['authorChannelUrl'],$replies['snippet']['authorDisplayName'],$replies['snippet']['authorProfileImageUrl'],$replies['snippet']['publishedAt'],$replies['snippet']['updatedAt'],$replies['snippet']['textDisplay'],$replies['snippet']['videoId'],$comment['snippet']['topLevelComment']['id'],$replies['id']);
}
$arrayReplies[] = $responseReplies;
}
$arrayComment[] = $responseComment;
}
}
else
{
echo $auth_url;
}
?>
<textarea style="width:100%;height:300px"><?php print_r($responseVideo['items']); ?><?php print_r($arrayComment); ?><?php print_r($arrayReplies); ?></textarea>
<script>
setTimeout(function () { window.location.reload(); }, 15*1000);
document.write(new Date());
</script>
Do I have to apply for more quota to YouTube
if you want to avoid hitting the quota and continue to make the number of requests you are making now. Yes you need to apply for a quota extension.
I would apply as soon as possible it can take a long time to get an extension.
How much quota should i apply ( basically im only pulling comment data, from who, id , and timestamp ) or sis there any other way.
That is up to you. How many requests are you making every day. You will need to do some math then pad it to ensure for future in crease of your application.
I'm trying to use Ebay PHP SDK to connect to Ebay and fetch sellers selling item. For this I used following steps:
Step 1: Get authorize token and code for logged-in user. I used following code to implement.
use \DTS\eBaySDK\OAuth\Services as OauthService;
use \DTS\eBaySDK\OAuth\Types as OauthType;
use \DTS\eBaySDK\Constants;
use \DTS\eBaySDK\Trading\Services;
use \DTS\eBaySDK\Trading\Types;
use \DTS\eBaySDK\Trading\Enums;
$service = new OauthService\OAuthService([
'credentials' => $config['sandbox']['credentials'],
'ruName' => $config['sandbox']['ruName'],
'sandbox' => true
]);
$oauthParam = [
'client_id' => $config['sandbox']['credentials']['appId'],
'redirect_uri' => $config['sandbox']['redirect_uri'],
'response_type' => 'code',
'scope' => 'https://api.ebay.com/oauth/api_scope'
];
$urlParam = '';
$query = [];
foreach($oauthParam as $key => $param) {
$query[] = "$key=$param";
}
$urlParam = '?' . implode('&', $query);
$url = 'https://signin.sandbox.ebay.com/authorize' . $urlParam;
#session_start();
if(isset($_SESSION['ebay_oauth_token'])) {
$token = $_SESSION['ebay_oauth_token']['code'];
}
else {
if(isset($_GET['code'])) {
$token = $_GET['code'];
$_SESSION['ebay_oauth_token']['code'] = $token;
$request = new OauthType\GetUserTokenRestRequest();
$request->code = $token;
$response = $service->getUserToken($request);
if ($response->getStatusCode() !== 200) {
//Error
} else {
$_SESSION['ebay_oauth_token']['access_token'] = $response->access_token;
}
} else {
#header('location: ' . $url);
}
}
$userOauthToken = $_SESSION['ebay_oauth_token']['access_token'];
The above code is working as expected. That is the user is redirected to Sign In Page to authorize himself and get the set of Code and Access Token.
Step 2: Fetch Selling Items using code obtained from Step #1. I've used following code to implement the functionality.
$request->RequesterCredentials = new Types\CustomSecurityHeaderType();
$request->RequesterCredentials->eBayAuthToken = $token; //Obtained from Step 1
$request->ActiveList = new Types\ItemListCustomizationType();
$request->ActiveList->Include = true;
$request->ActiveList->Pagination = new Types\PaginationType();
$request->ActiveList->Pagination->EntriesPerPage = 10;
$request->ActiveList->Sort = Enums\ItemSortTypeCodeType::C_CURRENT_PRICE_DESCENDING;
$pageNum = 1;
do {
$request->ActiveList->Pagination->PageNumber = $pageNum;
$response = $service->getMyeBaySelling($request);
if (isset($response->Errors)) {
//Error Output
}
if ($response->Ack !== 'Failure' && isset($response->ActiveList)) {
foreach ($response->ActiveList->ItemArray->Item as $item) {
//Output response
}
}
$pageNum += 1;
} while ({condition});
I'm having problem in Step #2. It is generating Invalid Token while running the code.
I would highly appreciate if anyone help me.
You are mixing the requests. In the second part of your code, the request belongs to the Trading API that uses the Auth'n'Auth token, and you are trying to make the call using the OAuth token. These 2 tokens are different and work for different APIs.
You have 2 options.
Either keep the second part of your code, which appears to be correct, actually, but use the Auth'n'Auth token (that you can generate from the developer account). In this case, the first part is useless.
Keep the first part of your code, and delete the second part. In this case, you need to rewrite your second part of code using the OAuth API instead of the Trading API.
I have a html form where name and email address are getting collected. I try to submit these informations to a GetResponse list using this script:
<?php
function mytheme_save_to_getresponse($form)
{
require_once 'jsonRPCClient.php';
$api_key = 'myAPIkey';
$api_url = 'http://api2.getresponse.com';
$client = new jsonRPCClient($api_url);
$result = NULL;
try {
$result = $client->get_campaigns(
$api_key,
array (
# find by name literally
'name' => array ( 'EQUALS' => 'testlist' )
)
);
}
catch (Exception $e) {
# check for communication and response errors
# implement handling if needed
die($e->getMessage());
}
$campaigns = array_keys($result);
$CAMPAIGN_ID = array_pop($campaigns);
$subscriberEmail = $_GET['email'];
try {
$result = $client->add_contact(
$api_key,
array (
'campaign' => $CAMPAIGN_ID,
'name' => $subscriberName,
'email' => $subscriberEmail,
'cycle_day' => '0'
)
);
}
catch (Exception $e) {
# check for communication and response errors
# implement handling if needed
die($e->getMessage());
}
}
?>
The script doesn't show any errors but GetResponse is not saving the lead to my list. Am I doing something wrong?
Thanks
James
If u are getting a response as [queued]=>1 then your script is working fine..
It will be added to your contact only after a validation/confirmation of entered email
$subscriberEmail will recieve a confirmation email...after the user click on the link contact will get added
This line is wrong:
'name' => $subscriberName,
because you have undefined variable and post it to then GetResponse API 'name' params without value so GetResponse API return Invalid params.
Change to:
$subscriberName => "Some_test_name", // for test only
In this line:
$subscriberEmail = $_GET['email'];
you should set some email in GET table maybe for test just change to:
$subscriberEmail = "test#domain.com"; // or sth like this.
Last idea is var_dump $result variable then you see response from GetResponse API
$result = null; // before try {
var_dump($result); // before end of function } ?>
Your code is looks good and You have to set the call back url for error handling
I am updating twitter status using my application and facing a problem.
stdClass Object ( [request] => /1/statuses/update.json [error] => Could not authenticate you. )
But i have authenticate just 2 minutes ago and again its showing same error using code given bellow.
if(strlen($status)>=140)
{
$status = substr($status,0,139);
}
if($E_oauth_token != "" && $E_oauth_token_secret != "")
{
try
{
$twitteroauth = new TwitterOAuth(YOUR_CONSUMER_KEY, YOUR_CONSUMER_SECRET, $E_oauth_token, $E_oauth_token_secret);
$access_token = $twitteroauth->getAccessToken($tweet_verifier);
$params = array('status' => $status);
print_r($twitteroauth->post('statuses/update', $params));
}
catch(exception $e)
{
echo $e;
}
I have found solution for this and explain on this site you can easily check.
There is two types of oauth tokens one is temporary and with that temporary we have to get permanent token explained here Twitter OAuth in PHP.
I've been researching this and trying many variations based off my understanding of how to update a record in an SObject, but I keep getting the following error:
SoapFault exception: [sf:INVALID_TYPE] INVALID_TYPE: Must send a concrete entity type. in /home/public_html/soapclient/SforceBaseClient.php:509
I am able to login successfully to the page, but when I execute the code below, I am getting the error listed above.
$fieldsToUpdate = array (
"Name"=>$_POST['Name']
);
$sObject = new SObject();
$sObject->Id = $_POST['prospectID']; // this is the Id of the record
$sObject->fields = $fieldsToUpdate;
$sObject->type = 'Prospect__c'; // this is the API name of custom object
try {
$response = $mySforceConnection->update($sObject);
} catch (Exception $e) {
echo $e;
}
I am using PHP Toolkit 13.0 from the Force.com developer docs, but not able to get to the bottom of this error. Also, I am using the Enterprise WSDL in sandbox mode, and have the proper wsdl xml assigned.
Thanks.
sObject is the base type for all other Salesforce objects that can be updated. When using the enterprise API (SOAP), you'll need to pass instances that derive from sObject. (Lead, Contact, and Account are examples)
Here is the documentation for the update() method as well.
You need to supply an object type as the second update() argument. Also, the first argument of the update() method must be an array of objects you'd like to update:
$response = $mySforceConnection->update(array($object), 'Prospect__c');
Also, you do not need to use any object classes provided by the toolkit, a simple StdClass should work:
$prospect = new StdClass();
$prospect->Id = '006....';
$prospect->Name 'Foobar';
$response = $mySforceConnection->update(array($prospect), 'Prospect__c');
FYI, I have never found a way to update multiple object types at once, but you can update a batch of the same type of objects, hence why the first parameter needs to be an array. The Salesforce toolkit doesn't automatically account for someone passing a single object (i.e. it doesn't wrap it in an array for you). I have always used an abstraction layer between my application logic and Salesforce's SOAP toolkit, which provides conveniences like I just described.
if your are using Partner wsdl
<?php
// SOAP_CLIENT_BASEDIR - folder that contains the PHP Toolkit and your WSDL
// $USERNAME - variable that contains your Salesforce.com username (must be in the form of an email)
// $PASSWORD - variable that contains your Salesforce.com password
define("SOAP_CLIENT_BASEDIR", "../../soapclient");
require_once (SOAP_CLIENT_BASEDIR.'/SforcePartnerClient.php');
require_once ('../userAuth.php');
try {
$mySforceConnection = new SforcePartnerClient();
$mySoapClient = $mySforceConnection->createConnection(SOAP_CLIENT_BASEDIR.'/partner.wsdl.xml');
$mylogin = $mySforceConnection->login($USERNAME, $PASSWORD);
/*--------------------------------------------------------\
| Please manage the values for OBJECT ID from file
| userAuth.php
\--------------------------------------------------------*/
$fieldsToUpdate = array (
'FirstName' => 'testupdate',
'City' => 'testupdateCity',
'Country' => 'US'
);
$sObject1 = new SObject();
$sObject1->fields = $fieldsToUpdate;
$sObject1->type = 'Lead';
$sObject1->Id = $UPDATEOBJECTID1;
$fieldsToUpdate = array (
'FirstName' => 'testupdate',
'City' => 'testupdate',
'State' => 'testupdate',
'Country' => 'US'
);
$sObject2 = new SObject();
$sObject2->fields = $fieldsToUpdate;
$sObject2->type = 'Lead';
$sObject2->Id = $UPDATEOBJECTID2;
$sObject2->fieldsToNull = array('Fax', 'Email');
$response = $mySforceConnection->update(array ($sObject1, $sObject2));
print_r($response);
} catch (Exception $e) {
print_r($mySforceConnection->getLastRequest());
echo $e->faultstring;
}
?>
else for enterprises wsdl use
<?php
// SOAP_CLIENT_BASEDIR - folder that contains the PHP Toolkit and your WSDL
// $USERNAME - variable that contains your Salesforce.com username (must be in the form of an email)
// $PASSWORD - variable that contains your Salesforce.com password
define("SOAP_CLIENT_BASEDIR", "../../soapclient");
require_once (SOAP_CLIENT_BASEDIR.'/SforceEnterpriseClient.php');
require_once ('../userAuth.php');
try {
$mySforceConnection = new SforceEnterpriseClient();
$mySoapClient = $mySforceConnection->createConnection(SOAP_CLIENT_BASEDIR.'/enterprise.wsdl.xml');
$mylogin = $mySforceConnection->login($USERNAME, $PASSWORD);
/*--------------------------------------------------------\
| Please manage the values for OBJECT ID from file
| userAuth.php
\--------------------------------------------------------*/
$sObject1 = new stdclass();
$sObject1->Id = $UPDATEOBJECTID1;
$sObject1->FirstName = 'testupdate';
$sObject1->City = 'testupdateCity';
$sObject1->Country = 'US';
$sObject2 = new stdclass();
$sObject2->Id = $UPDATEOBJECTID2;
$sObject2->FirstName = 'testupdate';
$sObject2->City = 'testupdate';
$sObject2->State = 'testupdate';
$sObject2->Country = 'US';
$sObject2->fieldsToNull = array('Fax', 'Email');
$response = $mySforceConnection->update(array ($sObject1, $sObject2), 'Lead');
print_r($response);
} catch (Exception $e) {
print_r($mySforceConnection->getLastRequest());
echo $e->faultstring;
}
?>