示例#1
0
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 test_validate_value(self):
        bad_value = 'bad-value'

        with self.assertRaises(TypeError) as context:
            CustomData(value=bad_value, )

        expected_exception_message = 'CustomData.value must be a float or int. TypeError on value: ' + bad_value
        self.assertTrue(expected_exception_message in str(context.exception))
    def test_validate_predicted_ltv(self):
        bad_predicted_ltv = 'bad-predicted_ltv'

        with self.assertRaises(TypeError) as context:
            CustomData(predicted_ltv=bad_predicted_ltv, )

        expected_exception_message = 'CustomData.predicted_ltv must be a float or int. TypeError on predicted_ltv: ' + bad_predicted_ltv
        self.assertTrue(expected_exception_message in str(context.exception))
示例#4
0
    def test_normalize(self):
        content = Content(product_id='id0', quantity='quantity1', item_price=3.99)
        custom_properties = {'custom1': 'property1', 'custom2': 'property2'}
        expected = {
            'value': 0.5,
            'currency': 'usd',
            'content_name': 'content-content1',
            'content_category': 'content-category2',
            'content_ids': ['id1', 'id2'],
            'content_type': 'content-type3',
            'contents': [
                {
                    'id': content.product_id,
                    'quantity': content.quantity,
                    'item_price': content.item_price,
                }
            ],
            'order_id': 'order-id4',
            'predicted_ltv': 5.99,
            'num_items': 6,
            'status': 'status7',
            'search_string': 'search-string8',
            'item_number': 'item-number9',
            'custom1': 'property1',
            'custom2': 'property2',
        }
        custom_data = CustomData(
            value=expected['value'],
            currency=expected['currency'],
            content_name=expected['content_name'],
            content_category=expected['content_category'],
            content_ids=expected['content_ids'],
            contents=[content],
            content_type=expected['content_type'],
            order_id=expected['order_id'],
            predicted_ltv=expected['predicted_ltv'],
            num_items=expected['num_items'],
            status=expected['status'],
            search_string=expected['search_string'],
            item_number=expected['item_number'],
            custom_properties=custom_properties,
        )

        self.assertEqual(custom_data.normalize(), expected)
    def test_delivery_category_validate(self):
        delivery_category = 'undefined_delivery_category'

        with self.assertRaises(TypeError) as context:
            CustomData(
                value=123.12,
                delivery_category=delivery_category,
            )

        expected_exception_message = 'delivery_category must be of type DeliveryCategory. Passed invalid category: ' + delivery_category
        self.assertTrue(expected_exception_message in str(context.exception))
示例#6
0
    def test_constructor(self):
        event_name = 'event_name-0'
        event_time = 123
        event_source_url = 'event_source_url-2'
        opt_out = False
        event_id = 'event_id-3'
        user_data = UserData(email='*****@*****.**')
        custom_data = CustomData(order_id=123)
        data_processing_options = ['4' '5']
        data_processing_options_country = 6
        data_processing_options_state = 7
        action_source = ActionSource.APP
        event = Event(
            event_name=event_name,
            event_time=event_time,
            event_source_url=event_source_url,
            opt_out=opt_out,
            event_id=event_id,
            user_data=user_data,
            custom_data=custom_data,
            data_processing_options=data_processing_options,
            data_processing_options_country=data_processing_options_country,
            data_processing_options_state=data_processing_options_state,
            action_source=action_source,
        )
        expected_params = {
            'event_name': event_name,
            'event_time': event_time,
            'event_source_url': event_source_url,
            'opt_out': opt_out,
            'event_id': event_id,
            'user_data': user_data.normalize(),
            'custom_data': custom_data.normalize(),
            'data_processing_options': data_processing_options,
            'data_processing_options_country': data_processing_options_country,
            'data_processing_options_state': data_processing_options_state,
            'action_source': action_source.value,
        }

        self.assertEqual(event.normalize(), expected_params)
