Giter VIP home page Giter VIP logo

php-photoslibrary's Introduction

Google Photos Library API PHP Client Library

This repository contains the PHP client library for the Google Photos Library API.

You can find samples for this library in the samples branch. See the samples section below.

Requirements and preparation

This library depends on Composer. If you don't have Composer installed on the command line as composer, follow the Linux/unix/OS X or Windows installation guides.

  • System requirements and dependencies can be found in composer.json of this library. If you are not familiar with Composer, see this page for more details.
  • Your PHP installation must include the bcmath extension.
  • OAuth 2.0 credentials configured for your project as described below.

Download the client library

Firstly, download the library, then set up OAuth 2.0 credentials to access the API. Next, you can follow the samples to see the client library in action.

Here are some ways to download this library:

Method Target Users
Using composer require If you want to use this library as a third-party library for your projects and do not require example files.
Using git clone If you want to alter or contribute to this library (for example, submitting a pull request) or want to run example files.
Downloading a compressed tarball If you only want to run example files.

Using composer require

Follow the below steps to download this library as a third-party library for your projects. The library will be downloaded by Composer and stored under the vendor/ directory. Examples are not downloaded by this download method.

$ composer require google/photos-library

Using git clone

Use this method if you want to alter or contribute to this library (for example, submitting pull requests) or if you wish to try our samples. When you clone the repository, all files in this repository will be downloaded.

  1. Run git clone https://github.com/google/php-photoslibrary.git at the command prompt.
  2. You'll get a php-photoslibrary directory. Navigate to it by running cd php-photoslibrary.
  3. Run composer install at the command prompt. This will install all dependencies needed for using the library.

Downloading a compressed tarball

Use this method only if you want to try out the Google Photos Library API with this client library. The extracted directory of the tarball will contain only the samples from the samples branch.

  1. On the releases page, select a version you want to try. Then, under Download, select the tarball of your choice, for example, php-photoslibrary-samples-vX.Y.Z.tar.gz.
  2. Extract your downloaded file to any location on your computer.
  3. Navigate to the extracted directory (for example, php-photoslibrary-samples-vX.Y.Z).
  4. Run composer install at the command prompt. This will install all dependencies needed for using the library and running examples.

Set up your OAuth2 credentials for PHP

The Google Photos Library API uses OAuth2 as the authentication mechanism. Note that the Library API does not support service accounts.

To complete the “Enable the API” and “Configure OAuth2.0” steps in the below procedure, refer to the get started guide in the developer documentation

This client library works with the Google Auth Library for PHP. Specify the client secret JSON file when initialising the library. Use the authentication credentials returned by the auth library when setting up the PhotosLibraryClient. See the file sample/src/common/common.php for an example on how to do this.

Sample usage

The best way to learn how to use this library is to review the samples. The developer documentation also includes code snippets for this client library in PHP.

Once you have set up the dependencies and OAuth 2 credentials, you can access the API. Here's a short example that shows how to create a new album:

// [START sample_usage]
use Google\Auth\Credentials\UserRefreshCredentials;
use Google\Photos\Library\V1\PhotosLibraryClient;
use Google\Photos\Library\V1\PhotosLibraryResourceFactory;

try {
    // Use the OAuth flow provided by the Google API Client Auth library
    // to authenticate users. See the file /src/common/common.php in the samples for a complete
    // authentication example.
    $authCredentials = new UserRefreshCredentials( /* Add your scope, client secret and refresh token here */ );

    // Set up the Photos Library Client that interacts with the API
    $photosLibraryClient = new PhotosLibraryClient(['credentials' => $authCredentials]);

    // Create a new Album object with at title
    $newAlbum = PhotosLibraryResourceFactory::album("My Album");

    // Make the call to the Library API to create the new album
    $createdAlbum = $photosLibraryClient->createAlbum($newAlbum);

    // The creation call returns the ID of the new album
    $albumId = $createdAlbum->getId();
} catch (\Google\ApiCore\ApiException $exception) {
    // Error during album creation
} catch (\Google\ApiCore\ValidationException $e) {
    // Error during client creation
    echo $exception;
}
// [END sample_usage]

