Skip to content

Commit

Permalink
finished web hook tests.
Browse files Browse the repository at this point in the history
  • Loading branch information
jacoor committed Jun 8, 2017
1 parent 49e7d23 commit b488b7d
Show file tree
Hide file tree
Showing 3 changed files with 120 additions and 98 deletions.
2 changes: 1 addition & 1 deletion aa_stripe/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ class WebhookAPI(CreateAPIView):

def post(self, request, *args, **kwargs):
payload = request.body.decode("utf-8")
sig_header = request.META['HTTP_STRIPE_SIGNATURE']
sig_header = request.META.get("HTTP_STRIPE_SIGNATURE")
event = None

try:
Expand Down
1 change: 0 additions & 1 deletion aa_stripe/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,6 @@ def charge(self):
self.save()
raise

print (type(stripe_charge))
self.stripe_charge_id = stripe_charge["id"]
self.stripe_response = stripe_charge
self.is_charged = True
Expand Down
215 changes: 119 additions & 96 deletions tests/test_webhooks.py
Original file line number Diff line number Diff line change
@@ -1,103 +1,126 @@
"""Test charging users through the StripeCharge model"""
import requests_mock
import simplejson as json
from aa_stripe.models import StripeCustomer, StripeSubscription, StripeSubscriptionPlan
from django.contrib.auth import get_user_model
from django.test import TestCase
import time

UserModel = get_user_model()
import simplejson as json
from aa_stripe.models import StripeWebhook
from django.conf import settings
from rest_framework.reverse import reverse
from rest_framework.test import APITestCase
from stripe.webhook import WebhookSignature


class TestSubscriptions(TestCase):
def setUp(self):
self.user = UserModel.objects.create(email="foo@bar.bar", username="foo", password="dump-password")
self.customer = StripeCustomer.objects.create(
user=self.user, stripe_customer_id="example", stripe_js_response="foo")
self.plan = StripeSubscriptionPlan.objects.create(
amount=100,
is_created_at_stripe=True,
name="example plan",
interval=StripeSubscriptionPlan.INTERVAL_MONTH,
interval_count=3,
)
class TestWebhook(APITestCase):

