Code Monkey home page Code Monkey logo

pinterest-php's Introduction

Pinterest PHP

Scrutinizer Code Quality Code Coverage Packagist Packagist

Install

Via Composer

$ composer require hansott/pinterest-php

Donate

If you like this package, please consider buying me a coffee. Thank you for your support! πŸ™‡β€β™‚οΈ

Buy Me A Coffee

Usage

Authentication

To use the API, you need an access token from Pinterest. Create a new Pinterest application if you haven't already. You then get a client ID and a client secret, specific for that application.

Back in your PHP application, create a Pinterest\Http\ClientInterface instance (the default is Pinterest\Http\BuzzClient) and use it to create an Pinterest\Authentication instance:

$client = new Pinterest\Http\BuzzClient();
$auth = new Pinterest\Authentication($client, $clientId, $clientSecret);

Replace the $clientId and $clientSecret variables with the data of your Pinterest application.

You can now let your user authenticate with your application be redirecting them to the URL obtained by a call to $auth->getAuthenticationUrl(), like this:

use Pinterest\App\Scope;

$url = $auth->getAuthenticationUrl(
    'https://your/redirect/url/here',
    array(
        Scope::READ_PUBLIC,
        Scope::WRITE_PUBLIC,
        Scope::READ_RELATIONSHIPS,
        Scope::WRITE_RELATIONSHIPS,
    ),
    'random-string'
);

header('Location: ' . $url);
exit;
  • The redirect URL is the URL to the page where pinterest will send us the authentication code for the user registering with your application. This URL needs to be accessible over https, and it has to be filled into to form of your Pinterst application (in the Pinterest backend).
  • The second parameter is an array of permissions your app needs on the user's account. There needs to be at least one here.
  • The validation state is a random code that you generate for the user registering, and persist (in SESSION for instance). Pinterest will send it back to us for further reference.

When your application user agrees to let your app take control of their Pinterest account via the API, Pinterest will redirect them to the URL you provided as redirect URL, with some added GET parameters. The most important being "code", which we'll trade for an OAuth access token in the next step. They'll also send the validation state back to us as a GET parameter so we can check if we expected this call.

The last step in the process is trading that code for an access token:

$code = $_GET['code'];
$token = $auth->requestAccessToken($code);

You should persist that token safely at this point. You can use it from now on to connect to the Pinterest API from your application, on behalf of the user.

Initialize the Pinterest\Api class:

$auth = Pinterest\Authentication::onlyAccessToken($client, $token);
$api = new Pinterest\Api($auth);

Using the Pinterest\Api instance in $api, you can now make authenticated API requests to Pinterest's API on behalf of the user.

Get the authenticated user

$response = $api->getCurrentUser();

if (!$response->ok()) {
    die($response->getError());
}

$user = $response->result(); // $user instanceof Objects\User

Get a user

// Get user by username
$response = $api->getUser('otthans');

// Get user by user id
$response = $api->getUser('314196648911734959');

if (!$response->ok()) {
    die($response->getError());
}

$user = $response->result(); // $user instanceof Objects\User

Get a board

$response = $api->getBoard('314196580192594085');

if (!$response->ok()) {
    die($response->getError());
}

$board = $response->result(); // $board instanceof Objects\Board

Update a board

// First, get the board using getBoard()
$response = $api->getBoard('314196580192594085');

if (!$response->ok()) {
    die($response->getError());
}

$board = $response->result(); // $board instanceof Objects\Board

// Or create a new board without getBoard()

$board = new Board;
$board->id = 'the-board-id';

// Then, update the fields you want to change

$board->name = 'New board name';
$board->description = 'New board description';
$response = $api->updateBoard($board);

if (!$response->ok()) {
    die($response->getError());
}

$updatedBoard = $response->result(); // $updatedBoard instanceof Objects\Board

Get the boards of the authenticated user

$response = $api->getUserBoards();

if (!$response->ok()) {
    die($response->getError());
}

$pagedList = $response->result(); // $pagedList instanceof Objects\PagedList
$boards = $pagedList->items(); // array of Objects\Board objects

Get the pins of the authenticated user

