It’s time to do some Evernote configuration.

To write an application that needs connection with Evernote I need a developer account. I have one, so in fact, you need it 😉

Credentials

Go to https://dev.evernote.com/doc/ and click “Get an API key” button and fill the form with your data. You’ll get Consumer Key and Consumer Secret needed to connect with Evernote.

Now I suggest you create a test account in https://sandbox.evernote.com/. It allows you to test your application using test account so you won’t mess up your real notes.

Installing SDK

The best way to install the SDK is to use Composer. Go in your console to `code` directory of the project and type `composer require evernote/evernote-cloud-sdk-php dev-master`. Let’s stop here for a moment and see what it does.

– `composer` simply executes Composer script.
– `require` tells, that you want to install the library
– `evernote/evernote-cloud-sdk-php` tells what library you need
– `dev-master` says what version you want

Note: You can often skip the last part and Composer will install the newest stable version of the library. But in this case, there is only developers version so I use `dev-master` to install the newest developer’s version.

This command will do all the work, so when it ends the SDK will be ready to use!

But there is a problem… It won’t work…

Dealing with broken libraries

[update] It’s now outdated, see the explanation in the end of this post.

Evernote SDK has one error – `start_session()` method is called twice. The second call, of course, throws an error. There is a pull request on GitHub with a fix, but it’s waiting for merge.

Thankfully, Composer can deal with such situations. All I had to do was fork the original repository on GitHub, fix the code and tell composer to use my repository instead of original one.

So in `composer.json` I had to add something like this:

"require": {
    ...
    "evernote/evernote-cloud-sdk-php": "dev-master"
},
"repositories": [
    {
        "type": "vcs",
        "url": "https://github.com/zelazowy/evernote-cloud-sdk-php"
    }
],

Now, execute `composer update` and all will be installed correctly using my fix.

Configuration

It’s a good practice to store any parameters needed for connecting with external services in `app/config/parameters.yml` file. Let’s add previously received consumer key and secret in there:

parameters:
    ...
    consumer_key: your_key
    consumer_secret: your_secret

Parameters stored there can be used by injection to services (I’ll cover it in the future) or by calling `$this->getParameter(“parameter_name”)` in a controller.

Note: Specifying parameters should be done by using `parameters.yml.dist`, but I’ll write more about it later, for now just fill those parameters in `parameters.yml` file and it’ll be ok.

Connection

Finally, the configuration is done so I can connect to the test account. Let’s create a new controller for dealing with Evernote. I’ll need one action for connecting with Evernote using consumer key and secret and receiving token for further communication.

class EvernoteController extends Controller
{
    /**
     * @Route("/connect", name="evernote_connect")
     */
    public function connectAction()
    {
        $key = $this->getParameter("consumer_key");
        $secret = $this->getParameter("consumer_secret");

        $oauthHandler = new OauthHandler(true, false, false);
        $tokenData = $oauthHandler->authorize($key, $secret, $this->generateUrl("evernote_connect", [], UrlGeneratorInterface::ABSOLUTE_URL));

        if (false === empty($tokenData)) {
            $token = $tokenData["oauth_token"];
            $this->get("session")->set("en_token", $token);

            return $this->redirectToRoute("note_list");
        }

        return new Response();
    }
}

The code is simple. Create Client, authorize in Evernote and receive the token. The only line that requires an explanation is the last one: `return new Response();`. It’s an empty response required by Symfony and the real redirect to Evernote is done inside `authorize` action using `header` function.

After authorizing your application you’ll receive the token which, for now, we’ll store in the user session. After that, you’ll be redirected to the list of notes controller, described in the previous post.

Getting the notes

Here comes the best. Getting the notes, the real notes, from Evernote.

Let’s start with the code.

    private function getNotes() : array
    {
        $token = $this->get("session")->get("en_token");

        $client = new Client($token, true);

        $nFilter = new NoteFilter();
        $nFilter->order = "created";
        $rSpec = new NotesMetadataResultSpec();
        $rSpec->includeTitle = true;

        /** @var NoteList $notesData */
        $notesData = $client->getUserNotestore()->findNotesMetadata($client->getToken(), $nFilter, 0, 50, $rSpec);

        $notes = [];
        /** @var NoteMetadata $noteData */
        foreach ($notesData->notes as $noteData) {
            $note = new Note();
            $note
                ->setId($noteData->guid)
                ->setTitle($noteData->title)
                ->setContent("unavailable")
                ->setCreatedAt((new \DateTime())->setTimestamp($noteData->created));

            $notes[] = $note;
        }

        return $notes;
    }

First I create `Client` object using received in `connectAction` token. Then I need to specify a filter for notes and it’ll be enough to order them by creation date.
Next, I need to specify what kind of data I want to receive. I set `includeTitle` to receive the title.
Now I can call `$client->getUserNotestore()->findNotesMetadata` to get notes’ data. This function gets only basic data like guid, title, creation date, etc. Content will be unavailable, so let’s skip it for a moment.
Let’s skip also reminder date because it requires some more actions to receive it and I’ll cover it in the next post.

Note: Because in Evernote id is stored as guid which is a string I’ve changed the type of `id` field in `Note` model from integer to string.

The final step is to create an array of `Note` models and return them just like dummy notes was returned earlier.

First look

If everything goes ok you shall see something like this (I have the notes in Polish, you’ll probably have some in your language 😉 )
Zrzut ekranu 2016-08-13 o 22.08.26

Note: I’ve changed the list template a little to increase readability.

Summary

And that’s basically it. Seeing real notes instead of dummy ones in nice, isn’t it? 🙂

You can find all the code presented in this post here.

Update 2016-08-30

Evernote finally has merged fix for duplicated `session_start()` calls 🙂

You can now skip the whole section Dealing with broken libraries, it’ll be enough to install the SDK like it’s described in Installing SDK section.
All changes are available, as always, in the GitHub.

Don’t forget to check out other PHPhyts!