def test_subscription_creation(self):
self.assertEqual(0, 1) # add webhooks
self.assertEqual(StripeSubscription.objects.count(), 0)
subscription = StripeSubscription.objects.create(
customer=self.customer,
user=self.user,
plan=self.plan,
metadata={"name": "test subscription"},
)
self.assertFalse(subscription.is_created_at_stripe)
with requests_mock.Mocker() as m:
m.register_uri("POST", "https://api.stripe.com/v1/subscriptions", [{"text": json.dumps({
"id": "sub_AnksTMRdnWfq9m",
"object": "subscription",
"application_fee_percent": None,
"cancel_at_period_end": False,
"canceled_at": None,
"created": 1496861935,
"current_period_end": 1499453935,
"current_period_start": 1496861935,
"customer": "cus_AnksoMvJIinvZm",
"discount": None,
"ended_at": None,
"items": {
"object": "list",
"data": [{
"id": "si_1AS9Mp2eZvKYlo2Cmmf01eoi",
"object": "subscription_item",
"created": 1496861935,
"plan": {
"id": self.plan.id,
"object": "plan",
"amount": 100,
"created": 1496857185,
"currency": "usd",
"interval": "month",
"interval_count": 3,
"livemode": False,
"metadata": {},
"name": "example plan",
"statement_descriptor": None,
"trial_period_days": None
},
"quantity": 1
}],
"has_more": False,
"total_count": 1,
"url": "/v1/subscription_items?subscription=sub_AnksTMRdnWfq9m"
},
"livemode": False,
"metadata": {"name": "test subscription"},
"plan": {
"id": self.plan.id,
"object": "plan",
"amount": 100,
"created": 1496857185,
"currency": "usd",
"interval": "month",
"interval_count": 3,
"livemode": False,
"metadata": {},
"name": "example plan",
"statement_descriptor": None,
"trial_period_days": None
self.assertEqual(StripeWebhook.objects.count(), 0)
payload = json.loads("""{
"created": 1326853478,
"livemode": false,
"id": "evt_00000000000000",
"type": "charge.failed",
"object": "event",
"request": null,
"pending_webhooks": 1,
"api_version": "2017-06-05",
"data": {
"object": {
"id": "ch_00000000000000",
"object": "charge",
"amount": 100,
"amount_refunded": 0,
"application": null,
"application_fee": null,
"balance_transaction": "txn_00000000000000",
"captured": false,
"created": 1496953100,
"currency": "usd",
"customer": null,
"description": "My First Test Charge (created for API docs)",
"destination": null,
"dispute": null,
"failure_code": null,
"failure_message": null,
"fraud_details": {
},
"invoice": null,
"livemode": false,
"metadata": {
},
"on_behalf_of": null,
"order": null,
"outcome": null,
"paid": false,
"receipt_email": null,
"receipt_number": null,
"refunded": false,
"refunds": {
"object": "list",
"data": [
],
"has_more": false,
"total_count": 0,
"url": "/v1/charges/ch_1ASX5ELoWm2f6pRwC6ZyewYR/refunds"
},
"review": null,
"shipping": null,
"source": {
"id": "card_00000000000000",
"object": "card",
"address_city": null,
"address_country": null,
"address_line1": null,
"address_line1_check": null,
"address_line2": null,
"address_state": null,
"address_zip": null,
"address_zip_check": null,
"brand": "Visa",
"country": "US",
"customer": null,
"cvc_check": null,
"dynamic_last4": null,
"exp_month": 8,
"exp_year": 2018,
"fingerprint": "DsGmBIQwiNOvChPk",
"funding": "credit",
"last4": "4242",
"metadata": {
},
"quantity": 1,
"start": 1496861935,
"status": "active",
"tax_percent": None,
"trial_end": None,
"trial_start": None
})}])
"name": null,
"tokenization_method": null
},
"source_transfer": null,
"statement_descriptor": null,
"status": "succeeded",
"transfer_group": null
}
}
}""")

url = reverse("stripe-webhooks")
response = self.client.post(url, data=payload, format="json")
self.assertEqual(response.status_code, 400) # not signed

headers = {
"HTTP_STRIPE_SIGNATURE": "wrong", # todo: generate signature
}
self.client.credentials(**headers)
response = self.client.post(url, data=payload, format="json")
self.assertEqual(response.status_code, 400) # wrong signature

subscription.create_at_stripe()
self.assertTrue(subscription.is_created_at_stripe)
self.assertEqual(subscription.stripe_response["id"], "sub_AnksTMRdnWfq9m")
self.assertEqual(subscription.stripe_subscription_id, "sub_AnksTMRdnWfq9m")
self.assertEqual(subscription.stripe_response["plan"]["name"], self.plan.name)
self.assertEqual(subscription.stripe_response["plan"]["amount"], self.plan.amount)
self.assertEqual(subscription.status, subscription.STATUS_ACTIVE)
timestamp = int(time.time())
raw_payload = json.dumps(payload).replace(": ", ":")
raw_payload = raw_payload.replace(", ", ",")
signed_payload = "{timestamp:d}.{raw_payload}".format(timestamp=timestamp, raw_payload=raw_payload)
signature = WebhookSignature._compute_signature(signed_payload, settings.STRIPE_WEBHOOK_ENDPOINT_SECRET)
headers = {
"HTTP_STRIPE_SIGNATURE": ("t={timestamp:d},v1={signature}"
",v0=not_important".format(timestamp=timestamp, signature=signature))
}
self.client.credentials(**headers)
response = self.client.post(url, data=payload, format="json")
self.assertEqual(response.status_code, 201)
self.assertEqual(StripeWebhook.objects.count(), 1)
webhook = StripeWebhook.objects.first()
self.assertEqual(webhook.id, payload["id"])
self.assertEqual(webhook.raw_data, payload)
self.assertFalse(webhook.is_parsed)

0 comments on commit b488b7d

Please sign in to comment.