Exemple #1
0
def collect(tracking_id, user_id=None, client_id=None, hit_type='pageview', http_session=COLLECT_SESSION, **kw):
    """

    collect('UA-407051-16', '1', hit_type='transaction', ti='test', tr='1.42', cu='USD')

    Page:
        hit_type='pageview'
        dp='/', # Page

    Transactions:
        hit_type='transaction',
        ti='...', # Transaction ID
        tr='...', # Transaction Revenue
        ta='...', # Transaction Affiliation.
        cu='USD', # Currency Code

    Transaction Item:
        hit_type='item',
        ti='12345',   # Transaction ID
        in='sofa',    # Item name. Required.
        ip='300',     # Item price.
        iq='2',       # Item quantity.
        ic='u3eqds4', # Item code / SKU.
        iv='furnitu', # Item variation / category.
        cu='EUR',     # Currency code.

    Events:
        hit_type='event',
        ec='...', # Event Category
        ea='...', # Event Action
        el='...', # Event Label
        ev='...', # Event Value

    Other:
        uip='1.2.3.4', # IP Override

    via https://developers.google.com/analytics/devguides/collection/protocol/v1/devguide
    """
    client_id = client_id or uuid.uuid4().hex
    params = {
        'v': 1, # Protocol version
        'tid': tracking_id, # Tracking ID (UA-XXXXXX-XX)
        'cid': client_id, # Client ID,
        'uid': user_id, # User ID,
        't': hit_type, # Hit Type
        'uip': '0.0.0.0', # IP Override
        'ni': 1, # Non-interactive
    }
    params.update(kw)

    req = requests.Request('POST', COLLECT_URL, data=urlencode(params, doseq=True)).prepare()
    resp = http_session.send(req)
    assert_response(resp)
    return resp
Exemple #2
0
    def send(self, settings=None):
        settings = settings or self.request.registry.settings
        api_key = settings['api.mailgun.key']
        api_url = settings.get(
            'api.mailgun.url',
            'https://api.mailgun.net/v3/mg.briefmetrics.com')
        r = requests.post(
            api_url + '/messages',
            auth=('api', api_key),
            data=self.params,
        )
        assert_response(r)

        return r.json()
Exemple #3
0
    def send(self, settings=None):
        settings = settings or self.request.registry.settings
        params = {
            'key': settings['api.mandrill.key'],
            'async': True,
            'message': self.params,
        }

        headers = {'content-type': 'application/json'}
        r = http_session.post(
            'https://mandrillapp.com/api/1.0/messages/send.json',
            data=json.dumps(params).encode(),
            headers=headers)
        assert_response(r)

        return r.json()
Exemple #4
0
def _namecheap_subscription_alter(request, data):
    nc_api = service_registry['namecheap'].instance

    event_id = data['event']['id']
    return_uri = data['event'].get('returnURI')
    remote_id = data['event']['user']['username']
    order = data['event']['order']

    q = model.Session.query(model.Account).filter_by(service='namecheap', remote_id=remote_id)
    q = q.options(orm.joinedload('user'))

    account = q.first()
    if not account:
        raise httpexceptions.HTTPBadRequest('Invalid remote id.')

    user = account.user
    old_plan = user.plan

    api.account.set_plan(user, order['pricing_plan_sku'], update_subscription=False)
    amount = 0
    if not user.num_remaining:
        amount = user.payment.prorate(old_plan=old_plan, new_plan=user.plan)
    if amount:
        try:
            user.payment.invoice(amount=amount, description='Briefmetrics: %s (Prorated)' % user.plan.option_str)
        except:
            log.error('Namecheap prorate invoice failed, reverting plan to %s: %s' % (old_plan.id, user))
            api.account.set_plan(user, old_plan.id)
            raise

    log.info('namecheap webhook: Altered %s' % user)

    ack = {
        'type': 'subscription_alter_resp',
        'id': event_id,
        'response': {
            'state': 'Active',
            'message': 'Changed plan to %s' % user.plan.option_str,
        }
    }

    if return_uri:
        # Confirm event, activate subscription
        r = nc_api.session.request('PUT', return_uri, json=ack) # Bypass our wrapper
        assert_response(r)

    return ack
Exemple #5
0
def collect(app_id,
            identity=None,
            event=None,
            properties=None,
            http_session=COLLECT_SESSION):
    """

    $ curl \
        -X POST \
        -H "Content-Type: application/json" \
        -d '{
          "app_id": "1675620903",
          "identity": "*****@*****.**",
          "event": "Send Transactional Email",
          "properties": {
            "subject": "Welcome to My App!",
            "variation": "A"
          }
        }' \
        https://heapanalytics.com/api/track

    ref: https://heapanalytics.com/docs/server-side#track
    """
    params = {'app_id': app_id}

    if identity:
        params['identity'] = identity

    if event:
        params['event'] = event

    if properties:
        params['properties'] = properties

    headers = {'Content-type': 'application/json'}
    req = requests.Request('POST',
                           COLLECT_URL,
                           data=json.dumps(params).encode(),
                           headers=headers).prepare()
    resp = http_session.send(req)
    assert_response(resp)
    return resp