Retry configuration

The default retry configuration follows the AIP guidance for retrying API requests, which is configured in photos_library_client_config.json.

This client library uses the Google gax-php library to make calls. See its reference documentation for \Google\ApiCore\RetrySettings that describes how to customize the retry configuration for individual invocations, for a group of API calls or for an entire client instance.

Media byte uploads made using PhotosLibraryClient -> upload (..) that have failed are not attempted again unless a retry configuration has been specified. Customize the UploadRetrySettings to configure the retry behaviour. Here's an example that shows how to change the retry behaviour for byte uploads for a client instance:

$uploadRetrySettings = [
    'initialRetryDelayMillis' => 1000, // 1 second
    'retryDelayMultiplier' => 1.3,
    'maxRetryDelayMillis' => 10000, // 10 seconds
    'singleTimeoutMillis' => 900000, // 15 minutes
    'maxNumRetries' => 5,
    'retryableCodes' => [ApiStatus::DEADLINE_EXCEEDED, ApiStatus::UNAVAILABLE],
    'retryableExceptions' => []
];

$photosLibraryClient = new PhotosLibraryClient([
    'credentials' => $myCredentials,
    'uploadRetrySettings' => $uploadRetrySettings
]);

Samples

A few samples are included in the samples directory. They show how to access media items, filter media, share albums, and upload files.

Reference Documentation

PHPDoc for this library can be found in the gh-pages branch of this repository. You can browse it online here: https://google.github.io/php-photoslibrary/index.html

General Google Photos Library API documentation can be found on our Google Developers site: https://developers.google.com/photos

Coding Style

We use PSR-2 as a coding style standard. Assuming that you're at the root directory of your project, to check for coding style violations, run

./vendor/bin/phpcs --standard=phpcs_ruleset.xml -np

To automatically fix (fixable) coding style violations, run

./vendor/bin/phpcbf --standard=phpcs_ruleset.xml

Getting support

For client library specific bug reports, feature requests, and patches, create an issue on the issue tracker.

See the support page for any other API questions, bug reports, or feature requests.

Announcements and updates

For general Google Photos Library API and client library updates and news, follow:

License

Copyright 2018 Google LLC

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

php-photoslibrary's People

Contributors

arielmagbanua avatar jfschmakeit avatar laurenmanzo avatar livgorton avatar signpostmarv avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

php-photoslibrary's Issues

Easily access credentials from browser

I am using credentials.json file to access clientid, redirecturl, and so on. is it safe to use from json file, because we can access it from direct url

Error Uploading File

Type: Error

Message: Call to undefined method Google\Photos\Library\V1\NewMediaItem::setFileName()

Filename: ..vendor/google/photos-library/src/Google/Photos/Library/V1/PhotosLibraryResourceFactory.php

Line Number: 100

Fatal Error when calling methods on in PhotosLibraryClient class

I am getting the error below when calling any method on a PhotosLibraryClient object. I read on stackoverflow that this could be due to a missing bcmath extension but enabling this (via composer) did not help.

Fatal error: Uncaught Error: Call to undefined function Google\Protobuf\Internal\bccomp() in /app/vendor/google/protobuf/src/Google/Protobuf/Internal/Message.php:933 Stack trace: #0 /app/vendor/google/protobuf/src/Google/Protobuf/Internal/Message.php(1218): Google\Protobuf\Internal\Message->convertJsonValueToProtoValue('1242', Object(Google\Protobuf\Internal\FieldDescriptor)) #1 /app/vendor/google/protobuf/src/Google/Protobuf/Internal/Message.php(1167): Google\Protobuf\Internal\Message->mergeFromArrayJsonImpl(Array) #2 /app/vendor/google/protobuf/src/Google/Protobuf/Internal/Message.php(815): Google\Protobuf\Internal\Message->mergeFromJsonArray(Array) #3 /app/vendor/google/protobuf/src/Google/Protobuf/Internal/Message.php(1218): Google\Protobuf\Internal\Message->convertJsonValueToProtoValue(Array, Object(Google\Protobuf\Internal\FieldDescriptor)) #4 /app/vendor/google/protobuf/src/Google/Protobuf/Internal/Message.php(1167): Google\Protobuf\Internal\Message->mergeFromArrayJsonImpl(Array) #5 /app/vendor/google/protobuf/src/ in /app/vendor/google/protobuf/src/Google/Protobuf/Internal/Message.php on line 933

