Giter Club home page Giter Club logo

intercom-php's Introduction

intercom-php

Circle CI packagist Intercom API Version

Official PHP bindings to the Intercom API

Project Updates

Maintenance

We're currently building a new team to provide in-depth and dedicated SDK support.

In the meantime, we'll be operating on limited capacity, meaning all pull requests will be evaluated on a best effort basis and will be limited to critical issues.

We'll communicate all relevant updates as we build this new team and support strategy in the coming months.

Installation

This library supports PHP 7.1 and later

This library uses HTTPlug as HTTP client. HTTPlug is an abstraction that allows this library to support many different HTTP Clients. Therefore, you need to provide it with an adapter for the HTTP library you prefer. You can find all the available adapters in Packagist. This documentation assumes you use the Guzzle6 Client, but you can replace it with any adapter that you prefer.

The recommended way to install intercom-php is through Composer:

composer require intercom/intercom-php php-http/guzzle6-adapter

Clients

Initialize your client using your access token:

use Intercom\IntercomClient;

$client = new IntercomClient('<insert_token_here>');

If you already have an access token you can find it here. If you want to create or learn more about access tokens then you can find more info here.

If you are building a third party application you can get your OAuth token by setting-up-oauth for Intercom.

For most use cases the code snippet above should suffice. However, if needed, you can customize the Intercom client as follows:

Add custom headers

use Intercom\IntercomClient;

$client = new IntercomClient(
    '<insert_token_here>',
    null,
    ['Custom-Header' => 'value']
);

Use a custom HTTP client

This client needs to implement Psr\Http\Client\ClientInterface

$client->setHttpClient($yourHttpClient);

Use a custom request factory

This factory needs to implement Http\Message\RequestFactory

$client->setRequestFactory($yourRequestFactory);

Use a custom URI factory

This factory needs to implement Http\Message\UriFactory

$client->setUriFactory($yourUriFactory); 

API Versions

This library is intended to work with any API Version. By default, the version that you have configured for your App in the Developer Hub will be used. However, you can overwrite that version for a single request or for all the requests using this library by including the Intercom-Version header when initializing the client as follows:

use Intercom\IntercomClient;

$client = new IntercomClient(
    '<insert_token_here>',
    null,
    ['Intercom-Version' => '1.1']
);

For more information about API Versioning, please check the API Versioning Documentation and the API changelog.

Important: Not all the resources supported by this API are supported by all API versions. See the notes below or the API Reference for more information about the resources supported by each API version.

Contacts

This resource is only available in API Versions 2.0 and above

/** Create a contact */
$client->contacts->create([
    'custom_attributes' => ['nickname' => 'Teddy'],
    'email' => '[email protected]',
    'type' => 'user',
]);

/** Update a contact */
$client->contacts->update('570680a8a1bcbca8a90001b9', [
    'custom_attributes' => ['nickname' => 'Teddy'],
    'email' => '[email protected]',
]);

/** Permanently delete a contact */
$client->contacts->deleteContact('570680a8a1bcbca8a90001b9');

/** Get a contact by ID */
$client->contacts->getContact('570680a8a1bcbca8a90001b9');

/** Search for contacts */
$query = ['field' => 'name', 'operator' => '=', 'value' => 'Alice'];
$client->contacts->search([
    'pagination' => ['per_page' => 10],
    'query' => $query,
    'sort' => ['field' => 'name', 'order' => 'ascending'],
]);

/** Get next page of conversation search results */
$client->contacts->nextSearch($query, $response->pages);

/** List all contacts */
$client->contacts->getContacts([]);

Users

This resource is only available in API Versions 1.0 to 1.4. Newer versions use the Contacts resource instead.

/** Create a user */
$client->users->create([
    'custom_attributes' => ['nickname' => 'Teddy'],
    'email' => '[email protected]',
]);

/**
 * Update a user (Note: This method is an alias to the create method. In practice you
 * can use create to update users if you wish)
 */
$client->users->update([
    'custom_attributes' => ['nickname' => 'Teddy'],
    'email' => '[email protected]',
]);

/** Archive a user by ID (i.e. soft delete) */
$client->users->archiveUser('570680a8a1bcbca8a90001b9');

/** Permanently delete a user */
$client->users->permanentlyDeleteUser('570680a8a1bcbca8a90001b9');

/** For more on the difference between archive and permanently deleting a user please see https://developers.intercom.com/reference#archive-a-user. */

/** Get a user by ID */
$client->users->getUser('570680a8a1bcbca8a90001b9');

/** Add companies to a user */
$client->users->create([
    'companies' => [
        [
            'company_id' => '3',
        ]
    ],
    'email' => '[email protected]',
]);

/** Remove companies from a user */
$client->users->create([
    'companies' => [
        [
            'company_id' => '3',
            'remove' => true,
        ]
    ],
    'email' => '[email protected]',
]);

/** Find a single user by email */
$client->users->getUsers([
    'email' => '[email protected]',
]);

/** List all users up to 10k records */
$client->users->getUsers([]);

/**
 * List all users (even above 10k records)
 * The result object contains an array of your user objects and a scroll_param which you can then
 * use to request the next 100 users. Note that the scroll parameter will time out after one minute
 * and you will need to make a new request
 */
$client->users->scrollUsers();

See here for more info on using the scroll parameter

Leads

This resource is only available in API Versions 1.0 to 1.4. Newer versions use the Contacts resource instead.

/**
 * Create a lead
 * See more options here: https://developers.intercom.io/reference#create-lead
 */
$client->leads->create([
    'custom_attributes' => ['nickname' => 'Teddy'],
    'email' => '[email protected]',
]);

/**
 * Update a lead (Note: This method is an alias to the create method.
 * In practice you can use create to update leads if you wish)
 */
$client->leads->update([
    'custom_attributes' => ['nickname' => 'Teddy'],
    'email' => '[email protected]',
]);