$response = $api->getUserPins();

if (!$response->ok()) {
    die($response->getError());
}

$pagedList = $response->result(); // $pagedList instanceof Objects\PagedList
$pins = $pagedList->items(); // array of Objects\Pin objects

Get the pins of a board

$response = $api->getBoardPins($boardId);

if (!$response->ok()) {
    die($response->getError());
}

$pagedList = $response->result(); // $pagedList instanceof Objects\PagedList
$pins = $pagedList->items(); // array of Objects\Pin objects

See Get the next items of a paged list

Get the followers of the authenticated user

$response = $api->getUserFollowers();

if (!$response->ok()) {
    die($response->getError());
}

$pagedList = $response->result(); // $boards instanceof Objects\PagedList
$users = $pagedList->items(); // array of Objects\User objects

See Get the next items of a paged list

Get the boards that the authenticated user follows

$response = $api->getUserFollowingBoards();

if (!$response->ok()) {
    die($response->getError());
}

$pagedList = $response->result(); // $boards instanceof Objects\PagedList
$boards = $pagedList->items(); // array of Objects\Board objects

See Get the next items of a paged list

Get the users that the authenticated user follows

$response = $api->getUserFollowing();

if (!$response->ok()) {
    die($response->getError());
}

$pagedList = $response->result(); // $boards instanceof Objects\PagedList
$users = $pagedList->items(); // array of Objects\User objects

See Get the next items of a paged list

Get the interests that the authenticated user follows

Example: Modern architecture

$response = $api->getUserInterests();

if (!$response->ok()) {
    die($response->getError());
}

$pagedList = $response->result(); // $boards instanceof Objects\PagedList
$boards = $pagedList->items(); // array of Objects\Board objects

See Get the next items of a paged list

Follow a user

$response = $api->followUser('otthans');

if (!$response->ok()) {
    die($response->getError());
}

Unfollow a user

$response = $api->unfollowUser('otthans'); // username or user ID

if (!$response->ok()) {
    die($response->getError());
}

Follow a board

$response = $api->followBoard('teslamotors', 'model-x');

if (!$response->ok()) {
    die($response->getError());
}

Unfollow a board

$response = $api->unfollowBoard('teslamotors', 'model-x');

if (!$response->ok()) {
    die($response->getError());
}

Create a board

$name = 'My new board';
$optionalDescription = 'The description of the board';
$response = $api->createBoard($name, $optionalDescription);

if (!$response->ok()) {
    die($response->getError());
}

$board = $response->result(); // $board instanceof Objects\Board

Delete a board

$boardId = '314196580192594085';
$response = $api->createBoard($boardId);

if (!$response->ok()) {
    die($response->getError());
}

Create a pin

$board = '<username>/<board_name>'; 
$note = 'This is an amazing pin!';
$optionalLink = 'http://hansott.github.io/';

// Load an image from a url.
$image = Pinterest\Image::url('http://lorempixel.com/g/400/200/cats/');

// Load an image from a file.
$pathToFile = 'myfolder/myimage.png';
$image = Pinterest\Image::file($pathToFile);

// Load a base64 encoded image.
$pathToFile = 'myfolder/myimage.png';
$data = file_get_contents($pathToFile);
$base64 = base64_encode($data);
$image = Pinterest\Image::base64($base64);
 
$response = $api->createPin($board, $note, $image, $optionalLink);

if (!$response->ok()) {
    die($response->getError());
}

$pin = $response->result(); // $pin instanceof Objects\Pin

Get a pin

$pinId = 'the-pin-id';
$response = $api->getPin($pinId);

if (!$response->ok()) {
    die($response->getError());
}

$pin = $response->result(); // $pin instanceof Objects\Pin

Update a pin

// First, get the pin using getPin()

$pinId = 'the-pin-id';
$response = $api->getPin($pinId);

if (!$response->ok()) {
    die($response->getError());
}

$pin = $response->result();

// Or create a new Pin without getPin()

$pin = new Pin;
$pin->id = 'the-pin-id';

// Then, update the fields you want to change

// Update note
$pin->note = 'a new note';

