APIs & Integrations

ritasousa
Participant

Issues with creating an engagement on Hubspot

We have been trying to create engagements with data linked the contact in hubspot back to the customer feedback data the user has entered on to our customer feedback portal. The feedback from the end user is that these engagements are not visible on to them, even thought the API responds with success status codes.

To do this we are searching for the contact in Hubspot system and using the contacts ‘canonical-vid’ to connect it to the newly created attachment.

A sample version of our code is here:

#!/usr/bin/env python
#from  event import Events
import requests
import json
import time
import datetime

class Events:
    response_end = datetime.datetime.now()
    event_id = 1234567

CANDIDATE_EMAIL="a@example.com"
SUNDIAL_APIKEY="***-***-***"

class HubSpotAPIError(RuntimeError):pass

class HubSpotConnector(object):

    def __init__(self,apikey,oauth , **kwargs ):
        self.owner = kwargs.get('owner',None)
        self.apikey = apikey
        self.host = kwargs.get('host',"https://api.hubapi.com")

    def _do_hs_query(self,net_method,url,data = None):
        query =  self.host + url +"?hapikey="+self.apikey

        kwargs = {}
        if data is not None:
            kwargs['json'] =data

        response = net_method(query, **kwargs)
        print query, response.reason
        return response

    def get_contact_json_by_email(self,email):
        """Returns a JSONPODobject representing the hubspot contact"""

        base_url = "/contacts/v1/contact/email/%s/profile" % email
        response = self._do_hs_query(requests.get,base_url)
        doc = response.json()
        try:
            if doc['status'] == 'error':
                raise HubSpotAPIError(doc['message'])
        except KeyError:pass
        return doc


    def add_engagement(self,contact, txt):
        base_url = "/engagements/v1/engagements"

        engagement_doc = {
            "engagement": {
                  "active": True,
                  "type": "NOTE",
                  "timestamp": int(time.mktime(time.gmtime()))
              },
              "associations": {
                  "contactIds": [ contact['canonical-vid'] ],
                  "companyIds": [ ],
                  "dealIds": [ ],
                  "ownerIds": [ ]
              },
              "metadata": {
                  "body": txt
              }
        }
        if self.owner:
            engagement_doc['engagement']['ownerId'] = self.owner

        resp =self._do_hs_query(requests.post,base_url,  data = engagement_doc)
        if resp.status_code != 200:
            raise HubSpotAPIError(resp.reason)

        return resp

def  main():
    hs = HubSpotConnector(SUNDIAL_APIKEY,None)
    contact = hs.get_contact_json_by_email(CANDIDATE_EMAIL)
    #If not found raises and exceptionand exits

#    e = Events(None,event_id)
    e = Events()
    note =  """
            GuestRate feedback submitted %(response_end)s

            Link: https://bdrconline.com/cgi-bin/guestrate/report.py?e=%(event_id)i
    """%{
        'event_id':e.event_id,
        'response_end':e.response_end,
    }
    r = hs.add_engagement(contact,note)
    print r.status_code,r.reason
    print repr(r.text)

if __name__ == "__main__":
    main()

When run we see following output.

https://api.hubapi.com/contacts/v1/contact/email/a@example.om/profile?hapikey=***-***-*** OK
https://api.hubapi.com/engagements/v1/engagements?hapikey=***-***-*** OK
200 OK
u'{"engagement":{"id":1020811462,"portalId":3274272,"active":true,"createdAt":1528971012677,"lastUpdated":1528971012677,"type":"NOTE","timestamp":1528971012},"associations":{"contactIds":[456851],"companyIds":[],"dealIds":[],"ownerIds":[],"workflowIds":[],"ticketIds":[],"contentIds":[]},"metadata":{"body":"\\n            GuestRate feedback submitted 2018-06-14 10:10:11.879795\\n\\n            Link: https://bdrconline.com/cgi-bin/guestrate/report.py?e=1234567\\n    "}}'

Additionally using real data we captured the following HTTP transaction indicating success. Unfortunately the capture was done via a utf8 terminal an the GZIP data is scrambled. (Green sent; Red received)