/**
 * List leads
 * See more options here: https://developers.intercom.io/reference#list-leads
 */
$client->leads->getLeads([]);

/** Find a lead by ID */
$client->leads->getLead('570680a8a1bcbca8a90000a9');

/** Delete a lead by ID */
$client->leads->deleteLead('570680a8a1bcbca8a90000a9');

/** Convert a Lead to a User */
$client->leads->convertLead([
    'contact' => [
        'user_id' => '8a88a590-e1c3-41e2-a502-e0649dbf721c',
    ],
    'user' => [
        'email' => '[email protected]',
    ],
]);

/**
 * List all leads (even above 10k records)
 * The result object contains an array of your contacts objects and a scroll_param which you can then
 * use to request the next 100 leads. Note that the scroll parameter will time out after one minute
 * and you will need to make a new request
 */
$client->leads->scrollLeads();

See here for more info on using the scroll parameter

Visitors

Retrieve user_id of a visitor via the JavaScript API

/** Update a visitor */
$client->visitors->update([
    'custom_attributes' => ['nickname' => 'Teddy'],
    'user_id' => '8a88a590-e1c3-41e2-a502-e0649dbf721c',
]);

/** Find a visitor by ID */
$client->visitors->getVisitor('570680a8a1bcbca8a90000a9');

/** Find a visitor by User ID */
$client->visitors->getVisitor('', [
    'user_id' => '8a88a590-e1c3-41e2-a502-e0649dbf721c',
]);

/** Delete a visitor by ID */
$client->visitors->deleteVisitor('570680a8a1bcbca8a90000a9');

/** Convert a Visitor to a Lead */
$client->visitors->convertVisitor([
    'type' => 'lead',
    'visitor' => [
        'user_id' => '8a88a590-e1c3-41e2-a502-e0649dbf721c',
    ],
]);

/** Convert a Visitor to a User */
$client->visitors->convertVisitor([
    'type' => 'user',
    'user' => [
        'email' => '[email protected]',
    ],
    'visitor' => [
        'user_id' => '8a88a590-e1c3-41e2-a502-e0649dbf721c',
    ],
]);

Tags

/** List tags */
$client->tags->getTags();

/**
 * Tag users
 * See more options here: https://developers.intercom.io/reference#tag-or-untag-users-companies-leads-contacts
 */
$client->tags->tag([
    'name' => 'Test',
    'users' => [
        ['id' => '1234'],
    ],
]);

Segments

/** List Segments */
$client->segments->getSegments();

/** View a segment */
$client->segments->getSegment('58a707924f6651b07b94376c');

/** View a segment with count */
$client->segments->getSegment('59c124f770e00fd819b9ce81', [
    'include_count' => 'true',
]);

Events

/** Create an event */
$client->events->create([
    'created_at' => 1391691571,
    'email' => '[email protected]',
    'event_name' => 'testing',
    'metadata' => [
        'order_date' => 1392036272,
        'stripe_invoice' => 'inv_3434343434',
    ],
]);

/** View events for a user */
$client->events->getEvents(['email' => '[email protected]']);

Companies

/** Create a company */
$client->companies->create([
    'company_id' => '3',
    'name' => 'foocorp',
]);

/**
 * Update a company
 */
$client->companies->update([
    'id' => '3',
    'name' => 'foocorp',
]);

/** Create or update a company with custom attributes. */
$client->companies->update([
    'custom_attributes' => [
        'short_name' => 'ABC Inc.',
    ],
    'id' => '3',
    'name' => 'foocorp',
]);

/** List Companies */
$client->companies->getCompanies([]);

/** Get a company by ID */
$client->companies->getCompany('531ee472cce572a6ec000006');

/** List users belonging to a company by ID */
$client->companies->getCompanyUsers('531ee472cce572a6ec000006');

/** List users belonging to a company by company_id */
$client->companies->getCompanies([
    'company_id' => '3',
    'type' => 'user',
]);

/**
 * Add companies to a contact with IDs
 * First parameter is contact ID, second is company ID
 */
$client->companies->attachContact('570680a8a1bcbca8a90001b9', '531ee472cce572a6ec000006');

/**
 * Detach company from contact
 * First parameter is contact ID, second is company ID
 */
$client->companies->detachContact('570680a8a1bcbca8a90001b9', '531ee472cce572a6ec000006');

Admins

/** List admins */
$client->admins->getAdmins();

Messages

/**
 * Send a message from an admin to a user
 * See more options here: https://developers.intercom.io/reference#conversations
 */
$client->messages->create([
    'body' => 'Ponies, cute small horses or something more sinister?',
    'from' => [
        'id' => '1234',
        'type' => 'admin',
    ],
    'message_type' => 'inapp',
    'subject' => 'Hey',
    'to' => [
        'email' => '[email protected]',
        'type' => 'user',
    ],
]);

Conversations

/**
 * Create a conversation
 * See more options here: https://developers.intercom.com/intercom-api-reference/reference#create-a-conversation
 */
$client->conversations->create([
    'body' => 'Hello.',
    'from' => [
        'id' => '1234',
        'type' => 'user',
    ],
]);

/**
 * List conversations for an admin
 * See more options here: https://developers.intercom.io/reference#list-conversations
 */
$client->conversations->getConversations([
    'admin_id' => '25610',
    'type' => 'admin',
]);

/** Get a single conversation */
$client->conversations->getConversation('1234');

/** Get a single conversation with plaintext comments */
$client->conversations->getConversation('1234', [
    'display_as' => 'plaintext',
]);

/** Search for conversations (API version >= 2.0) */
$query = ['field' => 'updated_at', 'operator' => '>', 'value' => '1560436784'];
$client->conversations->search([
    'pagination' => ['per_page' => 10],
    'query' => $query,
    'sort' => ['field' => 'updated_at', 'order' => 'ascending'],
]);

