def notify_view_content(product_id, url, remote_address, user_agent): user_data = UserData( # It is recommended to send Client IP and User Agent for Conversions API Events. client_ip_address=remote_address, client_user_agent=user_agent # fbc='fb.1.1554763741205.AbCdEfGhIjKlMnOpQrStUvWxYz1234567890', # fbp='fb.1.1558571054389.1098115397', ) content = Content( product_id=product_id, ) custom_data = CustomData( contents=[content], ) event = Event( event_name='ViewContent', event_time=int(time.time()), user_data=user_data, custom_data=custom_data, event_source_url=url, action_source=ActionSource.WEBSITE, ) event_request = EventRequest( events=[event], pixel_id=FACEBOOK_PIXEL_ID, ) event_response = event_request.execute()
def notify_initiate_checkout(basket_id, user_id, url, remote_address, user_agent): basket = Basket.objects.get(id=basket_id) user_phone = None user_email = None if user_id: user = ShopUser.objects.get(id=user_id) user_phone = user.phone user_email = user.email user_data = UserData( email=user_email, phone=user_phone, # It is recommended to send Client IP and User Agent for Conversions API Events. client_ip_address=remote_address, client_user_agent=user_agent # fbc='fb.1.1554763741205.AbCdEfGhIjKlMnOpQrStUvWxYz1234567890', # fbp='fb.1.1558571054389.1098115397', ) contents = [] for item in basket.items.all(): contents.append(Content( product_id=item.product.id, title=item.product.title, brand=item.product.manufacturer.name, item_price=str(item.price.quantize(Decimal('1'), rounding=ROUND_HALF_EVEN)), quantity=item.quantity )) custom_data = CustomData( contents=contents, content_type='product', currency='rub', value=float(basket.total) ) event = Event( event_name='InitiateCheckout', event_time=int(time.time()), user_data=user_data, custom_data=custom_data, event_source_url=url, action_source=ActionSource.WEBSITE, ) event_request = EventRequest( events=[event], pixel_id=FACEBOOK_PIXEL_ID, ) event_response = event_request.execute() log.error(event_response)
def test_http_client(self): mock_http_client = Mock(HttpServiceInterface) event = Event(event_name='Purchase', event_time=int(time.time())) expected_event = json.dumps( {'event_name': event.event_name, 'event_time': event.event_time} ) access_token = 'access-token-0' pixel_id = 'pixel123' appsecret = 'app-secret-234' appsecret_proof = Util.appsecret_proof(appsecret, access_token) expected_params = { 'data': [expected_event], 'test_event_code': 'test-code-1', 'namespace_id': '222', 'upload_id': '333', 'upload_tag': 'upload-tag4', 'upload_source': 'upload-source5', 'access_token': access_token, 'appsecret_proof': appsecret_proof, } event_request = EventRequest( pixel_id=pixel_id, events=[event], test_event_code=expected_params['test_event_code'], namespace_id=expected_params['namespace_id'], upload_id=expected_params['upload_id'], upload_tag=expected_params['upload_tag'], upload_source=expected_params['upload_source'], http_client=mock_http_client, access_token=access_token, appsecret=appsecret ) expected_event_response = EventResponse( events_received=2, fbtrace_id='traceid1', messages=['1', '2'] ) mock_http_client.execute.return_value = expected_event_response expected_headers = FacebookAdsApi.HTTP_DEFAULT_HEADERS expected_url = '%s/%s/%s/events' % (FacebookSession.GRAPH, FacebookAdsApi.API_VERSION, pixel_id) expected_request_options = RequestOptions( ca_bundle_path=Util.ca_bundle_path(), ) actual_event_response = event_request.execute() mock_http_client.execute.assert_called_with( url=expected_url, method=HttpMethod.POST, request_options=expected_request_options, headers=expected_headers, params=expected_params, ) self.assertEqual(actual_event_response, expected_event_response)
def push_conversions_api_events(self, events, test_event_code=None): """ Pushes a list of Events to the Facebook Conversions API. :param events: A list of Facebook Events to push to the conversions API :type events: list of Event :param test_event_code: A test_event_code from Facebook Events Manager to mark these as test events :type test_event_code: str Returns: A dictionary with the parsed response from the Facebook API rtype: dict[str, str] """ if len(events) > 1000: logging.error("The maximum number of events that Facebook accepts in a single API call is 1,000. " "Please use the split_events_to_batches() function to split the events into batches") raise ValueError event_request = EventRequest( events=events, pixel_id=self.pixel_id, ) # Add the test_event_code if one is given if test_event_code: event_request.test_event_code = test_event_code api_response = {} try: event_response = event_request.execute() logging.info('%s events pushed to Facebook Conversions API', event_response.events_received) api_response['status'] = 'API Success' api_response['fb_trace_id'] = event_response.fbtrace_id api_response['messages'] = '\n'.join(event_response.messages) api_response['total_events'] = event_response.events_received except FacebookRequestError as e: logging.error('There was a Facebook Conversions API error:\n\t%s', e) api_response['status'] = 'API Error' api_response['fb_trace_id'] = e.body()['error']['fbtrace_id'] error_message = e.body()['error']['message'] error_message = ': '.join([error_message, e.body()['error']['error_user_msg']]) api_response['messages'] = error_message api_response['total_events'] = None return api_response
def test_constructor(self, pixel_mock): event = Event(event_name='Purchase', event_time=int(time.time())) expected_event = json.dumps( {'event_name': event.event_name, 'event_time': event.event_time} ) pixel_id = 'pixel123' expected_data = { 'data': [expected_event], 'test_event_code': 'test-code-1', 'namespace_id': '222', 'upload_id': '333', 'upload_tag': 'upload-tag4', 'upload_source': 'upload-source5', 'partner_agent': 'partner-agent-6', } event_request = EventRequest( pixel_id=pixel_id, events=[event], test_event_code=expected_data['test_event_code'], namespace_id=expected_data['namespace_id'], upload_id=expected_data['upload_id'], upload_tag=expected_data['upload_tag'], upload_source=expected_data['upload_source'], partner_agent=expected_data['partner_agent'], ) ads_pixel = { 'events_received': 2, 'fbtrace_id': 'traceid1', 'messages': ['1', '2'], } expected_event_response = EventResponse( events_received=2, fbtrace_id='traceid1', messages=['1', '2'] ) pixel_instance_mock = pixel_mock.return_value pixel_instance_mock.create_event.return_value = ads_pixel actual_event_response = event_request.execute() pixel_mock.assert_called_with(pixel_id) pixel_instance_mock.create_event.assert_called_with( fields=[], params=expected_data ) self.assertEqual(actual_event_response, expected_event_response)
def notify_add_to_cart(product_id, url, remote_address, user_agent): product = Product.objects.get(id=product_id) user_data = UserData( # It is recommended to send Client IP and User Agent for Conversions API Events. client_ip_address=remote_address, client_user_agent=user_agent # fbc='fb.1.1554763741205.AbCdEfGhIjKlMnOpQrStUvWxYz1234567890', # fbp='fb.1.1558571054389.1098115397', ) content = Content( product_id=product_id, item_price=str(product.price.quantize(Decimal('1'), rounding=ROUND_HALF_EVEN)) ) custom_data = CustomData( contents=[content], content_type='product', currency='rub' ) event = Event( event_name='AddToCart', event_time=int(time.time()), user_data=user_data, custom_data=custom_data, event_source_url=url, action_source=ActionSource.WEBSITE, ) event_request = EventRequest( events=[event], pixel_id=FACEBOOK_PIXEL_ID, ) event_response = event_request.execute() log.error(event_response)
content = Content( product_id='product123', quantity=1, delivery_category=DeliveryCategory.HOME_DELIVERY, ) custom_data = CustomData( contents=[content], currency='usd', value=123.45, ) event = Event( event_name='Purchase', event_time=int(time.time()), user_data=user_data, custom_data=custom_data, event_source_url='http://jaspers-market.com/product/123', action_source=ActionSource.WEBSITE, ) events = [event] event_request = EventRequest( events=events, pixel_id=pixel_id, ) event_response = event_request.execute() print(event_response)
def pixel(): access_token = request.headers.get('token') pixel_id = request.headers.get('pixel') page_id = request.headers.get('page_id') FacebookAdsApi.init(access_token=access_token) now = int(time.time()) action_source = ActionSource('chat') payload = request.json if payload['opt_out'].lower().strip() == 'false': opt_out = False else: opt_out = True user_data = payload['user_data'] user_data = { key: None if user_data[key].find('{{') != -1 and user_data[key].find('}}') != -1 else user_data[key] for key, value in user_data.items() } user_data_0 = UserData() for key, value in user_data.items(): setattr(user_data_0, key, value) custom_data = payload['custom_data'] if payload["event_name"] == 'Purchase': try: custom_data['value'] = float(custom_data['value']) except ValueError or TypeError: response = f'{custom_data["value"]} is not allowed as value for {payload["event_name"]} event' entry = dict(message={ 'page_id': page_id, 'log': response }, component='arbitrary-property') print(json.dumps(entry)) return response, 400 if 'predicted_ltv' in custom_data.keys(): custom_data['predicted_ltv'] = float(custom_data['predicted_ltv']) if 'num_items' in custom_data.keys(): custom_data['num_items'] = int(custom_data['num_items']) custom_data_0 = CustomData() for key, value in custom_data.items(): setattr(custom_data_0, key, value) event_0 = Event(event_name=payload['event_name'], event_time=now, opt_out=opt_out, user_data=user_data_0, custom_data=custom_data_0, data_processing_options=[], action_source=action_source) events = [event_0] if payload['test_event_code'] == '': event_request = EventRequest( events=events, pixel_id=pixel_id, ) else: test_event_code = payload['test_event_code'] event_request = EventRequest(events=events, pixel_id=pixel_id, test_event_code=test_event_code) try: event_response = event_request.execute() except (TypeError, AttributeError) as error: error_message = error.args[0] response = {'response': error_message} return response, 400 except FacebookRequestError as error: error_message = error.body()['error']['message'] response = {'response': error_message} return response, 400 else: response = event_response.to_dict() return response finally: entry = dict(message={'page_id': page_id, 'log': response}) print(json.dumps(entry))