Create function using external php library | shipping - php

I use Inpost ShipX PHP SDK php library one courier company to post/create shipping using API.
With this code I can get shipping label and save, this working correct:
$shipmentData = json_decode($response->getBody()->__toString(), true);
while ($shipmentData['status'] !== 'confirmed') {
sleep(1);
$response = $api->shipments()->get($shipmentData['id']);
$shipmentData = json_decode($response->getBody()->__toString(), true);
}
$labelResponse = $api->shipments()->label()->get($shipmentData['id'], [
'format' => 'Pdf',
'type' => 'A6',
]);
file_put_contents('var/labels/paczkomaty_label.pdf', $labelResponse->getBody()->__toString());
Now I try also get tracking number for created shipping.
I try add to above code:
$trackingResponse = $api->shipments()->tracking()->get($shipmentData['id']);
var_dump($trackingResponse);
But after post I get:
An uncaught Exception was encountered
Type: InvalidArgumentException
Message: tracking resource not found
Filename: /vendor/imper86/php-inpost-api/src/Resource/AbstractResource.php
Line Number: 66
Can anyone check this library and help me build the function correctly or give me a hint how i can check the resource to build the right function?

Code for __call inside /vendor/imper86/php-inpost-api/src/Resource/AbstractResource.php#66:
$className = $this->reflection->getName() . '\\' . ucfirst($name);
In your case it would be Shipments\\Tracking, but there is no such class.
Try doing
$api->tracking()->shippingHistory()->get($shipmentData['id']);
Basically what you see inside src/Resouce dir you can call as method.
I have just performed static analysis of code/structure, may be wrong

Related

File Move Google Drive API v3 PHP