/** Get next page of conversation search results (API version >= 2.0) */
$client->conversations->nextSearch($query, $response->pages);

/**
 * Reply to a conversation
 * See more options here: https://developers.intercom.io/reference#replying-to-a-conversation
 */
$client->conversations->replyToConversation('5678', [
    'body' => 'Thanks :)',
    'email' => '[email protected]',
    'message_type' => 'comment',
    'type' => 'user',
]);

/**
 * Reply to a user's last conversation
 * See more options here: https://developers.intercom.com/reference#replying-to-users-last-conversation
 */
$client->conversations->replyToLastConversation([
    'body' => 'Thanks :)',
    'email' => '[email protected]',
    'message_type' => 'comment',
    'type' => 'user',
]);

/**
 * Mark a conversation as read
 * See API documentation here: https://developers.intercom.io/reference#marking-a-conversation-as-read
 */
$client->conversations->markConversationAsRead('7890');

Counts

/**
 * List counts
 * See more options here: https://developers.intercom.io/reference#getting-counts
 */
$client->counts->getCounts([]);

Notes

/** Create a note */
$client->notes->create([
    'admin_id' => '21',
    'body' => 'Text for my note',
    'user' => [
        'id' => '5310d8e8598c9a0b24000005',
    ]
]);

/** List notes for a user */
$client->notes->getNotes([
  'user_id' => '25',
]);

/** Get a single Note by id */
$client->notes->getNote('42');

Teams

/** List teams */
$client->teams->getTeams();

/** Get a single Team by id */
$client->teams->getTeam('1188');

Rate Limits

Rate limit info is passed via the rate limit headers. You can access this information as follows:

$rate_limit = $client->getRateLimitDetails();
print("{$rate_limit['remaining']} {$rate_limit['limit']} \n");
print_r($rate_limit['reset_at']->format(DateTime::ISO8601));

For more info on rate limits and these headers please see the API reference docs

Pagination

When listing, the Intercom API may return a pagination object:

{
  "pages": {
    "next": "..."
  }
}

You can grab the next page of results using the client:

$client->nextPage($response->pages);

In API versions 2.0 and above subsequent pages for listing contacts can be retreived with:

$client->nextCursor($response->pages);

Scroll

The first time you use the scroll API you can just send a simple GET request. This will return up to 100 records. If you have more than 100 you will need to make another call. To do this you need to use to scroll_parameter returned in the original response. Use this for subsequent responses until you get an empty array of records. This means there are no records and the scroll timer will be reset. For more information on scroll please see the API reference Here is an example of a simple way to use the scroll for multiple calls:

require "vendor/autoload.php";

use Intercom\IntercomClient;

$client = new IntercomClient(getenv('AT'), null);
$resp = $client->users->scrollUsers([]);
$count = 1;
echo "PAGE $count: " . sizeof($resp->users);
echo "\n";
while (!empty($resp->scroll_param) && sizeof($resp->users) > 0) {
    $count = ++$count;
    $resp = $client->users->scrollUsers(["scroll_param" => $resp->scroll_param]);
    echo "PAGE $count: " . sizeof($resp->users);
    echo "\n";
}

Exceptions

Exceptions are handled by HTTPlug. Every exception thrown implements Http\Client\Exception. See the http client exceptions and the client and server errors. The Intercom API may return an unsuccessful HTTP response, for example when a resource is not found (404). If you want to catch errors you can wrap your API call into a try/catch block:

try {
    $user = $client->users->getUser('570680a8a1bcbca8a90001b9');
} catch(Http\Client\Exception $e) {
    if ($e->getCode() == '404') {
        // Handle 404 error
        return;
    } else {
        throw $e;
    }
}

Pull Requests

  • Add tests! Your patch won't be accepted if it doesn't have tests.

  • Document any change in behaviour. Make sure the README and any other relevant documentation are kept up-to-date.

  • Create topic branches. Don't ask us to pull from your master branch.

  • One pull request per feature. If you want to do more than one thing, send multiple pull requests.

  • Send coherent history. Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please squash them before sending them to us.

intercom-php's People

Contributors

512banque avatar andrewtseipp avatar apassant avatar bobjflong avatar bviolier avatar choran avatar dannyfallon avatar dehora avatar edudobay avatar enrico-intercom avatar eugeneius avatar falldi avatar fnwbr avatar gabrielanca avatar joe-gaudet-hs avatar johnnynader avatar jonnyom avatar josler avatar klimesf avatar kmossco avatar lucasmichot avatar mmartinic avatar murtron avatar nurazem avatar oskarstark avatar ruairik avatar shibby avatar thewheat avatar tyloo avatar ziemkowski 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  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  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

intercom-php's Issues

getUser returns an iterator?

Hi,

I was trying to do this:

$intercom = \Intercom\IntercomBasicAuthClient::factory([
'app_id' => 'xyxyxyxy',
'api_key' => 'yxyxyxyxyx'
]);

$iUser = $intercom->getUser(
[
'email' => $someEmail
]
);

however I just get a list - and the first user in the list doesn't even have that email address.

Is there a problem with the API or the way I'm using it?
Cheers

Bug in docs

custom_data should become custom_attributes in the readme.

ConversationTest failing on type parameter

ConversationTest.php is expecting a type=user parameter to be set automatically but there's none. Looking at the guzzle definition file for conversation, it doesn't have a default value.

"type": {
                    "location": "query",
                    "required": true,
                    "static": true,
                    "default": "user"
                },

phpunit run below


There was 1 failure:

1) Intercom\ConversationTest::testGetConversations
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-'/conversations?type=user'
+'/conversations'

/Users/dehora/intercom/intercom-php/src/Intercom/IntercomTestCase.php:51
/Users/dehora/intercom/intercom-php/tests/Intercom/Resources/ConversationTest.php:50

FAILURES!
Tests: 77, Assertions: 236, Failures: 1.

