-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
app.py
2926 lines (2424 loc) · 112 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
This file is the entrypoint for this Flask application. Can be executed with 'flask
run', 'python app.py' or via a WSGI server like gunicorn or uwsgi.
"""
import calendar
#import json
import locale
import logging
import os
import re
import uuid
from datetime import datetime, timedelta
from pprint import pformat
import stripe
import plaid
from plaid.api import plaid_api
from plaid.model.item_public_token_exchange_request import ItemPublicTokenExchangeRequest
from plaid.model.processor_stripe_bank_account_token_create_request import ProcessorStripeBankAccountTokenCreateRequest
from amazon_pay.client import AmazonPayClient
from amazon_pay.ipn_handler import IpnHandler
from flask import Flask, jsonify, redirect, render_template, request, send_from_directory
from flask_limiter import Limiter
from flask_talisman import Talisman
from nameparser import HumanName
from pytz import timezone
from email_validator import validate_email, EmailNotValidError
from app_celery import make_celery
from bad_actor import BadActor
from charges import ChargeException, QuarantinedException, charge, create_plaid_link_token, calculate_amount_fees, check_level
from batch import Lock
from config import (
TIMEZONE,
AMAZON_MERCHANT_ID,
AMAZON_SANDBOX,
AMAZON_CAMPAIGN_ID,
MWS_ACCESS_KEY,
MWS_SECRET_KEY,
DEFAULT_FREQUENCY,
FLASK_SECRET_KEY,
FLASK_DEBUG,
WTF_CSRF_ENABLED,
LOG_LEVEL,
PLAID_SECRET,
PLAID_ENVIRONMENT,
PLAID_API_VERSION,
ENABLE_PORTAL,
ADVERTISING_CAMPAIGN_ID,
ANNIVERSARY_PARTY_CAMPAIGN_ID,
COMBINED_EMAIL_FIELD,
DEFAULT_CAMPAIGN_ONETIME,
DEFAULT_CAMPAIGN_RECURRING,
FESTIVAL_CAMPAIGN_ID,
TONIGHT_CAMPAIGN_ID,
MINNROAST_CAMPAIGN_ID,
MERCHANDISE_SALES_CAMPAIGN_ID,
SALESFORCE_CONTACT_ADVERTISING_EMAIL,
ENABLE_SENTRY,
SENTRY_DSN,
SENTRY_ENVIRONMENT,
REPORT_URI,
STRIPE_WEBHOOK_SECRET,
GOOGLE_ANALYTICS_ID,
GOOGLE_ANALYTICS_TRACKING_CODE_TYPE,
GOOGLE_TAG_MANAGER_ID,
GOOGLE_TAG_MANAGER_AUTH,
GOOGLE_TAG_MANAGER_PREVIEW
)
from forms import (
format_amount,
format_swag,
format_swag_subscription,
is_human,
PlaidForm,
DonateForm,
MinimalForm,
SponsorshipForm,
SalesForm,
AdvertisingForm,
CancelForm,
FinishForm,
)
from npsp import RDO, Account, Affiliation, Contact, Opportunity
from util import (
clean,
notify_slack,
send_multiple_account_warning,
dir_last_updated,
is_known_spam_email,
)
ZONE = timezone(TIMEZONE)
if ENABLE_SENTRY:
import sentry_sdk
from sentry_sdk.integrations.celery import CeleryIntegration
from sentry_sdk.integrations.flask import FlaskIntegration
sentry_sdk.init(
dsn=SENTRY_DSN,
environment=SENTRY_ENVIRONMENT,
integrations=[FlaskIntegration(), CeleryIntegration()],
)
locale.setlocale(locale.LC_ALL, "C")
csp = {
"default-src": ["'self'", "*.minnpost.com"],
"font-src": [
"'self'",
"data:",
"*.cloudflare.com",
"fonts.gstatic.com",
"use.typekit.net",
],
"style-src": [
"'self'",
"'unsafe-inline'",
"*.googleapis.com",
"tagmanager.google.com",
],
"img-src": [
"'self'",
"data:",
"*.minnpost.com",
"q.stripe.com",
"www.facebook.com",
"stats.g.doubleclick.net",
"www.google-analytics.com",
"www.google.com",
"googleads.g.doubleclick.net",
"www.googletagmanager.com",
"p.typekit.net",
"www.google.se",
"www.gstatic.com",
"www.google.iq",
"www.google-analytics.com",
"www.google.md",
"www.google.com.qa",
"www.google.ca",
"www.google.es",
"www.google.am",
"www.google.de",
"www.google.jo",
"www.google.com.pr",
"www.google.com.ng",
"www.google.com.lb",
"www.google.be",
"www.google.se",
"www.google.co.uk",
"www.google.co.in",
"srclinkapp.biz",
"www.google.com.mx",
"*",
],
"connect-src": [
"*.stripe.com",
"*.minnpost.com",
"www.google-analytics.com",
"www.facebook.com",
"stats.g.doubleclick.net",
"performance.typekit.net",
"*",
],
"frame-src": [
"'self'",
"*.stripe.com",
"www.googletagmanager.com",
"www.facebook.com",
"bid.g.doubleclick.net",
"bid.g.doubleclick.net",
"fonts.gstatic.com",
"connect.facebook.net",
"wib.capitalone.com",
"api.pmmapads.com",
"*",
],
"script-src": [
"data:",
"'unsafe-inline'",
"'unsafe-eval'",
"*.minnpost.com",
"www.googleadservices.com",
"js.stripe.com",
"*.googleapis.com",
"connect.facebook.net",
"www.googletagmanager.com",
"use.typekit.net",
"code.jquery.com",
"checkout.stripe.com",
"www.google-analytics.com",
"googleads.g.doubleclick.net",
"watcher.risd.net",
"*",
],
}
app = Flask(__name__)
Talisman(
app,
content_security_policy={},
content_security_policy_report_only=True,
content_security_policy_report_uri=REPORT_URI,
)
def get_real_user_ip():
"""ratelimit the users original ip instead of (optional) reverse proxy"""
if not request.headers.getlist("X-Forwarded-For"):
ip = request.remote_addr
else:
ip = request.headers.getlist("X-Forwarded-For")[0]
return ip
limiter = Limiter(
app, key_func=get_real_user_ip, default_limits=["200 per day", "250 per hour"]
)
log_level = logging.getLevelName(LOG_LEVEL)
app.logger.setLevel(log_level)
for handler in app.logger.handlers:
limiter.logger.addHandler(handler)
app.secret_key = FLASK_SECRET_KEY
app.config.from_pyfile("config.py")
app.config.update(
CELERY_ACCEPT_CONTENT=["pickle", "json"],
CELERY_ALWAYS_EAGER=False,
CELERY_IMPORTS=("app", "npsp", "batch"),
)
stripe.api_key = app.config["STRIPE_KEYS"]["secret_key"]
celery = make_celery(app)
"""
Redirects.
"""
# support.minnpost.com/minnroast-sponsorship
@app.route("/minnroast-sponsorship/")
def minnroast_sponsorship_form():
query_string = request.query_string.decode("utf-8")
return redirect("/minnroast-patron/?%s" % query_string, code=302)
# support.minnpost.com/minnroast-pledge
@app.route("/minnroast-pledge/")
def minnroast_pledge_form():
query_string = request.query_string.decode("utf-8")
return redirect("/pledge-payment/?%s" % query_string, code=302)
# support.minnpost.com/recurring-donation-update
@app.route("/recurring-donation-update/")
def minnpost_recurring_donation_update_form():
query_string = request.query_string.decode("utf-8")
return redirect("/donation-update/?%s" % query_string, code=302)
# support.minnpost.com/anniversary-sponsorship
@app.route("/anniversary-sponsorship/")
def anniversary_sponsorship_form():
query_string = request.query_string.decode("utf-8")
return redirect("/anniversary/?%s" % query_string, code=302)
# support.minnpost.com/anniversary-patron
@app.route("/anniversary-patron/")
def anniversary_patron_form():
query_string = request.query_string.decode("utf-8")
return redirect("/anniversary/?%s" % query_string, code=302)
# support.minnpost.com/minnpost-advertising
@app.route("/minnpost-advertising/")
def minnpost_advertising_form():
query_string = request.query_string.decode("utf-8")
return redirect("/advertising-payment/?%s" % query_string, code=302)
def apply_card_details(data=None, customer=None, payment_method=None, charge_source=None):
"""
Takes the expiration date, card brand and expiration from a Stripe object and copies
it to an RDO or Opportunity in Salesforce. The object is NOT saved and must be done
after calling this function. That's to save an API call since other SF details will
almost certainly need to be saved as well.
This method is not called if the payment type is bank account.
"""
# if the charge does not specify a payment method get it from the customer
if payment_method is None and charge_source is None:
payment_methods = stripe.PaymentMethod.list(
customer=customer["id"],
type="card",
limit=1,
)
if payment_methods is not []:
card_id = payment_methods.data[0].id
card = payment_methods.data[0].card
year = card.exp_year
month = card.exp_month
brand = card.brand
last4 = card.last4
else:
customer = stripe.Customer.retrieve(customer["id"])
card_id = customer.sources.data[0].id
card = customer.sources.retrieve(card_id)
year = card.exp_year
month = card.exp_month
brand = card.brand
last4 = card.last4
elif payment_method is not None:
# there is a payment method object
card = payment_method["card"]
card_id = payment_method["id"]
year = card["exp_year"]
month = card["exp_month"]
brand = card["brand"]
last4 = card["last4"]
if card["wallet"] is not None:
wallet_type = card["wallet"]["type"]
logging.info(f"digital wallet type is {wallet_type} ")
data.digital_wallet_type = card["wallet"]["type"]
elif charge_source is not None:
# there is a charge object
card = charge_source
card_id = card["id"]
year = card["exp_year"]
month = card["exp_month"]
brand = card["brand"]
last4 = card["last4"]
day = calendar.monthrange(year, month)[1]
# card details for Salesforce
data.stripe_card = card_id
data.stripe_card_expiration = f"{year}-{month:02d}-{day:02d}"
data.card_type = brand
data.stripe_card_last_4 = last4
return data
@celery.task(name="app.add_donation")
def add_donation(form=None, customer=None, donation_type=None, payment_method=None, charge_source=None, bad_actor_request=None):
"""
Add a contact and their donation into SF. This is done in the background
because there are a lot of API calls and there's no point in making the
payer wait for them. It sends a notification about the donation to Slack (if configured).
"""
#bad_actor_response = BadActor(bad_actor_request=bad_actor_request)
#quarantine = bad_actor_response.quarantine
quarantine = False
form = clean(form)
first_name = form.get("first_name", "")
last_name = form.get("last_name", "")
installment_period = form.get("installment_period", app.config["DEFAULT_FREQUENCY"])
email = form.get("email", "")
street = form.get("billing_street", "")
city = form.get("billing_city", "")
state = form.get("billing_state", "")
country = form.get("billing_country", "")
zipcode = form.get("billing_zip", "")
stripe_customer_id = form.get("stripe_customer_id", "")
fair_market_value = form.get("fair_market_value", 0)
opportunity_subtype = form.get('opportunity_subtype', None)
if opportunity_subtype is not None and opportunity_subtype == 'Sales: Advertising':
email = SALESFORCE_CONTACT_ADVERTISING_EMAIL
logging.info("----Getting contact....")
contact = Contact.get_or_create(
email=email, first_name=first_name, last_name=last_name, stripe_customer_id=stripe_customer_id,
street=street, city=city, state=state, zipcode=zipcode, country=country
)
logging.info(contact)
if opportunity_subtype is None or opportunity_subtype != 'Sales: Advertising':
if contact.first_name != first_name or contact.last_name != last_name:
logging.info(
f"Contact name doesn't match: {contact.first_name} {contact.last_name}"
)
if not contact.created:
logging.info(f"Updating contact {first_name} {last_name}")
contact.first_name = first_name
contact.last_name = last_name
contact.mailing_street = street
contact.mailing_city = city
contact.mailing_state = state
contact.mailing_postal_code = zipcode
contact.mailing_country = country
if stripe_customer_id != "":
contact.stripe_customer_id = stripe_customer_id
contact.save()
if contact.duplicate_found:
send_multiple_account_warning(contact)
if form["in_honor_or_memory"] != None:
honor_or_memory = form["in_honor_or_memory"]
form["in_honor_or_memory"] = 'In ' + str(honor_or_memory) + ' of...'
if installment_period == "one-time":
logging.info("----Creating one time payment...")
opportunity = add_opportunity(
contact=contact, form=form, customer=customer, payment_method=payment_method, charge_source=charge_source, quarantine=quarantine
)
try:
charge(opportunity)
lock = Lock(key=opportunity.lock_key)
lock.append(key=opportunity.lock_key, value=opportunity.id)
logging.info(opportunity)
notify_slack(contact=contact, opportunity=opportunity)
except ChargeException as e:
e.send_slack_notification()
except QuarantinedException:
bad_actor_response.notify_bad_actor(
transaction_type="Opportunity", transaction=opportunity
)
return True
else:
logging.info("----Creating recurring payment...")
rdo = add_recurring_donation(
contact=contact, form=form, customer=customer, payment_method=payment_method, charge_source=charge_source, quarantine=quarantine
)
# get opportunities
opportunities = rdo.opportunities()
today = datetime.now(tz=ZONE).strftime("%Y-%m-%d")
closing_today = [
opportunity
for opportunity in opportunities
if opportunity.close_date == today
]
if len(closing_today):
opp = closing_today[0]
opp.fair_market_value = fair_market_value # set the first opportunity's fair market value
try:
charge(opp)
lock = Lock(key=rdo.lock_key)
lock.append(key=rdo.lock_key, value=rdo.id)
logging.info(rdo)
notify_slack(contact=contact, rdo=rdo)
except ChargeException as e:
e.send_slack_notification()
except QuarantinedException:
bad_actor_response.notify_bad_actor(transaction_type="RDO", transaction=rdo)
return True
# this is used to update or cancel donations
@celery.task(name="app.update_donation")
def update_donation(form=None, customer=None, donation_type=None, payment_method=None, charge_source=None, bad_actor_request=None):
"""
Update a contact and their donation in SF. This is done in the background
because there are a lot of API calls and there's no point in making the
payer wait for them. It sends a notification about the donation to Slack (if configured).
"""
#bad_actor_response = BadActor(bad_actor_request=bad_actor_request)
#quarantine = bad_actor_response.quarantine
quarantine = False
form = clean(form)
first_name = form.get("first_name", "")
last_name = form.get("last_name", "")
installment_period = form.get("installment_period", app.config["DEFAULT_FREQUENCY"])
email = form.get("email", "")
street = form.get("billing_street", "")
city = form.get("billing_city", "")
state = form.get("billing_state", "")
country = form.get("billing_country", "")
zipcode = form.get("billing_zip", "")
stripe_customer_id = form.get("stripe_customer_id", "")
opportunity_subtype = form.get('opportunity_subtype', None)
if opportunity_subtype is not None and opportunity_subtype == 'Sales: Advertising':
email = SALESFORCE_CONTACT_ADVERTISING_EMAIL
logging.info("----Getting contact....")
contact = Contact.get_or_create(
email=email, first_name=first_name, last_name=last_name, stripe_customer_id=stripe_customer_id,
street=street, city=city, state=state, zipcode=zipcode, country=country
)
logging.info(contact)
if opportunity_subtype is None or opportunity_subtype != 'Sales: Advertising':
if contact.first_name != first_name or contact.last_name != last_name:
logging.info(
f"Contact name doesn't match: {contact.first_name} {contact.last_name}"
)
if not contact.created:
logging.info(f"Updating contact {first_name} {last_name}")
contact.first_name = first_name
contact.last_name = last_name
contact.stripe_customer_id = stripe_customer_id
contact.mailing_street = street
contact.mailing_city = city
contact.mailing_state = state
contact.mailing_postal_code = zipcode
contact.mailing_country = country
contact.save()
if contact.duplicate_found:
send_multiple_account_warning(contact)
if form["in_honor_or_memory"] != None:
honor_or_memory = form["in_honor_or_memory"]
form["in_honor_or_memory"] = 'In ' + str(honor_or_memory) + ' of...'
if installment_period == "one-time":
logging.info("----Updating one time payment...")
opportunity = update_opportunity(
contact=contact, form=form, customer=customer, payment_method=payment_method, charge_source=charge_source, quarantine=quarantine
)
return True
else:
logging.info("----Updating recurring payment...")
rdo = update_recurring_donation(
contact=contact, form=form, customer=customer, payment_method=payment_method, charge_source=charge_source, quarantine=quarantine
)
# get opportunities
opportunities = rdo.opportunities()
today = datetime.now(tz=ZONE).strftime("%Y-%m-%d")
closing_today = [
opportunity
for opportunity in opportunities
if opportunity.close_date == today
]
if len(closing_today):
opp = closing_today[0]
return True
# retry it for up to one hour, then stop
@celery.task(name="app.finish_donation", bind=True, max_retries=30)
def finish_donation(self, form=None):
"""
Update the post-submit donation info in SF if supplied
"""
# we don't run clean() on this form because the messages field is a list
installment_period = form.get("installment_period", app.config["DEFAULT_FREQUENCY"])
lock_key = form.get("lock_key", "")
post_submit_details = dict()
# update the post submit fields
# testimonial
reason_for_supporting = form.get("reason_for_supporting", "")
reason_for_supporting_shareable = form.get("reason_shareable", False)
# newsletters
groups_submitted = form.get("groups_submitted", [])
if reason_for_supporting == "" and groups_submitted == []:
return False
if "04471b1571" in groups_submitted:
daily_newsletter = True
else:
daily_newsletter = False
if "94fc1bd7c9" in groups_submitted:
sunday_review_newsletter = True
else:
sunday_review_newsletter = False
if "ce6fd734b6" in groups_submitted:
greater_mn_newsletter = True
else:
greater_mn_newsletter = False
if "d89249e207" in groups_submitted:
dc_memo = True
else:
dc_memo = False
if "68449d845c" in groups_submitted:
event_messages = True
else:
event_messages = False
if "958bdb5d3c" in groups_submitted:
feedback_messages = True
else:
feedback_messages = False
# testimonial in salesforce
post_submit_details["Reason_for_Gift__c"] = reason_for_supporting
post_submit_details["Reason_for_gift_shareable__c"] = reason_for_supporting_shareable
# newsletters in salesforce
post_submit_details["Daily_newsletter_sign_up__c"] = daily_newsletter
post_submit_details["Sunday_Review_newsletter__c"] = sunday_review_newsletter
post_submit_details["Greater_MN_newsletter__c"] = greater_mn_newsletter
post_submit_details["DC_Memo_sign_up__c"] = dc_memo
post_submit_details["Event_member_benefit_messages__c"] = event_messages
post_submit_details["Input_feedback_messages__c"] = feedback_messages
if installment_period == "one-time":
opps = Opportunity.load_after_submit(
lock_key=lock_key
)
if not opps:
logging.info("No opportunity id here yet. Delay and try again.")
raise self.retry(countdown=120)
response = Opportunity.update(opps, post_submit_details)
else:
rdo = RDO.load_after_submit(
lock_key=lock_key
)
if not rdo:
logging.info("No recurring donation id here yet. Delay and try again.")
raise self.retry(countdown=120)
rdo_response = RDO.update(rdo, post_submit_details)
opps = Opportunity.load_after_submit(
stage_name="Closed Won",
lock_key=lock_key
)
if not opps:
logging.info("No closed opportunity id here yet. Delay and try again.")
raise self.retry(countdown=120)
opps_response = Opportunity.update(opps, post_submit_details)
def do_charge_or_show_errors(form_data, template, function, donation_type):
app.logger.debug("----Creating or updating Stripe customer...")
amount = form_data["amount"]
amount_formatted = format(amount, ",.2f")
email = form_data["email"]
first_name = form_data["first_name"]
last_name = form_data["last_name"]
installment_period = form_data.get("installment_period", app.config["DEFAULT_FREQUENCY"])
customer_id = form_data.get("customer_id", "")
update_default_source = form_data.get("update_default_source", "")
stripe_payment_type = form_data.get("stripe_payment_type", "")
charge_source = None
payment_method_id = None
payment_method = None
bank_token = None
source_token = None
customer = None
if form_data.get("payment_method_id", ""):
payment_method_id = form_data["payment_method_id"]
elif form_data.get("bankToken", ""):
bank_token = form_data["bankToken"]
elif form_data.get("stripeToken", ""):
source_token = form_data["stripeToken"]
app.logger.info(f"payment id is {payment_method_id} and bank token is {bank_token} and source token is {source_token}")
if stripe_payment_type == "card":
if payment_method_id is None and source_token is None:
body = []
message = "To pay with your credit card, first be sure to add all of the required information."
app.logger.error(f"Missing credit card error: {message}")
body.append({'type': 'missing_payment', 'message': message})
return jsonify(errors=body)
elif stripe_payment_type == "bank_account":
if bank_token is None:
body = []
message = "To pay with your bank account, first sign in above to authorize the charge."
app.logger.error(f"Missing bank account error: {message}")
body.append({'type': 'missing_payment', 'message': message})
return jsonify(errors=body)
if customer_id == "": # this is a new customer
app.logger.debug("----Creating new Stripe customer...")
# if it is a new customer, assume they only have one payment method and it should be the default
try:
if payment_method_id is not None:
customer = stripe.Customer.create(
email=email,
payment_method=payment_method_id
)
# retrieve the payment method object for consistency
payment_method = stripe.PaymentMethod.retrieve(
payment_method_id
)
elif bank_token is not None:
customer = stripe.Customer.create(
email=email,
source=bank_token
)
elif source_token is not None:
customer = stripe.Customer.create(
email=email,
source=source_token
)
app.logger.info(customer)
except stripe.error.CardError as e: # Stripe returned a card error
body = e.json_body
err = body.get("error", {})
message = err.get("message", "")
app.logger.error(f"Stripe CardError: {message}")
return jsonify(errors=body)
except stripe.error.InvalidRequestError as e:
body = e.json_body
err = body.get("error", {})
message = err.get("message", "")
app.logger.error(f"Stripe InvalidRequestError: {message}")
return jsonify(errors=body)
except stripe.error.RateLimitError as e: # Too many requests made to the API too quickly
body = e.json_body
err = body.get("error", {})
message = err.get("message", "")
app.logger.error(f"Stripe RateLimitError: {message}")
return jsonify(errors=body)
except stripe.error.AuthenticationError as e: # Authentication with Stripe's API failed
body = e.json_body
err = body.get("error", {})
message = err.get("message", "")
app.logger.error(f"Stripe AuthenticationError: {message}")
return jsonify(errors=body)
except stripe.error.APIConnectionError as e: # Network communication with Stripe failed
body = e.json_body
err = body.get("error", {})
message = err.get("message", "")
app.logger.error(f"Stripe APIConnectionError: {message}")
return jsonify(errors=body)
except stripe.error.StripeError as e: # Generic stripe error
body = e.json_body
err = body.get("error", {})
message = err.get("message", "")
app.logger.error(f"Stripe StripeError: {message}")
return jsonify(errors=body)
except Exception as e: # Unknown Stripe error
body = e.json_body
err = body.get("error", {})
message = err.get("message", "")
app.logger.error(f"Stripe Unknown Error: {message}")
return jsonify(errors=body)
elif customer_id is not None and customer_id != '': # this is an existing customer
app.logger.info(f"----Updating existing Stripe customer: ID {customer_id}")
customer = stripe.Customer.retrieve(customer_id)
# since this is an existing customer, add the current payment method to the list.
# we don't keep doing the default source thing since Stripe doesn't push it now.
try:
if payment_method_id is not None:
app.logger.info(f"----Update customer: ID {customer_id}. Retrieve payment method.")
customer = stripe.Customer.modify(
customer_id,
email=email,
)
# retrieve the payment method object
payment_method = stripe.PaymentMethod.retrieve(
payment_method_id
)
elif bank_token is not None:
app.logger.info(f"----Update customer: ID {customer_id}. Retrieve bank account.")
customer = stripe.Customer.modify(
customer_id,
email=email,
)
# retrieve the bank account object
charge_source = stripe.Customer.create_source(
customer_id,
source=bank_token,
)
elif source_token is None:
if update_default_source != "":
app.logger.info(f"----Add new default source for customer: ID {customer_id}.")
customer = stripe.Customer.modify(
customer_id,
email=email,
source=source_token
)
else:
app.logger.info(f"----Add new source for customer: ID {customer_id}")
charge_source = stripe.Customer.create_source(
customer_id,
source=source_token,
)
except stripe.error.CardError as e: # Stripe returned a card error
body = e.json_body
err = body.get("error", {})
message = err.get("message", "")
app.logger.error(f"Stripe CardError: {message}")
return jsonify(errors=body)
except stripe.error.InvalidRequestError as e: # Stripe returned a bank account error
body = e.json_body
err = body.get("error", {})
message = err.get("message", "")
if message == 'A bank account with that routing number and account number already exists for this customer.':
# try to get the bank account that matches the token they've supplied
try:
token = stripe.Token.retrieve(bank_token)
bank_accounts = stripe.Customer.list_sources(
customer_id,
object="bank_account",
)
for bank_account in bank_accounts:
if bank_account.object == 'bank_account' and bank_account.routing_number == token.bank_account.routing_number and bank_account.last4 == token.bank_account.last4:
customer = stripe.Customer.modify(
customer_id,
email=email,
)
charge_source = bank_account
app.logger.debug("----Reuse this bank account that was already on the Stripe customer...")
break
except stripe.error.InvalidRequestError as e: # give up
body = e.json_body
err = body.get("error", {})
message = err.get("message", "")
app.logger.error(f"Stripe InvalidRequestError: {message}")
return jsonify(errors=body)
else:
app.logger.error(f"Stripe InvalidRequestError: {message}")
return jsonify(errors=body)
except stripe.error.RateLimitError as e: # Too many requests made to the API too quickly
body = e.json_body
err = body.get("error", {})
message = err.get("message", "")
app.logger.error(f"Stripe RateLimitError: {message}")
return jsonify(errors=body)
except stripe.error.AuthenticationError as e: # Authentication with Stripe's API failed
body = e.json_body
err = body.get("error", {})
message = err.get("message", "")
app.logger.error(f"Stripe AuthenticationError: {message}")
return jsonify(errors=body)
except stripe.error.APIConnectionError as e: # Network communication with Stripe failed
body = e.json_body
err = body.get("error", {})
message = err.get("message", "")
app.logger.error(f"Stripe APIConnectionError: {message}")
return jsonify(errors=body)
except stripe.error.StripeError as e: # Generic stripe error
body = e.json_body
err = body.get("error", {})
message = err.get("message", "")
app.logger.error(f"Stripe StripeError: {message}")
return jsonify(errors=body)
except Exception as e: # Unknown Stripe error
body = e.json_body
err = body.get("error", {})
message = err.get("message", "")
app.logger.error(f"Stripe Unknown Error: {message}")
return jsonify(errors=body)
app.logger.info(f"Customer id: {customer.id} Customer email: {email} Customer name: {first_name} {last_name} Charge amount: {amount_formatted} Charge installment period: {installment_period}")
bad_actor_request = None
#try:
# if "zipcode" in form_data:
# zipcode = form_data["zipcode"]
# else:
# zipcode = form_data["billing_zip"]
# bad_actor_request = BadActor.create_bad_actor_request(
# headers=request.headers,
# captcha_token=form_data["recaptchaToken"],
# email=email,
# amount=amount,
# zipcode=zipcode,
# first_name=form_data["first_name"],
# last_name=form_data["last_name"],
# remote_addr=request.remote_addr,
# )
# app.logger.info(bad_actor_request)
#except Exception as error:
# app.logger.warning("Unable to check for bad actor: %s", error)
function(
customer=customer,
form=clean(form_data),
donation_type=donation_type,
payment_method=payment_method,
charge_source=charge_source,
bad_actor_request=bad_actor_request,
)
# get the json response from the server and put it into the specified template
return jsonify(success=True)
def validate_form(FormType, template, function=add_donation.delay):
form = FormType(request.form)
# use form.data instead of request.form from here on out
# because it includes all filters applied by WTF Forms
form_data = form.data
form_errors = form.errors
email = form_data["email"]
first_name = form_data["first_name"]
last_name = form_data["last_name"]
app.logger.info(pformat(form_data))
# currently donation_type is not used for anything. maybe it should be used for the opportunity type
if FormType is DonateForm or FormType is MinimalForm or FormType is CancelForm or FormType is FinishForm:
donation_type = "Donation"
elif FormType is AdvertisingForm or FormType is SalesForm:
donation_type = "Sales"
elif FormType is SponsorshipForm:
donation_type = "Sponsorship"
else:
raise Exception("Unrecognized form type")
# some form types allow for updating an existing Salesforce record
if FormType is MinimalForm or FormType is CancelForm:
if form_data["opportunity_id"] or form_data["recurring_id"]:
function = update_donation.delay
body = []
try:
valid = validate_email(email, allow_smtputf8=False) # validate and get info
email = valid.email # replace with normalized form
except EmailNotValidError as e:
# email is not valid, exception message is human-readable
app.logger.error(f"Email validation failed on address: {email}")
message = str(e)
body.append({"field": "email", "message": message})
return jsonify(errors=body)
if not form.validate():
app.logger.error(f"Form validation errors: {form.errors}")
for field in form.errors:
body.append({"field": field, "message": form.errors[field]})
return jsonify(errors=body)
email_is_spam = is_known_spam_email(email)
if email_is_spam is True: # email was a spammer
body = []
message = f"Please ensure you have a valid email address. {email} has been flagged as a possible spam email address."
body.append({"field": "email", "message": message})
return jsonify(errors=body)
if app.config["USE_RECAPTCHA"] == True:
captcha_response = request.form['g-recaptcha-response']
if not is_human(captcha_response):
app.logger.error(f"Error: recaptcha failed on donation: {email} {first_name} {last_name}")
message = 'Our system was unable to verify that you are a human. Please email [email protected] for assistance.'
body.append({'field': 'recaptcha', 'message': message})
return jsonify(errors=body)
# for a cancel form, we go ahead and pass the data to the function and then stop
if FormType is CancelForm:
customer = None
customer_id = form_data["customer_id"]
if customer_id:
customer = stripe.Customer.retrieve(form_data["customer_id"])
function(customer=customer, form=clean(form_data), donation_type=donation_type)
# get the json response from the server and put it into the specified template
return True
return do_charge_or_show_errors(
form_data=form_data,
template=template,
function=function,
donation_type=donation_type,
)
@app.route("/robots.txt")
def robots_txt():
root_dir = os.path.dirname(os.getcwd())
return send_from_directory(os.path.join(root_dir, "app"), "robots.txt")
@app.route("/")
def root_form():
template = "root.html"
title = "Support MinnPost"
form = MinimalForm()
form_action = "/give/"
# if there is already an amount, use it
if request.args.get("amount"):
amount = format_amount(request.args.get("amount"))
amount_formatted = format(amount, ",.2f")
else:
amount = ""
amount_formatted = ""
# installment period