Token has been expired or revoked

Although I use the parameter "access_type = offline" the token expires and I can not work offline for more than 1 hour.
The error message is:
{
"error": "invalid_grant",
"error_description": "Token has been expired or revoked."
}

And the code is
$authCredentials = new UserRefreshCredentials( [ 'https://www.googleapis.com/auth/photoslibrary.sharing', 'https://www.googleapis.com/auth/photoslibrary' ], [ 'client_id' => $this->client_id, 'refresh_token' => $this->refreshToken, 'client_secret' => $this->clientSecret, ] );
How can I renew the token without user intervention?

server to server connect

thanks for the good examples, I would like to know how to connect to bees without passing from the google windows authorization for example for a server-to-server functionality

Example code fails with error unsupported_grant_type

Trying to run example code from docs but it fails with this error:

PHP Fatal error:  Uncaught GuzzleHttp\Exception\ClientException: Client error: `POST https://oauth2.googleapis.com/token` resulted in a `400 Bad Request` response:
{
  "error": "unsupported_grant_type",
  "error_description": "Invalid grant_type: "
}
 in /media/G/BFHome/Projects/Web/GooglePhoto/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php:113
Stack trace:
#0 /media/G/BFHome/Projects/Web/GooglePhoto/vendor/guzzlehttp/guzzle/src/Middleware.php(66): GuzzleHttp\Exception\RequestException::create(Object(GuzzleHttp\Psr7\Request), Object(GuzzleHttp\Psr7\Response))
#1 /media/G/BFHome/Projects/Web/GooglePhoto/vendor/guzzlehttp/promises/src/Promise.php(203): GuzzleHttp\Middleware::GuzzleHttp\{closure}(Object(GuzzleHttp\Psr7\Response))
#2 /media/G/BFHome/Projects/Web/GooglePhoto/vendor/guzzlehttp/promises/src/Promise.php(156): GuzzleHttp\Promise\Promise::callHandler(1, Object(GuzzleHttp\Psr7\Response), Array)
#3 /media/G/BFHome/Projects/Web/GooglePhoto/vendor/guzzlehttp/promises/src/TaskQueue.php(47): GuzzleHttp\Promise\Pr in /media/G/BFHome/Projects/Web/GooglePhoto/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php on line 113

Code I've tried to run:

<?php
require('vendor/autoload.php');

use Google\Auth\Credentials\UserRefreshCredentials;
use Google\Photos\Library\V1\PhotosLibraryClient;
use Google\Photos\Library\V1\PhotosLibraryResourceFactory;

$credentials = json_decode(file_get_contents('credentials.json'), true);
$credentials = $credentials['installed'];
$credentials['refresh_token'] = null; // fails with error "Missing required parameter: refresh_token" without setting it

$scopes = array(
    'https://www.googleapis.com/auth/photoslibrary.readonly',
    //'https://www.googleapis.com/auth/photoslibrary',
    'https://www.googleapis.com/auth/photoslibrary.sharing',
    'https://www.googleapis.com/auth/photoslibrary.appendonly',
    'https://www.googleapis.com/auth/photoslibrary.readonly.appcreateddata'
);

$authCredentials = new UserRefreshCredentials(
    /* Add your scope, client secret and refresh token here */
    $scopes,
    $credentials
);

$photosLibraryClient = new PhotosLibraryClient(['credentials' => $authCredentials]);

$newAlbum = PhotosLibraryResourceFactory::album("Example Album");

$createdAlbum = $photosLibraryClient->createAlbum($newAlbum);

$albumId = $createdAlbum->getId();

The error occurs when calling $photosLibraryClient->createAlbum($newAlbum).

Please fix creation_time

When $photosLibraryClient->batchCreateMediaItems($newMediaItems, ['albumId' => $albumId]);