POST /engagements/v1/engagements?hapikey=***-***-*** HTTP/1.1
Host: api.hubapi.com
Content-Length: 540
Accept-Encoding: gzip, deflate
Accept: */*
User-Agent: python-requests/2.4.3 CPython/2.7.9 Linux/3.16.0-4-amd64
Connection: keep-alive
Content-Type: application/json

{"associations": {"contactIds": [456851], "ownerIds": [], "companyIds": [], "dealIds": []}, "engagement": {"active": true, "timestamp": 1528969555, "type": "NOTE"}, "metadata": {"body": "\n                    GuestRate feedback submitted 2018-06-13 07:58:43\n                    Wedding stay at Woodside checking out 2018-06-09\n\n                    Likelihood to recommend: 10, Overall value for money: 10, Overall Satisfaction:10.\n                    Link: https://bdrconline.com/cgi-bin/guestrate/report.py?e=2761942\n\n            "}}



HTTP/1.1 200 OK
Date: Thu, 14 Jun 2018 09:51:23 GMT
Content-Type: application/json;charset=utf-8
Transfer-Encoding: chunked
Connection: keep-alive
Set-Cookie: __cfduid=d458e1bf1702492918b3c5dd16e2010221528969883; expires=Fri, 14-Jun-19 09:51:23 GMT; path=/; domain=.hubapi.com; HttpOnly
Access-Control-Allow-Credentials: false
Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Accept-Charset, Accept-Encoding, X-Override-Internal-Permissions, X-Properties-Source, X-Properties-SourceId, X-Properties-Flag, X-Hubspot-User-Id, X-Hubspot-Trace, X-Hubspot-Callee, X-Hubspot-Offset, X-Hubspot-No-Trace, X-HubSpot-Request-Source, X-HubSpot-Request-Reason, Subscription-Billing-Auth-Token, X-App-CSRF, X-Tools-CSRF, Online-Payment-Signing-UUID, X-Source, X-SourceId
Access-Control-Allow-Methods: GET, OPTIONS, PUT, POST, DELETE, PATCH, HEAD
X-Trace: 2BB47561F6D920DAA37E6F3C68C2F44F6182244210000000000000000000
Expect-CT: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
Server: cloudflare
CF-RAY: 42abe5c7ff826a9d-LHR
Content-Encoding: gzip

198
6RËŠí³›@í³Œí²•í²¡í³c[Ë–Bí³ˆ!í²„í²
í²í²
<í³˜Cví²¬í²™í²¶<Hí²š3-í³žßƒHbHí³¢ô-ºší²ª~í²œí²
[í²˜Wí³°Lí²žy^í²•í²»mí²©aí³€(í³˜?80eí²±í³Ÿí³»BZí³±g#q"
]8vÇž/í²·í²„xÛ‘í³œí³ b@í³¡7í²ŸjHÐ¡í³ í³¢Þ°í²›í³í³€sPwí³¢í³ƒDI>í²£í²:í²¹mí²§í³’í³”
^í²„í²œ*í²²í²Œ^eí²»U^í²ªloí²ªí³šlí³‹í³»Oí³€í²œí²¬Jí²‚í²³BQOí³Œ.yGÊží³ˆv
Ã“í³œí³€í²²í³ƒsí²ží²¯í³³í³‘wí³”í³»í²³Sí³‚
í²’í³¥aí² í³ í²Œí³Š3í²-í³í²±í³¯í³•í³»í²‰Ô‘í²£8í³í³Œ'í³¹Å§í³£rj&í³í³– í²Q'í²‘1í²™ÍŠqí³‘rí³š}í² í²µí³¥ac[í²¿j|ØŽí³‹j"
m"-í³¯í²Ží³§í²·í³Ží²Ší³˜í³¯í³²Ã¶í³ž{í²ž^í³¿M`Õí²“
0

0 Upvotes
3 Replies 3
Derek_Gervais
HubSpot Alumni
HubSpot Alumni

Issues with creating an engagement on Hubspot

Hi @tomframp,

So to start, when I navigate to the contact record in question (vid: 456851) I'm able to see the engagement you're referring to (id: 1020811462). You can confirm this by navigating to that contact here: https://app.hubspot.com/contacts/3274272/contact/456851/?interaction=note

Is it possible that the user didn't have 'Notes' included in their timeline filters?

0 Upvotes
Derek_Gervais
HubSpot Alumni
HubSpot Alumni

Issues with creating an engagement on Hubspot

Hi @tomframp,

Can you send me your Hub ID so that I can take a look at the object(s) in question?

0 Upvotes
ritasousa
Participant

Issues with creating an engagement on Hubspot

Thanks Derek,

My Hub ID is 3274272

0 Upvotes