Using Google API v3 I try to move a file from one folder to another. I am using a wrapper class in Laravel, the file and parent IDs are correct. Developing from the documentation, I have tried code as:
public function moveFileFromTo($fileID, $toParentID) {
$fromFile = $this->service->files->get($fileID, ['fields' => '*']);
$fromParentID = $fromFile->getParents();
$blankFile = new Google_Service_Drive_DriveFile();
$this->service->files->update($fileID, $blankFile, [
"removeParents" => $fromParentID,
"addParents" => $toParentID
]);
}
However, this seems to move the file but strips out all the meta data.
I have also tried
public function moveFileFromTo($fileID, $toParentID) {
$fromFile = $this->service->files->get($fileID, ['fields' => '*']);
$fromParentID = $fromFile->getParents();
$fromFile->setParents($fromParentID);
$this->service->files->update($fileID, $fromFile);
}
However, this gives the error:
Google\Service\Exception
{ "error": { "errors": [ { "domain": "global", "reason":
"fieldNotWritable", "message": "The resource body includes fields
which are not directly writable." } ], "code": 403, "message": "The
resource body includes fields which are not directly writable." } }
I wish to simply move the file and retain all its metadata. From the documentation, it seems either a new empty file is required in update (really weird) or I must somehow strip out the fields of the object used in the second argument ($fromFile) it does not like to be written to (even though I am simply updating the files parents - which is writable).
See also https://issuetracker.google.com/issues/199921300
Problems with Answers so far:
but grateful for responses
$fromFile = $this->service->files->get($fileID, ['fields' => 'parents, id']);
returns all ~75 attributes a lot of which are not writeable.
Instead of the expected 2 as per PHPStorm debug (note the break is at the statement immediately following the GET request so irrelevant at this point
using
unset($fromFile->shared);
still leaves other writable attributes
and indeed the file is not actually shared
UPDATE TO MY CODING
public function moveFileFromTo($fileID, $toParentID) {
$fromFile = $this->service->files->get($fileID, ["fields" => "id,parents"]);
$fromFile = $this->getParsedWritableFile($fromFile);
$fromFile->setParents($toParentID);
$this->service->files->update($fileID, $fromFile, ['addParents' => $toParentID]);
}
getParsedWritableFile is trying to just set writable attributes on a new Google Drive file object:
public function getParsedWritableFile($gdrivefile) {
$gdrivefile = new \Google_Service_Drive_DriveFile();//comment or delete, just here to check auto complete function names
$parsedFile = new \Google_Service_Drive_DriveFile();
//$parsedFile=$gdrivefile;
// currently only allow these according to https://developers.google.com/drive/api/v3/reference/files#resource-representations
$parsedFile->setName($gdrivefile->getName());//name
$parsedFile->setMimeType($gdrivefile->getMimeType());//mimeType
$parsedFile->setDescription($gdrivefile->getDescription());//description
$parsedFile->setStarred($gdrivefile->getStarred());//starred
$parsedFile->setTrashed($gdrivefile->getTrashed());//trashed
$parsedFile->setParents($gdrivefile->getParents());//parents
$parsedFile->setProperties($gdrivefile->getProperties());//properties [object]
$parsedFile->setAppProperties($gdrivefile->getAppProperties());//appProperties [object]
$parsedFile->setCreatedTime($gdrivefile->getCreatedTime());//createdTime
$parsedFile->setModifiedTime($gdrivefile->getModifiedTime());//modifiedTime
$parsedFile->setWritersCanShare($gdrivefile->getWritersCanShare());//writersCanShare
$parsedFile->setViewedByMeTime($gdrivefile->getViewedByMeTime());//viewedByMeTime
$parsedFile->setFolderColorRgb($gdrivefile->getFolderColorRgb());//folderColorRgb
$parsedFile->setOriginalFilename($gdrivefile->getOriginalFilename());//originalFilename
$parsedFile->setCopyRequiresWriterPermission($gdrivefile->getCopyRequiresWriterPermission());//copyRequiresWriterPermission
/*complex permissions*/
/*
contentHints.thumbnail.image
contentHints.thumbnail.mimeType
contentHints.indexableText
*/
$contenthints=$gdrivefile->getContentHints();//could be null meaning further functions eg getThumbnail cause exception
if($contenthints){
$parsedFile->setContentHints($contenthints->getThumbnail()->getImage());
$parsedFile->setContentHints($contenthints->getThumbnail()->getMimeType());
$parsedFile->setContentHints($contenthints->getIndexableText());
}
/*no function to get indiviual attributes*/
/*
contentRestrictions[].readOnly
ccontentRestrictions[].reason
*/
$parsedFile->setContentRestrictions($gdrivefile->getContentRestrictions());
//</ end>
return $parsedFile;
}
This is proving a bit successful but this is original meta
the above code does move it, with seemingly proper meta data, created time and EXIF data is now intact
The problem is that you are using file.update which uses HTTP PATCH methodology. By using a PATCH its going to try to update all of the properties in the file object that you send.
You did a file.get and you included fileds *
$fromFile = $this->service->files->get($fileID, ['fields' => '*']);
By including 'fields' => '*' you told the API to return to you all of the properties that the file has. A file resource has a lot of properties and they are not all writeable.
By sending the file.update method all of the fields you are telling it you want to update everything including some of the properties that you are not allowed to update. To which the api responds with fieldNotWritable
The soultion would be to do the following
$fromFile = $this->service->files->get($fileID, ['fields' => 'parents, id']);
Which will cause the method to only return the two parameters that you actual need. The id and the parents parameter. (TBH you may just need the parents part, I would need to test that.)
{
"id": "1x8-vD-XiA5Spf3qp8x2wltablGF22Lpwup8VtxNY",
"parents": ["0B1bbSFgVLpoXcVDRFRF8tTkU"
]
}
You should then be allowed to update the parent and move your file.
I don't know how to do in laravel but the problem might be
I have also faced the same problem some time and after searching internet for over months found nothing and one day Referring to documentation, seen that shared
isn't a writable field.
That's it, if you are sharing the File and trying to move the file it wouldn't move. Try to un-share the File and then try to move the File it would be done.
I ended up creating a custom function to only include writeable attributes as specified in the Google Documentation:
public function getParsedWritableFile($gdrivefile) {
$gdrivefile = new \Google_Service_Drive_DriveFile();//comment or delete, just here to check auto complete function names
$parsedFile = new \Google_Service_Drive_DriveFile();
// currently only allow these according to https://developers.google.com/drive/api/v3/reference/files#resource-representations
$parsedFile->setName($gdrivefile->getName());//name
$parsedFile->setMimeType($gdrivefile->getMimeType());//mimeType
$parsedFile->setDescription($gdrivefile->getDescription());//description
$parsedFile->setStarred($gdrivefile->getStarred());//starred
$parsedFile->setTrashed($gdrivefile->getTrashed());//trashed
$parsedFile->setParents($gdrivefile->getParents());//parents
$parsedFile->setProperties($gdrivefile->getProperties());//properties [object]
$parsedFile->setAppProperties($gdrivefile->getAppProperties());//appProperties [object]
$parsedFile->setCreatedTime($gdrivefile->getCreatedTime());//createdTime
$parsedFile->setModifiedTime($gdrivefile->getModifiedTime());//modifiedTime
$parsedFile->setWritersCanShare($gdrivefile->getWritersCanShare());//writersCanShare
$parsedFile->setViewedByMeTime($gdrivefile->getViewedByMeTime());//viewedByMeTime
$parsedFile->setFolderColorRgb($gdrivefile->getFolderColorRgb());//folderColorRgb
$parsedFile->setOriginalFilename($gdrivefile->getOriginalFilename());//originalFilename
$parsedFile->setCopyRequiresWriterPermission($gdrivefile->getCopyRequiresWriterPermission());//copyRequiresWriterPermission
/*complex permissions*/
/*
contentHints.thumbnail.image
contentHints.thumbnail.mimeType
contentHints.indexableText
*/
$contenthints=$gdrivefile->getContentHints();//could be null meaning further functions eg getThumbnail cause exception
if($contenthints){
$parsedFile->setContentHints($contenthints->getThumbnail()->getImage());
$parsedFile->setContentHints($contenthints->getThumbnail()->getMimeType());
$parsedFile->setContentHints($contenthints->getIndexableText());
}
/*no function to get indiviual attributes*/
/*
contentRestrictions[].readOnly
ccontentRestrictions[].reason
*/
$parsedFile->setContentRestrictions($gdrivefile->getContentRestrictions());
return $parsedFile;
}
and called with
public function moveFileFromTo($fileID, $toParentID) {
$fromFile = $this->service->files->get($fileID, ["fields" => "id,parents"]);
$fromFile = $this->getParsedWritableFile($fromFile);
$fromFile->setParents($toParentID);
$this->service->files->update($fileID, $fromFile, ['addParents' => $toParentID]);
}

How to get list of campaigns in Facebook Marketing API using PHP

an advanced thank you for taking time answering this.
I would like to retrieve all of my campaign list in facebook marketing API.
this is my code:
use FacebookAds\Object\AdUser;
use FacebookAds\Object\AdAccount;
use FacebookAds\Object\Fields\AdAccountFields;
use FacebookAds\Object\Campaign;
use FacebookAds\Object\AdCampaign;
use FacebookAds\Object\Fields\CampaignFields;
use FacebookAds\Object\Fields\AdCampaignFields;
use FacebookAds\Object\Fields\AdsInsightsFields;
use FacebookAds\Object\Fields\AdSetFields;
$account = new AdAccount($account_id);
$params = array(
'time_interval' => array(
'day_start' => array('year' =>'2015', 'month'=> '5', 'day'=>'1'),
'day_stop' => array( 'year'=>'2015', 'month'=>'5', 'day'=>'31')
),
'limit' => 500,
);
$fields = array(
AdCampaignFields::NAME, /* <--- this is the error */
AdCampaignFields::OBJECTIVE,
AdCampaignFields::STATUS,
);
$campaigns = $account->getAdCampaigns($fields,$params);
print_r($campaigns);
Now there are no result shown instead there's an error:
[14-Feb-2017 01:26:55 UTC] PHP Fatal error: Class 'FacebookAds\Object\Fields\AdCampaignFields' not found in /home/rbadmin17/public_html/test_17/index.php on line 98
I already call the "AdCampaignFields" and still it says Class not found.
Thanks for the help...
Your code looks correct but the class AdCampaignFields doesn't yet exist in the up to date SDK and was replaced by CampaignFields class (which isn't actually needed for your code).
Your code should work just by removing the line :
use FacebookAds\Object\Fields\AdCampaignFields;
Edit: in fact some examples of the FB doc are deprecated. Just take a look in the SDK folders to see by yourself when you get this kind of error. Sometimes it's just a class name which have been changed.

Unable to create bitcoin transaction using blockcypher api

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.

PHP: Error in creating Server Instance in Google Cloud Compute

While using Google Cloud Compute's API in PHP, I am able to start, stop, delete instances as well as create and delete disks.
However, when trying to create an Instance, I keep getting this error
Invalid value for field 'resource.disks'
PHP Fatal error: Uncaught exception 'Google_Service_Exception' with message 'Error calling POST https://www.googleapis.com/compute/v1/projects/project/zones/zone/instances: (400) Invalid value for field 'resource.disks': ''. Boot disk must be specified.' in /var/www/html/google/google-api-php-client/src/Google/Http/REST
Here is the request I am making
self::connectClient();
$computeService = new Google_Service_Compute($this->client);
if ($this->client->getAccessToken())
{
$googleNetworkInterfaceObj = new Google_Service_Compute_NetworkInterface();
$network = self::DEFAULT_NETWORK;
$googleNetworkInterfaceObj->setNetwork($network);
$diskObj = self::getDisk($instance_name);
$new_instance = new Google_Service_Compute_Instance();
$new_instance->setName($instance_name);
$new_instance->setMachineType(self::DEFAULT_MACHINE_TYPE);
$new_instance->setNetworkInterfaces(array($googleNetworkInterfaceObj));
$new_instance->setDisks(array(
"source"=>$diskObj->selfLink,
"boot"=>true,
"type"=>"PERSISTENT",
"deviceName"=>$diskObj->name,
));
$insertInstance = $computeService->instances->insert(self::DEFAULT_PROJECT,self::DEFAULT_ZONE_NAME, $new_instance);
Any help will be highly appreciated, thank you.
Ok the solution was really simple (and silly)
Instead of
$new_instance->setDisks(array(
"source"=>$diskObj->selfLink,
"boot"=>true,
"type"=>"PERSISTENT",
"deviceName"=>$diskObj->name,
));
It's supposed to be
$new_instance->setDisks(array(
array(
'source'=>self::getDisk($instance_name)->selfLink,
'boot'=>true,
'type' => "PERSISTENT",
'deviceName'=>self::getDisk($instance_name)->name,
)
));

Creating an outbound conference call in Twilio, Fatal error: Call to undefined method Services_Twilio::request()

I am trying to code some PHP for an outbound call conference room. The point of the conference room is to make a temporary solution for our customers calling one of our call centers, who need to be transferred, and automatically placed in a call with the other call center. This is exactly what we need, but having this error.
I already tried SMS and standard calls and those work fine. When I run the code below for conference calls, I get this error.
Fatal error: Call to undefined method Services_Twilio::request()
I have my conference.xml file already, like so.
<?xml version="1.0" encoding="UTF-8" ?>
<Response>
<Dial>
<Conference>i2c</Conference>
</Dial>
</Response>
And my conference.php file looks like this:
<?php
// The PHP Twilio helper library. Get it here http://www.twilio.com/docs/libraries/
require('twilio-php/Services/Twilio.php');
$API_VERSION = '2010-04-01';
$ACCOUNT_SID = 'my sid #';
$AUTH_TOKEN = 'my auth_token';
$client = new Services_Twilio($ACCOUNT_SID, $AUTH_TOKEN);
// The phone numbers of the people to be called
$participants = array('customer#', 'call-center#');
// Go through the participants array and call each person.
foreach ($participants as $participant)
{
$vars = array(
'From' => 'my #',
'To' => $participant,
'Url' => 'conference.xml');
$response = $client->request("/$API_VERSION/Accounts/$ACCOUNT_SID/Calls", "POST", $vars);
}
?>
It's getting an error on line 23, which is the line with the $response on it. Can you tell what's going wrong? I'm working off this code that Twilio provided. The part that says "Reach Out and Call Somebody". I changed TwilioRestClient to Services_Twilio because that is the newer version.
https://www.twilio.com/blog/2011/07/easy-conference-calling-twilio.html
Anyone see where I'm messing up?

Categories