Updating a user without specifying 'id'

Is id a required field for updateUser, or would it be OK if I update the service config?

My interpretation of the docs at http://doc.intercom.io/api/#create-or-update-user was that specifiying user_id or email should allow me to update the user, and that id is not required?

Note that the following lookup order applies when updating users - id then user_id then email, and results in the following logic -

id is matched - the user_id and email will be updated if they are sent.
user_id match - the email will be updated, the id is not updated.
email match - the user_id will be updated if sent, the id is not updated if sent.

Function getConversation doesn't take options... Should it?

Docs: getConversation can take an option

In the Intercom docs (https://developers.intercom.io/reference#get-a-single-conversation) it says you can optionally request that messages be returned in plain text:

getconversation_ref

Code: getConversation doesn't have a parameter for options

But in IntercomConversations.php, the function getConversation only takes one parameter:

public function getConversation($id) {
    $path = $this->conversationPath($id);
    return $this->client->get($path, []);
}

Problem this causes

I can't retrieve the messages of a conversation in plain text.

My hack

*I'm not saying this is the RIGHT way to make this better, or that you should do this. I'm just including it to illustrate the problem a bit more.

Locally, I updated the function getConversation in IntercomConversations.php to accept options:

public function getConversation($id, $options) {
    $path = $this->conversationPath($id);
    return $this->client->get($path, $options);
}

Now I can get messages in plain text:

$client = new IntercomClient( '<appID>', '<apiKey>');
$conversations = new IntercomConversations( $client );
$convo = $conversations->getConversation( $conversation["id"], array( "display_as" => "plaintext" ) );

Validate custom attribute syntax

The custom_attributes object allows you to send any information you wish about a user with the following restrictions:

  • Field names must not contain Periods (โ€˜.โ€™) or Dollar (โ€˜$โ€™) characters

convertLead() call do not work as expected

Version info

  • intercom-php version: 2.0.0
  • PHP version: 5.6.16

Expected behavior

$leads->convertLead() call with both contact and user identifiers set should merge contact with user and delete the contact.

Actual behavior

When $leads->convertLead() called with both contact and user identifiers set, creates a converted the contact to a new user. System then has two users with same email address.

Steps to reproduce (as granular as possible, including screenshots where appropriate)

  1. $lead = $client->leads->getLead('8a88a590-e1c3-41e2-a502-e0649dbf721c');
  2. $user = $client->users->getUsers(['email'=>$lead->email]);
  3. $response = $client->leads->convertLead(array('contact'=>array('user_id'=>$lead->id), 'user'=>array('user_id'=>$user->user_id)));

Please, assume $contact and $lead exists (and are proper) and so point (3) looks something like following.

$response = $client->leads->convertLead(array('contact'=>array('user_id'=>'8a88a590-e1c3-41e2-a502-e0649dbf721c'), 'user'=>array('user_id'=>'578d39cd1806525670000190")));

$response should return a user object having user_id same as the 'user->user_id' passed to it but it returns a new user_id and adds a new user in the system.

Logs

Problem with curl

Hello!

We are often got some errors
2015-03-14 15:43:39 0.21587300 [5822]: Internal error - [curl] 60: [url] https://api.intercom.io/users
2015-03-14 15:43:51 0.53412100 [5822]: Internal error - [curl] 60: [url] https://api.intercom.io/users
2015-03-14 15:44:18 0.27215200 [5822]: Internal error - [curl] 60: [url] https://api.intercom.io/users
2015-03-14 15:56:33 0.21471500 [5822]: Internal error - [curl] 60: [url] https://api.intercom.io/users
2015-03-14 15:57:19 0.56658900 [5822]: Internal error - [curl] 60: [url] https://api.intercom.io/users
2015-03-14 15:57:41 0.40475400 [5822]: Internal error - [curl] 60: [url] https://api.intercom.io/users
2015-03-14 16:00:12 0.43175000 [5822]: Internal error - [curl] 60: [url] https://api.intercom.io/users
2015-03-14 16:03:14 0.83226900 [5822]: Internal error - [curl] 60: [url] https://api.intercom.io/users
2015-03-14 16:04:49 0.08834600 [5822]: Internal error - [curl] 60: [url] https://api.intercom.io/users
2015-03-14 16:06:24 0.59697500 [5822]: Internal error - [curl] 60: [url] https://api.intercom.io/users

Code 60 in curl_d.php define ('CURLE_SSL_CACERT', 60);
And also such errors 2015-03-12 11:13:23 0.80077600 [5822]: Internal error - [curl] 51: SSL: certificate subject name '.nextpoint.com' does not match target host name 'api.intercom.io' [url] https://api.intercom.io/users
2015-03-12 11:14:05 0.65313000 [5822]: Internal error - [curl] 51: SSL: certificate subject name '
.nextpoint.com' does not match target host name 'api.intercom.io' [url] https://api.intercom.io/users
2015-03-12 11:16:04 0.51287700 [5822]: Internal error - [curl] 51: SSL: certificate subject name '.nextpoint.com' does not match target host name 'api.intercom.io' [url] https://api.intercom.io/users
2015-03-12 11:16:31 0.15936900 [5822]: Internal error - [curl] 51: SSL: certificate subject name '
.nextpoint.com' does not match target host name 'api.intercom.io' [url] https://api.intercom.io/users
2015-03-12 11:16:48 0.96651500 [5822]: Internal error - [curl] 51: SSL: certificate subject name '*.nextpoint.com' does not match target host name 'api.intercom.io' [url] https://api.intercom.io/users

Error Intercom API

Hello friends recently bought a plan intercom .

And I would like to get the following data from a form and send that data as a new User 's intercom .

However this error returning me to do this, I'm following the step by step here GitHub and even the developers documents.

Warning: require(vendor/autoload.php): failed to open stream: No such file or directory in /home/u213882019/public_html/Intercom/user.php on line 3

Fatal error: require(): Failed opening required 'vendor/autoload.php' (include_path='.:/opt/php-5.6/pear') in /home/u213882019/public_html/Intercom/user.php on line 3

returns me that error above. I entered the SSH and gave the following command.
composer require intercom/intercom-php
and I fell this screen
image

however still returns me this error Fatal error: Class 'GuzzleHttp\Client' not found in /home/u213882019/public_html/Intercom/Intercom/IntercomClient.php on line 71

Please can someone help me? Thanks!

Media Type not acceptable when sending bulk request

Version info

  • intercom-php version: 2.0.0
  • PHP version: 5.6.7

Expected behavior

Updating via bulk request should not return error, that "The Accept header should send a media type of application/json".

Actual behavior

updating users via bulk request returns error: "The Accept header should send a media type of application/json".
This is the actual response:
{"app_id":"yf209ops","id":"job_v2_c5e0b20a_895d_11e6_9b38_5dea02a373e5","created_at":1475494652,"updated_at":1475494652,"completed_at":null,"name":"api_bulk_job","closing_at":1475495552,"state":"running","links":{"error":"https:\/\/api.intercom.io\/jobs\/job_v2_c5e0b20a_895d_11e6_9b38_5dea02a373e5\/error","self":"https:\/\/api.intercom.io\/jobs\/job_v2_c5e0b20a_895d_11e6_9b38_5dea02a373e5"}}
Users are not updated in Intercom, when checking the link in "error" field, it gives me following message:
{errors:[{code:"media_type_not_acceptable",message:"The Accept header should send a media type of application/json"}],type:"error.list"}

Steps to reproduce (as granular as possible, including screenshots where appropriate)

  1. Create new IntercomClient with app_id + app_secret
  2. Send bulk request with users and custom attributes, e.g.:
$attributes['plan'] = $user->plan;
$attributes['active'] = $user->active;
$attributes['email'] = $user->email;
$items[] = [
    'method' => 'post',
    'data_type' => 'user',
    'attributes' => $attributes
];
  1. Get this error as response

Are there any known issues with the API?

User data is not accurate

When I run $intercom->getUsers(); the total_count field in the User model is saying 157, but the All segment in Intercom is saying the correct number 715. Why is that? Also I noticed that many of the "created_at" and "updated_at" fields aren't matching their Intercom in-app numbers, what I assume to be "Signed up" and "Last seen".

On a side note I noticed that the api will only let me pull 60 users at a time, is there any way to increase that? I'm trying to extract my full user model once a day to build metrics and graphs with.

Call to /events returning a 404

Brand new to this API today, but a few successful calls to the getUser() and was able to tag the user... I tried to call the createEvent() and got this.

:: Client error response
[status code] 404
[reason phrase] Not Found
[url] https://api.intercom.io/events on 47 in Intercom/Exception/IntercomException.php

getLeads with created_since do not filter leads

Version info

  • intercom-php version: 2.0.0
  • PHP version: 5.6.16

Expected behavior

$client->leads->getLeads(['created_since'=>2]); Call should return filtered results that are about few hundred leads in my case.

Actual behavior

$client->leads->getLeads(['created_since'=>2]); call returns over 4000 pages of 50 instances per page that are same as if I omit "created_since" parameter.

   [type] => contact.list
    [pages] => stdClass Object
        (
            [type] => pages
            [next] => https://api.intercom.io/contacts?created_since=2&per_page=50&page=2
            [page] => 1
            [per_page] => 50
            [total_pages] => 4072
        )

Steps to reproduce (as granular as possible, including screenshots where appropriate)

  1. $client = new IntercomClient(PAT, null)
  2. $client->leads->getLeads(['created_since'=>2]);

Am I missing something or it actually has some issues?

bootstrap.php include not working properly

Hi,

In the file "bootstrap.php" under tests folder, line 5

include DIR . '/../vendor/autoload.php';

If I ran phpunit in command line, "up one level" which is ".." is not working for me so I have to manually specify the absolute path for it. It seems it also happened to others, please give a look, thanks.

ly

Install with PHP version 5.5 it's not possible

I love to stay updated, but IT department upgrade the PHP versions only with the OS Repositories. In our current platform we have 5.5.9 version of PHP.

I think that your business is justly to have more clients using your platform. I think too this situation is present in a lot of organizations, so I think that you have to keep in mind this limitation to fix them. It's only a suggestion, or maybe you can release a version to PHP 5.5 -at least- and other to the current PHP Version like PHP 7 -i.e.-

Version info

  • intercom-php version: v3.0.0
  • PHP version: PHP 5.5.9

Expected behavior

  • To be installed

Actual behavior

  • It's not installed when you have PHP 5.5 version

Steps to reproduce (as granular as possible, including screenshots where appropriate)

  1. You need to have PHP 5.5.X.
  2. execute: composer require intercom/intercom-php

Logs

Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

Problem 1
- intercom/intercom-php v3.0.0 requires php >= 5.5.9 -> your PHP version (5.5.9) overridden by "config.platform.php" version (5.5.9) does not satisfy that requirement.
- intercom/intercom-php v3.0.0 requires php >= 5.5.9 -> your PHP version (5.5.9) overridden by "config.platform.php" version (5.5.9) does not satisfy that requirement.
- Installation request for intercom/intercom-php ^3.0 -> satisfiable by intercom/intercom-php[v3.0.0].

Items not updating

Version info

  • intercom-php version: v2.0.0
  • PHP version: 5.6.20

Expected behavior

Updating user identified by email should update items like name, etc.. I tried this:

$user = [
    'email' => '[email protected]',
    'name' => 'Changed name',
];
$response = $client->users->create($user);

Dumping $response shows correct information about user with newly set up name parameter. But when I open Intercom and find by email, user has the old name.

Steps to reproduce

  1. create user
  2. try to update params like name
  3. the old param values are in Intercom

Logs

Metadata cannot be blank for Event

According https://doc.intercom.io/api/#event-metadata-types
I'm try to create Event using php

$intercom->createEvent(array(
  "event_name" => "placed-order",
  "created_at" => 1391691571,
  "user_id" => "314159",
  "metadata" => $more_metadata
));

If pass $more_metadata such as empty array []
In this case i got error Bad Request response from Intercom.

It not critical and I add if, but if you fix it will very fantastic =)

Make it work on PHP 5.5 or provide work-around?

Hi,

We can't update our server platform right now but are in immediate need to track events in the backend. We run PHP 5.5 on an IIS-platform.

My main question is: how can we and/or you fix this and create a work around?

Version info

  • intercom-php version: 2.0.0
  • PHP version: 5.5

Expected behavior

  • It should work and not give an error message.

Actual behavior

Halts with PHP error:
Parse error: syntax error, unexpected 'function' (T_FUNCTION), expecting identifier (T_STRING) or \\ (T_NS_SEPARATOR) in C:\inetpub\yyy\vendor\intercom\intercom-php\src\IntercomClient.php on line 7

Steps to reproduce

  1. Use PHP 5.5
  2. Follow the intended installation with composer and usage
  3. Look at the error message

Client error response

Hi, I am getting this error message:

Client error response [status code] 404 [reason phrase] Not Found [url] https://api.intercom.io/events

What could be the problem?

Not Working Need to fix default Accept Header for CURL PHP

Today i have tried to integrate Intercom IO with one of my projects and i had to waste lots of time finding this issue. Intercom site is not providing any response without HTTP ACCEPT header being set to "application/json". Please set it as the default header in all curl requests to make a use of this library.

If possible then please provide option for debuging by setting CURLOPT_VERBOSE to true. You can also raise an exception if the response from server is other then HTTP 200, like in this case it is always 406.

Version info

  • intercom-php version: 1.5
  • PHP 5.5.9-1ubuntu4.14 (cli) (built: Oct 28 2015 01:34:46)
    Copyright (c) 1997-2014 The PHP Group
    Zend Engine v2.5.0, Copyright (c) 1998-2014 Zend Technologies
    with Zend OPcache v7.0.3, Copyright (c) 1999-2014, by Zend Technologies
    with Xdebug v2.2.3, Copyright (c) 2002-2013, by Derick Rethans

Expected behavior

An array list of companies

Actual behavior

Null

Steps to reproduce

  1. Install provided setup with composer.
  2. Set up a call to get companies list
  3. check the result

Logs

Problem with JSON parsing

A call to https://api.intercom.io/events returns a 202 response with an empty " " space in it. This causes issues with Guzzle since it cannot be parsed as json:

{"error":{"type":"Guzzle\Common\Exception\RuntimeException","message":"Unable to parse response body into JSON: 4","file":"/home/vagrant/myapp/vendor/guzzle/guzzle/src/Guzzle/Http/Message/Response.php","line":861}}

Event > create "found unpermitted parameters: metadata" error

In Php, empty associative array are JSON encoded as "[]" and so, sending:

POST https://api.intercom.io/events
{"created_at":1430841996,"event_name":"merchant_created","metadata":[],"user_id":"1"}

Gives

{
    "type": "error.list",
    "request_id": "7e654619-03e4-43e8-aaef-8d0c82850bf2",
    "errors": [
        {
            "code": "parameter_invalid",
            "message": "found unpermitted parameters: metadata"
        }
    ]
}

A possible solution would be to remove metadata field is it's empty.

Problem with save user data

Hello,
I am using intercom-php and try to save user info,

  1. can't save information like: avatar, or social_profiles
    $newUser = $intercom->createUser(array(
    "email" => '[email protected]',
    "name" => 'Hello World',
    "last_request_at" => time(),
    "created_at" => time(),
    "avatar" => array(
    "type" => "avatar",
    "image_url" => 'http://url.to.image'
    ),
    "location_data" => array(
    "type" => "location_data",
    "latitude" => $location[1],
    "longitude" => $location[0]
    ),
    "social_profiles" => array(
    "type" => "social_profile",
    "name" =>"facebook",
    "id" => '1234',
    "username" => 'Facebook User Name',
    "url" => 'http://facebook.url'
    )
    ));
    In intercom user with email '[email protected]' was created , but avatar and social_profiles data are empty.
    What I missed?
  2. Can't create message from user..
    $text = $intercom->createMessage(array(
    "message_type" => "inapp",
    "subject" => $subject,
    "body" => $text,
    "template" => "plain",
    "from" => array(
    "type" => "user",
    "id" => '123a'
    ),
    "to" => array(
    "type" => "user",
    "id" => '123b'
    )
    ));
    Users Ids : '123a' & '123b' - exist in intercom.
    Any ideas??
    P.S. There are no errors in both cases.

media_type_not_acceptable and The Accept header should send a media type of application/json error

I am writing a custom PHP script to use CURL to get all the user IDs within my app (all pages, so I need to create a pagination loop which the Intercom PHP library doesn't support, so am doing it in PHP itself). Once I have all user IDs from all pages, I need to pass these user IDs into the events API endpoint.

I have a PHP script that is running on localhost via MAMP, but see the error below.
screen shot 2015-12-12 at 15 11 35

My code is below, I have left in commented out code chunks so you can see the multiple things I tried.

<?php
$login = 'string with my app ID';
$password = 'string with my API key';
header('Content-Type: application/json');
// ;charset=utf-8
$url = 'https://api.intercom.io/users';
$additionalHeaders = array(
  'Content-type: application/json',
  'Authorization: string with my appID:string with my api key',
);

//  Initiate curl
$ch = curl_init();
// $ch = curl_init($url);
//Set the URL
curl_setopt($ch, CURLOPT_URL,$url);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);

curl_setopt($process, CURLOPT_HTTPHEADER, array('Content-Type: application/json', $additionalHeaders));
curl_setopt($process, CURLOPT_HEADER, true);
curl_setopt($process, CURLOPT_TIMEOUT, 30);
curl_setopt($process, CURLOPT_POST, 1);
curl_setopt($process, CURLOPT_POSTFIELDS, $payloadName);
  // Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//Set the type of authentication to CURLAUTH_BASIC
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
//Set the username and password
curl_setopt($ch, CURLOPT_USERPWD, $login . ":" . $password);
//Execute the command
$result = curl_exec($ch);
//Close curl.
curl_close($ch);
//Set the header to be JSON
// header('Content-Type: application/json');

// Will dump a beauty json :3
// echo json_encode($result );
var_dump(json_decode($result, true));
?>

Interface to check API limiting

Can we have a interface to check the API limit?

Example:

$company = $intercom->getCompany($company);
$callsLeft = $company->meta->rate_limit;
$endOfWindow = $company->meta->limit_ending;

ClientErrorResponse exception too general, all code/type info is in message string

Version info

  • intercom-php version: v1.5.0
  • PHP version: 5.5.9-1ubuntu4.14

Expected behavior

  1. When running a batch update (i.e. tagCompanies()) I expect the update to go through and return any error info in the event of an error. For example, if I batch update 50 company IDs to have tag "xyz", and if one of those company IDs doesn't exist for our account, I would except to receive 20x response that 49 were updated and 1 didn't exist.
  2. When receiving a ClientErrorResponseException error I would except the code to not be 0, and for the code/reason info to not be garbled into a string that I have to manually parse. I would also expect different errors to be handled with different exceptions, and not one catch-all exception used with the entire contents forced into the exception message string.

Actual behavior

There are a couple problems here:

  1. Why am I getting a "404" error when a company ID doesn't exist in a batch update? That doesn't make any sense and actually took me an hour of debugging thinking the endpoint URL was wrong before I realized what was going on!!!
  2. If you DO return a 404, why is that not a CompanyNotFoundException? I can catch specific errors and handle them accordingly but instead you use one generic ClientErrorResponseException and put the code as a string (!) into the exception message. This makes exception handling nearly impossible and it forces me to custom-parse your error string.

Steps to reproduce

$intercom = IntercomBasicAuthClient::factory([
    'app_id' => '123456abcdef',
    'api_key' => '123456'
]);
$intercom->tagCompanies([
    "name" => 'xyz',
    "companies" => [
        [ "company_id" => "goodId123" ],
        [ "company_id" => "badId123" ]
    ]
]);

This fails to update "goodId123", throws a ClientErrorResponseException with the payload:

Client error response
[status code] 404
[reason phrase] Not Found

Logs

Not needed

Intercom version 2.0.0 is importing namespaced function (php 5.6 functionality)

Version info

  • intercom-php version: 2.0.0
  • PHP version: 5.5

Expected behavior

Creating object client

Actual behavior

crashing with error complaining about unexpected 'function' in IntercomClient.php line 7

Steps to reproduce (as granular as possible, including screenshots where appropriate)

  1. create IntercomClient object
  2. run code using php version 5.5

Note:

it would be nice, if new release 2.0.1 would be made, which does not expect php 5.6+ functionality

Upgrade to Guzzle 4.x or 5.x

Just what the title says :)

Guzzle is already at version 5.1.0, with 3.9 (the version currently used in Intercom) having been released almost a year ago, which makes it hard for people to keep up.

We use Guzzle 4.0 for our application and were able to install Intercom's package when it still required 4.0 but suddenly you downgraded it to 3.8 and now we're stuck, without being able to upgrade Intercom :(

Error when creating an event on a test app

Hello,

The following exception raises everytime I try to create an event in my test app:
Client error response [status code] 404 [reason phrase] Not Found [url] https://api.intercom.io/events

I'm currently using the test app app_id and api_key. The create event function works correctly in my production app.

Thanks

Error handling in the documentation

I miss the error handling for the library in the documentation, for example, what happens if I try to get a User that doesn't exist? Do you return an Exception? Null? Nothing?

I will just check your code to know how It works, but I think It would be nice to have a better documentation so It would be easier to deploy this to Production. I tried also in your API especification page (http://doc.intercom.io/api/#view-a-user) but I didn't find any information about it.

From my point of view this error handling documentation is as important as how to get/edit/delete resources, because otherwise we are blind regarding error handling, and problems could arise.

Thank you very much.

[Feature] IDE autocompletion

It would be a nice feature to allow IDE autocompletion by adding a dockblock at the top of IntercomBasicAuthClient or IntercomAbstractClient.

Example:

/**
  * @method Returned_Class methodName(TypeHint $typehint, TypeHint2 $typehint2) And a comment to describe what the method does
  */
class IntercomBasicAuthClient {}

This will also allow users to know what requests are supported and what not. See #86

Bulk requests

It would be great to allow for bulk requests to the API through this client. The reason I say this, is being in NZ/AU, it's quite demanding of a user to wait 2-3 seconds while all I do is the following:

Update user
Tag User
Record Event

Problem during creating events

Hi,
I am trying to integrate intercom with our symfony app and I am using following code:
public function addPackageCheckOutEvent($user, $package) {
$intercomUser = 'XXXXXX';
$metadata = array(
"checout_date" => $package->getCheckedOut()->getTimestamp(),
"tracking_code" => $package->getTrackingCode()
);
$this->intercomHandler->createEvent(array(
"event_name" => "checkout-package",
"created_at" => $package->getCheckedOut()->getTimestamp(),
"id" => $intercomUser['id'],
"metadata" => $metadata
));
}
When this method executes, server is responding in below manner :
{
"code": 500,
"message": "Client error response\n[status code] 400\n[reason phrase] Bad Request\n[url] https://api.intercom.io/events"
}

Any idea what is going wrong ?

createEvent error

Hi, first time I'm using intercom-php client.

I get this error all the time:

failed: Client error response
[status code] 404
[reason phrase] Not Found
[url] https://api.intercom.io/events

This code is working

        try {
            $this->intercom->updateUser(
                [
                    'email' => $event->getUserEmail(),
                    'last_request_at' => time(),
                    'custom_attributes' => $event->getUserProperty()
                ]
            );

        } catch (ServerErrorResponseException $e) {

        } catch (ClientErrorResponseException $e) {

        }

This code is not:

        try {
            $this->intercom->createEvent(
                array(
                    "event_name" => $event->getEventName(),
                    "email" => $event->getUserEmail(),
                    "created_at" => time(),
                )
            );
        } catch (ServerErrorResponseException $e) {

        } catch (ClientErrorResponseException $e) {

        }

I have tried with the examples of the documentation as well but I still get the same error ...

Any idea what would be is happening?

Thanks!

Unauthorized error when creating messages

Hi, I'm sending a message from a user by using the example from the docs in the readme but I'm getting unauthorized exceptions the entire time.

Client error response [status code] 401 [reason phrase] Unauthorized [url] https://api.intercom.io/messages

I'm using the exact same example as the one from the docs. Both appid and appkey are set correctly. Any idea what might be wrong with the library?

Function handleResponse returns an Object... Should it return an Array?

Function nextPage expecting: an Array

In the docs on the intercom-php page (https://github.com/intercom/intercom-php) there is this example of how to get the next page:

You can grab the next page of results using the client:
$client->nextPage($response["pages"]);

That shows $response being an Array. And the nextPage function in IntercomClient.php expects $pages to be an Array:

public function nextPage($pages)
{
    $response = $this->http_client->request('GET', $pages['next'], [

Function handleResponse returns: an Object

But the handleResponse function in IntercomClient.php returns an object not n array:

private function handleResponse(Response $response){
    $stream = stream_for($response->getBody());
    //$data = json_decode($stream->getContents());           // <-- Object
    $data = json_decode( $stream->getContents(), TRUE );  // <-- Array
   return $data;
}

Problem this causes

Here's some sample code showing the problem:

$client = new IntercomClient( '<appID>', '<apiKey>');
$conversations = new IntercomConversations( $client );
$result = $conversations->getConversations( array() );

while( $result->{"pages"}{"next"} )
{ 
    $result = $client->nextPage( $result->{"pages"} );  // <-- Fails... awkward!
}

Have I just missed the point somewhere??

My hack

*I'm not saying this is the RIGHT way to make this better, or that you should do this. I'm just including it to illustrate the problem a bit more.

Locally, I updated handleResponse in IntercomClient.php to return an array (as shown above), and that made my while loop like this, which works now:

while( $result["pages"]["next"] )
{ 
    $result = $client->nextPage( $result["pages"] );
}

Bug: Wrong exception on server overloading

As per your codes/documentation

namespace Intercom\Exception;

/**
 * Exception when a server error is encountered (5xx codes)
 */
class ServerErrorResponseException extends IntercomException
{
}

Wrong exception is throwing when your server is overloading. Status code: 503 and should be handled by above exception.

Uncaught PHP Exception Intercom\Exception\IntercomException: "Unsuccessful response [status code] 503 [reason phrase] Service Unavailable: Back-end server is at capacity [url] https://api.intercom.io/events" at /mypath/intercom/intercom-php/src/Intercom/Exception/IntercomException.php line 47 {"exception":"[object] (Intercom\\Exception\\IntercomException(code: 0): Unsuccessful response\n[status code] 503\n[reason phrase] Service Unavailable: Back-end server is at capacity\n[url] https://api.intercom.io/events at /mypath/intercom/intercom-php/src/Intercom/Exception/IntercomException.php:47)"} []

syntax error, unexpected 'function' on /IntercomClient.php on line 7

I am new to intercom. I installed it using composer, but I have also tried just including all dependencies myself.

Either way, when I run the following:

$client = new IntercomClient('######','#########');

I get the following error:

Parse error: syntax error, unexpected 'function' (T_FUNCTION), expecting identifier (T_STRING) or \ (T_NS_SEPARATOR) in /vendor/intercom/intercom-php/src/IntercomClient.php on line 7

Line 7:

use function GuzzleHttp\Psr7\stream_for;

PSR7 is installed and so are all other dependencies.

Any ideas?

getUsers with Id

Version info

  • intercom-php version: 3.0
  • PHP version: 7.0

Expected behavior

I try to get the complete user from a hook.

$conversation = $intercomClient->conversations->getConversation($request->get('data')['item']['id']);
dump($conversation);
$user = $intercomClient->users->getUsers(['id' => $conversation->user->id]);
dump($user);

$user should contain only one user

Actual behavior

Even if my userId is good (https://app.intercom.io/a/apps/{myappid}/users/{myUserId}/all-conversations exist) $user contains a user.list with all my users. Not only the one I'm looking for

Logs

capture du 2016-09-22 13-19-37

Second instance is not creating after calling intercom instance

Hi

I installed intercom PHP from https://github.com/intercom/intercom-php .
When I created second instance after created first intercom instance, second instance is not working.
Second instance is for other class.
For example:

require "./vendor/autoload.php";

  1. $client = new IntercomClient();
    $client->users->create([
    "email" => "[email protected]"
    ]);

  2. $usersMdl = new App_Models_Users();

Second instance is not working. When IntercomClient(); instance is not there. Second instance ie working fine

Version info

  • intercom-php version: latest
  • PHP version: 7.0.8

Expected behavior

The instance which is created after intercom client will work as like other instances

Actual behavior

The instance which is created after intercom client is not working

Steps to reproduce (as granular as possible, including screenshots where appropriate)

  1. create intercom instance
  2. create another instance after intercom instance

Logs

instance is not found

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.