// Update link
$pin->link = 'https://google.com';

$response = $api->updatePin($pin);

if (!$response->ok()) {
    die($response->getError());
}

$updatedPin = $response->result();

Delete a pin

$pinId = 'the-pin-id';
$response = $api->deletePin($pinId);

if (!$response->ok()) {
    die($response->getError());
}

Get the next items of a paged list

$hasMoreItems = $pagedList->hasNext();

if (!$hasMoreItems) {
    return;
}

$response = $api->getNextItems($pagedList);

if (!$response->ok()) {
    die($response->getError());
}

$nextPagedList = $response->result();

Contributing

Please see CONTRIBUTING for details.

Security

If you discover any security related issues, please email hansott at hotmail be instead of using the issue tracker.

Credits

License

The MIT License (MIT). Please see License File for more information.

pinterest-php's People

Contributors

hansott avatar narainsagar avatar scrutinizer-auto-fixer avatar shailesh-daund avatar subodhdahal avatar turanct 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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pinterest-php's Issues

Cannot Authorize Token from Code

Hi, I have a problem when authorizing my code to token. I have tried the javascript version and it works fine but I need to do with PHP. Here is the code.

$client = new Pinterest\Http\BuzzClient();
$clientId = "xxx";
$clientSecret = "xxx";
$auth = new Pinterest\Authentication($client, $clientId, $clientSecret);

if(empty($_GET["code"])){
	$callbackurl = 'mycallbackurl';
	$url = $auth->getAuthenticationUrl(
		$callbackurl,
		array(
			Scope::READ_PUBLIC,
			Scope::WRITE_PUBLIC,
			Scope::READ_RELATIONSHIPS,
			Scope::WRITE_RELATIONSHIPS,
		),
		'random-string'
	);

	header('Location: ' . $url);
	exit;
}
else{
	$code = $_GET['code'];
	$token = $auth->requestAccessToken($code);
	echo $token; --> here is the error
}

It produces code but the problem is when the code is converted into a token. That gave this following error.

Fatal error: Uncaught Pinterest\Api\Exceptions\TokenMissing in /home/admin/ocicio/botsector/vendor/hansott/pinterest-php/src/Pinterest/Authentication.php:222 Stack trace: #0 /home/admin/ocicio/botsector/index.php(31): Pinterest\Authentication->requestAccessToken('d77eecdc2dae2ad...') #1 {main} thrown in /home/admin/ocicio/botsector/vendor/hansott/pinterest-php/src/Pinterest/Authentication.php on line 222

Get pins from a board

There seems to be no function available to get the pins from a certain board (of the authenticated user).
Would be nice to have this!
Thanks

Notice: Undefined offset: 1 in /vendor/hansott/pinterest-php/src/Pinterest/Http/BuzzClient.php on line 71

Hi,
I have installed the PHP Pinterest API on my server and I have authenticated the user using OAuth. When I am trying to get board details I am facing an issue "Notice: Undefined offset: 1 in /vendor/hansott/pinterest-php/src/Pinterest/Http/BuzzClient.php on line 71". I have debugged the issue and found that the key "Pinterest-Generated-By" doesn't have the value. For this please refer Line number 71 in /vendor/hansott/pinterest-php/src/Pinterest/Http/BuzzClient.php

Line cauisng issue,

list($key, $value) = explode(': ', $header);

My code:

$client = new Pinterest\Http\BuzzClient();

$auth = Pinterest\Authentication::onlyAccessToken($client, $token);
$api = new Pinterest\Api($auth);

$response = $api->getUserBoards();

Please let me know why I am facing this issue. And do I need to add value in settings to get the value for "Pinterest-Generated-By"?

Thanks

Simple Question regarding "Follow a Board" and "Repin / Save a Pin" functions

Hey,
Thanks for this library πŸ‘ I did a bit of research and seems like this is the only Pinterest official API PHP wrapper which is being maintained regularly.. πŸ‘

I have 2 quick questions:

Does it support all API endpoints ? and specifically Does it have methods for following functions:

  • Follow a Board
  • Repin / Save A Pin

Thanks.

