Ebay Api, getOrders. Can't get buyer email - php

Everybody.
Have a question about ebay trading api.
I'm trying to get all orders for authorized user.
I'm developing my web application using PHP.
So, I use this sdk:
https://github.com/davidtsadler/ebay-sdk-php
I'm getting list using getOrders method:
http://developer.ebay.com/devzone/xml/docs/Reference/ebay/GetOrders.html
Here is my code example:
public function getOrders(){
$service = $this->getTradingService();
$args = array(
//"OrderStatus" => "Completed",
"OrderStatus" => "All",
"SortingOrder" => "Ascending",
"OrderRole" => "Seller",
//"CreateTimeFrom" => new \DateTime('2015-01-01'),
"CreateTimeFrom" => new \DateTime('2000-01-01'),
"CreateTimeTo" => new \DateTime(),
);
$request = new Types\GetOrdersRequestType($args);
$request->RequesterCredentials = new Types\CustomSecurityHeaderType();
$request->RequesterCredentials->eBayAuthToken = $this->userToken;
$request->IncludeFinalValueFee = true;
$request->Pagination = new Types\PaginationType();
$request->Pagination->EntriesPerPage = 100;
$pageNum = 1;
$orders = [];
do {
$request->Pagination->PageNumber = $pageNum;
$response = $service->getOrders($request);
if (isset($response->Errors)) {
$message = '';
foreach ($response->Errors as $error) {
$message .= $error->ShortMessage;
}
throw new Exception($message);
}
if ($response->Ack !== 'Failure' && isset($response->OrderArray)) {
foreach ($response->OrderArray->Order as $order) {
$orders[] = $order->toArray();
}
}
$pageNum += 1;
}
while(isset($response->OrderArray) && $pageNum <= $response->PaginationResult->TotalNumberOfPages);
return $orders;
}
It works fine for me except one issue.
I can't get buyer email.
$orders[0]['ShippingAddress']['ExternalAddressID']
Is empty.
$orders[0]['TransactionArray']['Transaction'][0]['Buyer']['Email']
Is string value "Invalid Request"
If somebody knows way to get buyers emails.
Or just get informatioan about many users in one request(so I could simply merge them).
UPDATE:
Also tried to do the same without SDK.
public function getOrders2(){
$xml = '<?xml version="1.0" encoding="utf-8"?>
<GetOrdersRequest xmlns="urn:ebay:apis:eBLBaseComponents">
<CreateTimeFrom>2000-01-01T00:00:00</CreateTimeFrom>
<CreateTimeTo>2015-10-22T00:00:00</CreateTimeTo>
<IncludeFinalValueFee>true</IncludeFinalValueFee>
<OrderRole>Seller</OrderRole>
<OrderStatus>All</OrderStatus>
<DetailLevel>ReturnAll</DetailLevel>
<RequesterCredentials>
<eBayAuthToken>' . $this->userToken . '</eBayAuthToken>
</RequesterCredentials>
</GetOrdersRequest>';
$url = 'https://api.ebay.com/ws/api.dll';
$results = $this->sendPostRequest($xml,$url);
$results = new SimpleXMLElement($results);
return $results;
}
Get the same issue.
Thanks

Need change SiteID to id User Registration.
$config = [
'apiVersion' => Services\TradingService::API_VERSION,
'siteId' => Constants\SiteIds::US,
'credentials' => [
'appId' => getenv('EBAY_APP_ID'),
'certId' => getenv('EBAY_CERT_ID'),
'devId' => getenv('EBAY_DEV_ID')
],
'sandbox' => false
];