示例#7
0
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)
示例#8
0
def build_predicted_revenue_events(df, event_name):
    """
    Creates a list of Facebook Event objects which can be pushed to the Facebook Conversions API.
    Also creates DataFrame for logging which can be used to stream insert to a BigQuery log table.

    :param df: A DataFrame with the events to build Facebook events for
    :type df: pd.DataFrame

    Returns: A tuple with a list of Facebook events and a DataFrame for logs
    rtype: (list of Event, pd.DataFrame)
    """
    events = []
    logs = []
    for index, row in df.iterrows():
        date = int(time.mktime(datetime.strptime(row['date'], '%Y%m%d').timetuple()))
        user_data = UserData(
            country_code=row['shop'],
            fbp=row['facebook_browser_id']
        )

        custom_data = CustomData(
            currency=row['currency'],
            value=row['predicted_revenue']
        )

        event = Event(
            event_name=event_name,
            event_time=date,
            user_data=user_data,
            custom_data=custom_data,
            data_processing_options=[]
        )
        events.append(event)

        logs.append(
            {
                "facebook_browser_id": row['facebook_browser_id'],
                "shop": row['shop'],
                "date_source": row['date'],
                "date_processed": datetime.today().strftime('%Y-%m-%d-%H:%M:%S'),
                "predicted_revenue": row['predicted_revenue'],
                "currency": row['currency']
            }
        )
    df_logs = pd.DataFrame(logs)
    return events, df_logs
示例#9
0
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)
示例#10
0
    # It is recommended to send Client IP and User Agent for Conversions API Events.
    client_ip_address=request.META.get('REMOTE_ADDR'),
    client_user_agent=request.headers['User-Agent'],
    fbc='fb.1.1554763741205.AbCdEfGhIjKlMnOpQrStUvWxYz1234567890',
    fbp='fb.1.1558571054389.1098115397',
)

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(
示例#11
0
access_token = '<ACCESS_TOKEN>'
pixel_id = 'ADS_PIXEL_ID>'

FacebookAdsApi.init(access_token=access_token)

user_data = UserData(
    email='*****@*****.**',
    # It is recommended to send Client IP and User Agent for Conversions API Events.
    client_ip_address=request.META.get('REMOTE_ADDR'),
    client_user_agent=request.headers['User-Agent'],
    fbc='fb.1.1554763741205.AbCdEfGhIjKlMnOpQrStUvWxYz1234567890',
    fbp='fb.1.1558571054389.1098115397',
)

custom_data = CustomData(
    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,
    def test_emptyobject_normalize(self):
        custom_data = CustomData()

        self.assertEqual(custom_data.normalize(), {})
 def test_normalize_int_and_float_predicted_ltvs_work(self):
     self.assertEqual(
         CustomData(predicted_ltv=123).normalize(), {'predicted_ltv': 123})
     self.assertEqual(
         CustomData(predicted_ltv=123.45).normalize(),
         {'predicted_ltv': 123.45})
 def test_normalize_int_and_float_values_work(self):
     self.assertEqual(CustomData(value=123).normalize(), {'value': 123})
     self.assertEqual(
         CustomData(value=123.45).normalize(), {'value': 123.45})
示例#15
0
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))
pixel_id = None

if access_token is None or pixel_id is None:
    raise Exception(
        "You must set your access token and pixel id before executing")

FacebookAdsApi.init(access_token=access_token)

user_data = UserData(email="*****@*****.**",
                     phone="16505551212",
                     country_code="us",
                     gender=Gender.FEMALE)

content = Content(product_id="XYZ789", quantity=4, item_price=3.5)
contents = [content]
custom_data = CustomData(contents=contents, value=14.0, currency="usd")

event = Event(
    event_name="Purchase",
    event_time=int(time.time()),
    user_data=user_data,
    custom_data=custom_data,
)

events = [event]

event_request = EventRequest(events=events, pixel_id=pixel_id)

event_response = event_request.execute()
print(event_response)