Error:
vendor/google/gax/src/ApiCore/Transport/RestTransport.php:153
Error occurred during parsing: String specified for bool or submessage field: creation_time

common/common.php uses League/Plates/Engine

I am trying to play with this example but am running into the problem that it apparently uses a template from League/Plates/Engine, without 'require'-ing any script. I tried adding

'use League/Plate/Engine'

to common/common.php, hoping that the server that I am working on had the templates installed, but this does not help.

I am a bit new to standalone php development, so far have been working on a Joomla! website, which had a lot of the boiler plate stuff taken care of.

Do you have any suggestion how to get going with the samples without the League templates and/or how to get a minimal version of it downloaded?

Thanks, Marco.

Descriptions with unicode characters are ignored in batchCreateMediaItems

Descriptions that contain unicode characters are ignored when calling batchCreateMediaItems(..).

We have verified this by using the string КОНТАКТНЫЙ ТЕЛЕФОН.

This does not appear to be an issue in the API itself, but rather an issue with the encoding of strings when making the request.

token expired how to refresh?

i will be the only one using it , on the backend server side meaning 1 user only i tried saved token on a file but how do i refresh because it expires after 1 hour

Can't get next page token from response

Hi,
When making a call to searchMediaItems, the response object does not contain the methods of SearchMediaItemsResponse, only PagedListResponse, therefore I am unable to retrieve the next page token.

$photosLibraryClient = new PhotosLibraryClient(['credentials' => $credentials]);
$response = $photosLibraryClient->searchMediaItems(['pageSize' => 50]);

$response->getNextPageToken() is undefined

Json key is missing the refresh token field in google photos api

While authenticate i got this error

Fatal error: Uncaught InvalidArgumentException: json key is missing the refresh_token field in C:\xampp\htdocs\gphotos\vendor\google\auth\src\Credentials\UserRefreshCredentials.php:78 Stack trace: #0 C:\xampp\htdocs\gphotos\config.php(49): Google\Auth\Credentials\UserRefreshCredentials->__construct(Array, Array) #1 C:\xampp\htdocs\gphotos\index.php(5): connectWithGooglePhotos() #2 {main} thrown in C:\xampp\htdocs\gphotos\vendor\google\auth\src\Credentials\UserRefreshCredentials.php on line 78

Cannot install with PHP 8

When I run composer require google/photos-library I get this error:

google/photos-library dev-main requires php ^5.5 || ^7.0 -> your php version (8.0.5) does not satisfy that requirement.

Is there anything specific that is incompatible with PHP 8, or should the platform requirements be simply changed to >=5.5, which doesn't exclude PHP 8?

Tests Failed on PHP Version 5.5

One of the test of current main branch code is failing on PHP version 5.5.

image

I bet originally the method was setExpectedException from phpunit 4.8.36. It is likely somebody refactored it to expectException since he/she might be working on new PHP version (perhaps 7.0?) which implies newer version of phpunit which setExpectedException is definitely deprecated.

Should we stop supporting PHP version 5.5 and support newer PHP version and then replace those deprecated methods?

pageSize has no effect ?

Sorry for my poor english.

I downloaded sample from this repo, and change line 36 of albums/index.php

from
$pagedResponse = $photosLibraryClient->listAlbums();

to
$pagedResponse = $photosLibraryClient->listAlbums(['pageSize' => '5']);

but i got all 58 albums back.

README issues

There is a dead link to samples on the README page (under review the samples), and the sample itself is missing some key components, such as php syntax in the code blocks, a use statement for the PhotosLibraryClient class, and an explanation for $_SESSION['credentials'].

I would submit a PR but my understanding is all of this is automatically generated. Or are the READMEs maintained separately? If so I can submit some fixes.

InvalidArgumentException with guzzlehttp dependency

Error message is clear:

InvalidArgumentException: Passing in the "body" request option as an array to send a POST request has been deprecated. Please use the "form_params" request option to send a application/x-www-form-urlencoded request, or the "multipart" request option to send a multipart/form-data request. 

Please update library.

EDIT: ok, it is more google/gax issue than this one, but media uploading is broken currently.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.