Exemple #6
0
def _namecheap_subscription_cancel(request, data):
    nc_api = service_registry['namecheap'].instance

    event_id = data['event']['id']
    return_uri = data['event'].get('returnURI')
    remote_id = data['event']['user']['username']

    q = model.Session.query(model.Account).filter_by(service='namecheap', remote_id=remote_id)
    q = q.options(orm.joinedload('user'))

    account = q.first()
    if not account:
        raise httpexceptions.HTTPBadRequest('Invalid remote id.')

    user = account.user

    amount = 0
    if not user.num_remaining:
        amount = user.payment and user.payment.prorate()
    if amount:
        user.payment.invoice(amount=amount, description='Briefmetrics: Prorated refund')

    api.account.delete_payments(user)
    log.info('namecheap webhook: Cancelled %s' % user)

    ack = {
        'type': 'subscription_cancel_resp',
        'id': event_id,
        'response': {
            'state': 'Inactive',
        }
    }

    if return_uri:
        # Confirm event, activate subscription
        r = nc_api.session.request('PUT', return_uri, json=ack) # Bypass our wrapper
        assert_response(r)

    return ack
Exemple #7
0
    def invoice(self, amount, description):
        amount_dollars = '%0.2f' % round(amount / 100, 2)
        # Make payment
        nc = service_registry['namecheap'].instance

        # Create invoice
        r = nc.request('POST',
                       '/v1/billing/invoice',
                       data={
                           'subscription_id': self.token,
                       })
        assert_response(r)
        data = r.json()
        invoice_id = data['result']['id']

        # Add line item
        item = {
            'description': description,
            'amount': amount_dollars,
            'taxable': 0,
        }
        r = nc.request('POST',
                       '/v1/billing/invoice/{invoice_id}/line_items'.format(
                           invoice_id=invoice_id),
                       json=item)
        assert_response(r)

        # Submit payment
        r = nc.request('POST',
                       '/v1/billing/invoice/{invoice_id}/payments'.format(
                           invoice_id=invoice_id),
                       json={})
        assert_response(r)
        data = r.json()

        log.info("Namecheap invoice ${amount}: {user}; {data}".format(
            user=self.user, amount=amount_dollars, data=data))

        if data['result']['status'] == 'failed':
            raise PaymentError('Failed to invoice')
Exemple #8
0
 def _get(self, url, params=None):
     r = self.api.get(url, params=params)
     assert_response(r)
     return r.json()
Exemple #9
0
 def request(self, method, resource, **kw):
     r = self.session.request(method, self.url_prefix+resource, **kw)
     assert_response(r)
     return r
Exemple #10
0
def _namecheap_subscription_create(request, data):
    nc_api = service_registry['namecheap'].instance

    event_id = data['event']['id']
    return_uri = data['event'].get('returnURI')
    subscription_id = data['event']['subscription_id']

    try:
        email, first_name, last_name, remote_id = get_many(data['event']['user'], ['email', 'first_name', 'last_name', 'username'])
    except KeyError as e:
        k = e.args[0]
        log.warning("namecheap webhook: Failing due to missing field '%s': %s" % (k, event_id))
        return {
            'type': 'subscription_create_resp',
            'id': event_id,
            'response': {
                'state': 'failed',
                'provider_id': '',
                'message': 'missing field: %s' % k,
            }
        }

    display_name = ' '.join([first_name, last_name])
    plan_id = data['event']['order'].get('pricing_plan_sku')

    user = api.account.get_or_create(
        email=email,
        service='namecheap',
        display_name=display_name,
        remote_id=remote_id,
        remote_data=data['event']['user'],
        plan_id=plan_id,
    )

    if user.num_remaining != 10:
        log.warning('Resetting num_remaining from %s: %s' % (user.num_remaining, user))
    user.num_remaining = 10

    ack_message = 'Briefmetrics activation instructions sent to %s' % email
    ack_state = 'Active'

    if user.payment:
        ack_message = 'Failed to provision new Briefmetrics account for {email}. Account already exists with payment information.'.format(email=email)
        ack_state = 'Failed'
        log.info('namecheap webhook: Provision skipped %s' % user)
    else:
        user.set_payment('namecheap', subscription_id)
        if user.payment.auto_charge:
            user.time_next_payment = now() + user.payment.auto_charge
        model.Session.commit()
        log.info('namecheap webhook: Provisioned %s' % user)

    ack = {
        'type': 'subscription_create_resp',
        'id': event_id,
        'response': {
            'state': ack_state,
            'provider_id': user.id,
            'message': ack_message,
        }
    }

    if return_uri:
        # Confirm event, activate subscription
        r = nc_api.session.request('PUT', return_uri, json=ack) # Bypass our wrapper
        assert_response(r)

    if ack_state != 'Active':
        return ack

    subject = u"Welcome to Briefmetrics"
    html = api.email.render(request, 'email/welcome_namecheap.mako')
    message = api.email.create_message(request,
        to_email=email,
        subject=subject,
        html=html,
    )
    api.email.send_message(request, message)
    return ack