Notice: Undefined offset: 1 in /vendor/hansott/pinterest-php/src/Pinterest/Http/BuzzClient.php on line 71

Hi,
I am also facing the same issue
I have installed the PHP Pinterest API on my server and I have authenticated the user using OAuth. When I am trying to get board details I am facing an issue "Notice: Undefined offset: 1 in /vendor/hansott/pinterest-php/src/Pinterest/Http/BuzzClient.php on line 71". I have debugged the issue and found that the key "Pinterest-Generated-By" doesn't have the value. For this please refer Line number 71 in /vendor/hansott/pinterest-php/src/Pinterest/Http/BuzzClient.php

Line cauisng issue,

list($key, $value) = explode(': ', $header);

My code:

$client = new Pinterest\Http\BuzzClient();

$auth = Pinterest\Authentication::onlyAccessToken($client, $token);
$api = new Pinterest\Api($auth);

$response = $api->getUserBoards();
Please let me know why I am facing this issue. And do I need to add value in settings to get the value for "Pinterest-Generated-By"?

Thanks

Need Suggesstion on Pinterest API options

Hi,
We are using the Pinterest API to add pins in our Boards. We have figured out the steps in PHP to get access token and create pins in our board. On proceeding further with our development we have few doubts,

  1. We came across a option called "Section" in each board. We have researched to find the PHP code for creating the section in a board. But we can't able to get any reference for creating sections in a board. So can anyone help us by providing any reference to create sections.

  2. We tried to try the advertisement in Pinterest Campaign, but in Step #3 it is allowing us to select only one pin at a time for campaign promotion. I tried with different types of promotions but I can't able to select multiple pins at a time for promotion. Can we able to select multiple pins in the ads manager? Or is there any API to manager the ads and the campaigns, so we can control it through automation. Please let us know your suggestions.

Thanks

Error - Operation timed out after 5000 milliseconds with 0 bytes received

I am not sure, if there's any issue or something but I noticed and got this this error once (*I'm using the api from past 15+ days, i.e., I never noticed this before.).

Fatal error: Uncaught Exception: Operation timed out after 5000 milliseconds with 0 bytes received in /Users/narainsagar/www/SweepWidgetLive/vendor/hansott/pinterest-php/src/Pinterest/Http/BuzzClient.php on lineΒ 123 --

screen shot 2018-04-13 at 4 19 52 am

deletePin sprintf format causes data conversion and thus results in pin not found

deletePin->658440407994591131
print_r($request):
Pinterest\Http\Request Object
(
[method:Pinterest\Http\Request:private] => DELETE
[endpoint:Pinterest\Http\Request:private] => pins/2147483647/
[params:Pinterest\Http\Request:private] => Array
(
)

[headers:Pinterest\Http\Request:private] => Array
    (
    )

)

My fix:
Api.php Line 489
< $request = new Request('DELETE', sprintf('pins/%d/', $pinId));

$request = new Request('DELETE', sprintf('pins/%s/', $pinId));

Save (Re-Pin) a pin

Hans, Thanks for the code.
Do you have the ability to Save (Re-Pin) a pin.
(I am not referring to Create a pin, which i see you can already do)

Thanks
Hil

Edit Pins option is missing

Hi,
I am using this API for managing boards and pins of Pinterest. In this API, I can't able to find the function for "Edit Pins". Can you please add the function and release the new file as soon as possible.

And do you have any reference to managing the Pinterest Campaigns and Ads through API?

Waiting for your response.

Thanks

Can not install package

Failed to download hansott/pinterest-php from dist: The archive may contain identical file names with different capitalization (which fails on case insensitive filesystems): ZipArchive::extractTo(): Full extraction path exceed MAXPATHLEN (260)
Now trying to download from source

System: Win10
some files are very long name

pinterest-php-master\tests\Pinterest\responses\post_v1_pins_314196580192658592_A_note!_7839fe8158191d9aedc41da6132fff1a_id_link_url_creator_board_created_at_note_color_counts_media_attribution_image_metadata.json

when changing code to an access token I am getting this error