If the order is too old then it will will result in Invalid Request ( Simply saying " This orders is XX days old and we wont provide email address for it )

Ebay withholds their user's email information 14 days after the order is placed.
If you are using their APIs to pulling order info after that you get:
Email = 'Invalild Request'
Example response ...
...
'TransactionArray': {'Transaction': [...
'Buyer': {'Email': 'Invalid Request',
'UserFirstName': None,
'UserLastName': None},
...
The thing to do is
Pull the data before that, and then
Do not update the order email data on subsequent data pulls.
I found this out the hard way. I don't recall reading about that in the API docs.

Related

How to insert text with google docs api php

I'm trying to create a copy of a document using the Google Docs Api, and then edit it that copy by inserting text into it. So, I've looked at the documentation and seemingly implemented it exactly the way it says.
<?php
//That is, if this is just a regular login
//Personal Files
require("loginManager.php");
require("globals.php");
require("googleDrive.php");
//Moodle files
require("../config.php");
require("../my/lib.php");
require("../files/renderer.php");
require("../course/lib.php");
//Google Docs
$CREDENTIALS_PATH = "../../" . "vendor/autoload.php";
require ($CREDENTIALS_PATH);
//Example code
$copyTitle = 'Copy Title';
$documentId = "1vYyeGLbadFi0sl9g2LEJSZCB4YiGOpCb";
$copy = new Google_Service_Drive_DriveFile(array(
'name' => $copyTitle
));
//Initialize necessary client variables
$desiredPath = "../../credentials.json";
$authCode = (isset($_GET["code"]) ? $_GET["code"]:"");
GoogleDrive::setAuthCode($authCode);
$client = GoogleDrive::getClient($desiredPath, $FULLSCRIPT);
$docServices = new Google_Service_Docs($client);
$driveServices = new Google_Service_Drive($client);
$files = $driveServices->files;
$documents = $docServices->documents;
$driveResponse = $files->copy($documentId, $copy);
$documentCopyId = $driveResponse->id;
//Create desiredRequests
$desiredRequests = array(new Google_Service_Docs_Request(array(
'insertText' => array(
'text' => 'Hello world!',
'location' => array(
'index' => 25)))));
$batchUpdateRequests = new Google_Service_Docs_BatchUpdateDocumentRequest(array(
'requests' => $desiredRequests));
$docChangeResponse = $documents->batchUpdate($documentCopyId, $batchUpdateRequests);
echo $OUTPUT->header();
echo $OUTPUT->custom_block_region('content');
echo $OUTPUT->footer();
//Check if there's any get actions that need to be serviced
$getVariable = filter_input(INPUT_GET, "action");
if($getVariable == "openFileManager") {core_files_renderer::render_form_filemanager();}
else if($getVariable == "createCourse")
{
/*Important note: there are two types of ids when it comes to courses
*
* Programmer's Notes:
*
* -$instance is the instance of a record of from the enrol table
* -the enrol table stores instances of courses...so does mdl_course
* -idnumber and id, the latter is the actual primary key, the other is
* I guess is for school admins or course creators to be able to number
* the courses according to their own system. idnumber can be null.
*
*/
$enrollmentPlugin = enrol_get_plugin("manual");
if($enrollmentPlugin)
{
//Create data for course_request
$data = new stdClass();
$data->requester = $USER->id;
$data->id = 1;
$course_request_object = new course_request($data);
unset($data);
//create data for new course
$data = new stdClass();
$data->fullname = 'Math';
$data->shortname = 'Math 7';
$data->summary = 'Awesome!';
$data->summaryformat = FORMAT_PLAIN;
$data->format = 'topics';
$data->newsitems = 0;
$data->numsections = 5;
//$data->category = $course_request_object->get_category();
$data->category = 1;
$course = create_course($data);
//Instance is the record from the enrol table
$instanceid = $enrollmentPlugin->add_instance($course);
$instance = $DB->get_record('enrol', array('courseid'=>$course->id, 'enrol'=>'manual'), '*', MUST_EXIST);
$enrollmentPlugin->enrol_user($instance, $USER->id);
}
}
else if($getVariable == "appendDocument")
{
$courseID = filter_input(INPUT_GET, "courseID");
$fs = get_file_storage();
$data = array(
'contextid' => $courseID, // ID of context
'component' => 'course_myarea', // usually = table name
'filearea' => 'myarea', // usually = table name
'itemid' => 0, // usually = ID of row in table
'filepath' => '/', // any path beginning and ending in /
'filename' => 'myfile.txt'
);
$content = "hellp worldl";
$fs->create_file_from_string($data, $content);
}
else if($getvariable == null)
{
//if there are no get paramaters then it's a first time entry
//get all of user's courses, files, etc
$courses = enrol_get_all_users_courses($USER->id);
global $DB;
foreach($courses as $currentCourse)
{
$desiredID = $currentCourse->id;
$desiredFiles = $DB->get_record('files', array('contextid'=> $desiredID));
$contentHash = $desiredFiles->contenthash;
$dir1 = substr($contentHash, 0, 2); $dir2 = substr($contentHash, 2, 2);
$desiredPath = $CFG->dirrot."../../../../moodledata/filedir/"
.$dir1."/".$dir2."/".$contentHash;
$myFile = file_get_contents($desiredPath);
$type = mime_content_type($desiredPath);
$contentTypes = array("pdf" => "application/pdf",
"txt" => "text/plain");
//header("Content-Type: application/pdf");
//readfile($desiredPath, false, $foo);
$myFile = file_get_contents("goedel.pdf");
$foo = 3;
}
}
?>
Here's where GoogleDrive::getClient is defined in case it helps
class GoogleDrive
{
private static $AUTH_CODE;
public static function setAuthCode($desiredCode)
{
self::$AUTH_CODE = $desiredCode;
}
public static function getClient($credentialsPath, $callbackScript)
{
$client = new Google_Client();
$client->setApplicationName('MyApp');
$client->setScopes(Google_Service_Drive::DRIVE);
$client->setAuthConfig($credentialsPath);
$client->setAccessType('online');
$client->setPrompt('select_account consent');
$desiredVariable = self::$AUTH_CODE;
if($desiredVariable != null)
{
$accessToken = $client->fetchAccessTokenWithAuthCode($desiredVariable);
$client->setAccessToken($accessToken);
return $client;
}
// Load previously authorized token from a file, if it exists.
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
$tokenPath = 'token.json';
if (file_exists($tokenPath)) {
$accessToken = json_decode(file_get_contents($tokenPath), true);
$client->setAccessToken($accessToken);
}
// If there is no previous token or it's expired.
if ($client->isAccessTokenExpired()) {
// Refresh the token if possible, else fetch a new one.
if ($client->getRefreshToken()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
} else {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
$client->setRedirectUri($callbackScript);
redirect($authUrl);
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
$client->setAccessToken($accessToken);
// Check to see if there was an error.
if (array_key_exists('error', $accessToken)) {
throw new Exception(join(', ', $accessToken));
}
}
// Save the token to a file.
if (!file_exists(dirname($tokenPath))) {
mkdir(dirname($tokenPath), 0700, true);
}
file_put_contents($tokenPath, json_encode($client->getAccessToken()));
}
return $client;
}
}
However, when I run the previous code I get this error.
"{
"error": {
"code": 400,
"message": "This operation is not supported for this document",
"errors": [
{
"message": "This operation is not supported for this document",
"domain": "global",
"reason": "failedPrecondition"
}
],
"status": "FAILED_PRECONDITION"
}
}
"
Any help or direction will be greatly appreciated.
Edit 1: I've changed the script to reflect Tanaike's solution
I believe your situation and goal as follows.
You have already been able to use Google Docs API.
The script of a copy of a document worked.
You want to remove the error in your question.
For this, how about this modification?
From:
$desiredRequests = new Google_Service_Docs_Request(array(
'insertText' => array(
'text' => 'Hello world!',
'location' => array(
'index' => 25))));
In your script, when $batchUpdateRequests is retrieved, it becomes as follows.
{"requests":{"createNamedRangeType":{},"createNamedRangeDataType":{},"createParagraphBulletsType":{},"createParagraphBulletsDataType":{},"deleteContentRangeType":{},"deleteContentRangeDataType":{},"deleteNamedRangeType":{},"deleteNamedRangeDataType":{},"deleteParagraphBulletsType":{},"deleteParagraphBulletsDataType":{},"deletePositionedObjectType":{},"deletePositionedObjectDataType":{},"deleteTableColumnType":{},"deleteTableColumnDataType":{},"deleteTableRowType":{},"deleteTableRowDataType":{},"insertInlineImageType":{},"insertInlineImageDataType":{},"insertTableRowType":{},"insertTableRowDataType":{},"insertTextType":{},"insertTextDataType":{},"replaceAllTextType":{},"replaceAllTextDataType":{},"updateParagraphStyleType":{},"updateParagraphStyleDataType":{},"updateTextStyleType":{},"updateTextStyleDataType":{},"internal_gapi_mappings":{},"modelData":{},"processed":{},"insertText":{}}}
I think that this is the reason of your issue.
To:
$desiredRequests = array(new Google_Service_Docs_Request(array(
'insertText' => array(
'text' => 'Hello world!',
'location' => array(
'index' => 25)))));
In this modified script, when $batchUpdateRequests is retrieved, it becomes as follows.
{"requests":[{"insertText":{"text":"Hello world!","location":{"index":25,"segmentId":null}}}]}
In this request body, I could confirm that it worked.
Note:
If an error like Invalid requests[0].insertText: Index 25 must be less than the end index of the referenced segment occurs, please modify 'index' => 25 to 'index' => 1.
Reference:
Method: documents.batchUpdate

Ebay: Auth token is invalid. Validation of the authentication token in API request failed

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.

Paypal payouts always return 403 error

I have a web application that send payment to the user when they reach some level
That's the class that handle a single payment:
public function pagaSingoloAction(Request $request, $id_richiesta)
{
$richiesta_pagamento = $this->getDoctrine()->getRepository("AppBundle:RichiestaPagamento")->find($id_richiesta);
if ($richiesta_pagamento)
{
$logger = $this->get('logger');
$em = $this->getDoctrine()->getManager();
$tassa = $this->get('application.settings')->ritornaImpostazioneDaNome("percentuale_tasse_pagamenti_richieste");
if (!$tassa)
$tassa = 0;
$totale_richiesta_aggiornato = $richiesta_pagamento->getTotale();
$totale_tassa_decurtata_network = 0;
if ($tassa != 0)
{
$totale_tassa_decurtata_network = (($tassa / 100) * $totale_richiesta_aggiornato);
$totale_richiesta_aggiornato = $totale_richiesta_aggiornato - $totale_tassa_decurtata_network;
}
$imp = new ImpostazioniApplicazione($this->getDoctrine());
$apiContext = new ApiContext(new OAuthTokenCredential(
$imp->getPaypalAppId(),
$imp->getPaypalAppSecret()
));
$apiContext->setConfig(array(
'mode' => $this->getParameter('paypal_mode'),
'log.LogEnabled' => true,
'log.FileName' => 'PayPal.log',
'log.LogLevel' => 'FINE'
));
$logger->info("SETTATA CONFIGURAZIONE API CONTEXT");
$payouts = new Payout();
$sender_batch_header = new PayoutSenderBatchHeader();
$sender_batch_header->setSenderBatchId(uniqid())
->setEmailSubject("New payment from request!");
$sender_item = new PayoutItem();
$sender_item->setRecipientType('EMAIL')
->setNote("Payment request n. " . $richiesta_pagamento->getId())
->setReceiver($richiesta_pagamento->getEmailPaypal())
->setSenderItemId(uniqid())
->setAmount(new Currency('{
"value" : "'. $totale_richiesta_aggiornato .'",
"currency" : "EUR"
}'));
$payouts->setSenderBatchHeader($sender_batch_header)
->addItem($sender_item);
$output = "";
try{
$output = $payouts->createSynchronous($apiContext, null);
$logger->error(var_export($output, true));
}catch (Exception $ex){
$logger->error($ex->getMessage());
}
$payout_item = $output->getItems()[0];
if ($payout_item->getTransactionStatus() == "SUCCESS")
{
//ITS ALL OK
}
return $this->render('pagamento_singolo_richiesta/singolo_pagamento_dettagli.html.twig', array(
'pagamento' => $pagamento_singolo,
));
}
else{
return $this->render('pagamento_singolo_richiesta/pagamento_errore.html.twig');
}
}
When i try to make payment:
try{
$output = $payouts->createSynchronous($apiContext, null);
$logger->error(var_export($output, true));
}catch (Exception $ex){
$logger->error($ex->getMessage());
}
I always get 403 AUTORIZHATION but a month ago all works great!
So i can't understand what's the problem... I have checked with php sample code on paypal documentation and it's all ok like my code.
I use symfony framework in my application.
I get payment without any problem but i can't send money.
I have also tried to upgrade all Bundles and symfony itself but nothink has changed, same problem.
That's the paypal error log:
[25-10-2016 11:21:08] PayPal\Core\PayPalHttpConnection : INFO: Response Status : 403
[25-10-2016 11:21:08] PayPal\Core\PayPalHttpConnection : ERROR: Got Http response code 403 when accessing https://api.paypal.com/v1/payments/payouts?sync_mode=true. {"name":"AUTHORIZATION_ERROR","message":"Authorization error occurred","debug_id":"3676075eac96e","information_link":"https://developer.paypal.com/docs/api/payments.payouts-batch/#errors"}
The 403-response from PayPal API is always if there is something wrong with your credentials. Have you check if the desired PayPal-account is still active? And your client ID en secret ID are still legit?

PHP MusicBrainz get the first release date

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

graph api get post max limit 30 and nothing filter?

I would like to ask a facebook timeline with php sdk.
$this->FaceBookApp = new Facebook\Facebook(array(
"app_id" => $this->appId,
"app_secret" => $this->appSecret,
"default_graph_version" => $this->defaultGraphVersion
));
$this->FaceBookApp->setDefaultAccessToken($this->appId .'|'. $this->appSecret);
$Fields = "fields=type,message,source,picture,created_time,name,link,description,is_published";
$response = $this->FaceBookApp->get('/'.$this->userId.'/posts?limit=100&'.$Fields, $this->appId .'|'. $this->appSecret);
$list = $response->getDecodedBody();
$this->workingList = $list["data"];
count($this->workingList) = 36;
regardless of the value of the limit, but the Graph API Explorer returns 100 results.
and the filter does not work.
And:
$feedEdge = $response->getGraphEdge();
$nextFeed = $this->FaceBookApp->next($feedEdge);
$nextFeed = NULL !!
how can i get the last 100 post or how can i filter list?
thanx

Categories