Fatal error: Uncaught Pinterest\Api\Exceptions\TokenMissing in /home/socialwe/public_html/pinterestApi/vendor/hansott/pinterest-php/src/Pinterest/Authentication.php:222 Stack trace: #0 /home/socialwe/public_html/pinterestApi/index.php(29): Pinterest\Authentication->requestAccessToken('d4b81156aa5111a...') #1 {main} thrown in /home/socialwe/public_html/pinterestApi/vendor/hansott/pinterest-php/src/Pinterest/Authentication.php on line 222

I get a token, but can't use $api in callback -- auth error

My Pinterest app is in development. Thanks for any help.

I make my redirect fine --
I get called backed and there is a code --
I get a token from the code.
No matter how I try to create the $auth and $api -- when I try to use the api - I see the error at the bottom

Here's my callback code:

    $this->client = new Pinterest\Http\BuzzClient();
    $this->auth   = new Pinterest\Authentication($this->client,
            env('PINTEREST_APP_ID'),
            env('PINTEREST_APP_SECRET'));

    $code  = $_GET['code'];
    try {
        $token = $this->auth->requestAccessToken($code);

    } catch (\Exception $e) {
         die('rate limit reached -- try again later');
    }
   // I have tried both of these and the result is always the same
    if (true){
        $auth = Pinterest\Authentication::onlyAccessToken($this->client, $token);
    } else{
        $auth = Pinterest\Authentication::withAccessToken($this->client,
                     env('PINTEREST_APP_ID', false),
                     env('PINTEREST_APP_SECRET', false),
                    $token);
    }
 
    $api  = new Pinterest\Api($auth);
    $response = $api->getCurrentUser();    // always fails.

--- at this point, I get an exception -- see below.

object(Pinterest\Http\Response)[502]
public 'body' =>
object(stdClass)[496]
public 'status' => string 'failure' (length=7)
public 'message' => string 'Authorization failed.' (length=21)
public 'code' => int 3
public 'data' => null
private 'statusCode' => int 401
private 'rawBody' => string '{"status": "failure", "message": "Authorization failed.", "code": 3, "data": null}' (length=82)
private 'headers' =>
array (size=14)

ACCESS_TOKEN Pin Sharing

Hello there,

I do not have API access, can we pin only with access_token? Can you share sample code.

I can't get user info

Hello, im new here and i like start use this API
here is my code (one file send.php):

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require DIR . '/vendor/autoload.php';

use Pinterest\App\Scope;

$client = new \Pinterest\Http\BuzzClient();
$appId = '.............';
$appSecret = '...............................';
$auth = new \Pinterest\Authentication($client, $appId, $appSecret);

$url = $auth->getAuthenticationUrl(
'https://www.mysite.com/hansott/send.php',
array(
Scope::READ_PUBLIC,
Scope::WRITE_PUBLIC,
Scope::READ_RELATIONSHIPS,
Scope::WRITE_RELATIONSHIPS,
),
'random-state'
);

if(!ISSET($_GET['code'])){
header('Location: '.$url);
exit();
}
else{
$token = $auth->requestAccessToken($_GET['code']);
$auth = Pinterest\Authentication::onlyAccessToken($client, $token);
$api = new Pinterest\Api($auth);

$response = $api->getCurrentUser();

if (!$response->ok()) {
    die($response->getError());
}

$user = $response->result(); // $user instanceof Objects\User

var_dump($user);

}

Thanks you

Malformed Json Error

Hello i am getting malformed json error after one succesfull pin. I checked rawBody response and it look like a jpeg code.
I attached a screenshot which is shows how response is.

1

Proxy Usage

Hi, how can we use proxy for api requests?

$api->getUserBoards() suddenly failing

This happens after I auth a new user. All of which works fine. The user has 2 boards.

basically I do this:

$response = $api->getUserBoards();
if (!$response->ok())
{"message": "Invalid parameters.", "type": "api", "param": "creator"}

Any thoughts?

Parameter 'board' is required.

$image = Pinterest\Image::file('images.jpg');
$response = $api->createPin('746612513164716763', "test func", $image, "https://website.com");

if (!$response->ok()) {
die($response->getError());
}

failed: Parameter 'board' is required.

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.