-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathclient.py
More file actions
1204 lines (918 loc) · 44.8 KB
/
client.py
File metadata and controls
1204 lines (918 loc) · 44.8 KB
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
"""Python client for Sift Science's API.
See: https://siftscience.com/docs/references/events-api
"""
import decimal
import json
import requests
import requests.auth
import sys
if sys.version_info[0] < 3:
import six.moves.urllib as urllib
_UNICODE_STRING = str
else:
import urllib.parse
_UNICODE_STRING = str
import sift
import sift.version
API_URL = 'https://api.siftscience.com'
API3_URL = 'https://api3.siftscience.com'
API_URL_VERIFICATION = 'https://api.sift.com/v1/verification/'
DECISION_SOURCES = ['MANUAL_REVIEW', 'AUTOMATED_RULE', 'CHARGEBACK']
def _quote_path(s):
# by default, urllib.quote doesn't escape forward slash; pass the
# optional arg to override this
return urllib.parse.quote(s, '')
class DecimalEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, decimal.Decimal):
return (str(o),)
return super(DecimalEncoder, self).default(o)
class Client(object):
def __init__(
self,
api_key=None,
api_url=API_URL,
timeout=2.0,
account_id=None,
version=sift.version.API_VERSION,
session=None):
"""Initialize the client.
Args:
api_key: Your Sift Science API key associated with your customer
account. You can obtain this from
https://siftscience.com/console/developer/api-keys .
api_url: Base URL, including scheme and host, for sending events.
Defaults to 'https://api.siftscience.com'.
timeout: Number of seconds to wait before failing request. Defaults
to 2 seconds.
account_id: The ID of your Sift Science account. You can obtain
this from https://siftscience.com/console/account/profile .
version: The version of the Sift Science API to call. Defaults to
the latest version ('205').
"""
_assert_non_empty_unicode(api_url, 'api_url')
if api_key is None:
api_key = sift.api_key
_assert_non_empty_unicode(api_key, 'api_key')
self.session = session or requests.Session()
self.api_key = api_key
self.url = api_url
self.timeout = timeout
self.account_id = account_id or sift.account_id
self.version = version
def track(
self,
event,
properties,
path=None,
return_score=False,
return_action=False,
return_workflow_status=False,
return_route_info=False,
force_workflow_run=False,
abuse_types=None,
timeout=None,
version=None,
include_score_percentiles=False):
"""Track an event and associated properties to the Sift Science client.
This call is blocking. Check out https://siftscience.com/resources/references/events-api
for more information on what types of events you can send and fields you can add to the
properties parameter.
Args:
event: The name of the event to send. This can either be a reserved
event name such as "$transaction" or "$create_order" or a custom event
name (that does not start with a $).
properties: A dict of additional event-specific attributes to track.
return_score: Whether the API response should include a score for this
user (the score will be calculated using this event).
return_action: Whether the API response should include actions in the response. For
more information on how this works, please visit the tutorial at:
https://siftscience.com/resources/tutorials/formulas .
return_workflow_status: Whether the API response should
include the status of any workflow run as a result of
the tracked event.
return_route_info: Whether to get the route information from the Workflow Decision.
This parameter must be used with the return_workflow_status query parameter.
force_workflow_run: TODO:(rlong) Add after Rishabh adds documentation.
abuse_types(optional): List of abuse types, specifying for which abuse types a score
should be returned (if scores were requested). If not specified, a score will
be returned for every abuse_type to which you are subscribed.
timeout(optional): Use a custom timeout (in seconds) for this call.
version(optional): Use a different version of the Sift Science API for this call.
include_score_percentiles(optional) : Whether to add new parameter in the query parameter.
if include_score_percentiles is true then add a new parameter called fields in the query parameter
Returns:
A sift.client.Response object if the track call succeeded, otherwise
raises an ApiException.
"""
_assert_non_empty_unicode(event, 'event')
_assert_non_empty_dict(properties, 'properties')
headers = {'Content-type': 'application/json',
'Accept': '*/*',
'User-Agent': self._user_agent()}
if version is None:
version = self.version
if path is None:
path = self._event_url(version)
if timeout is None:
timeout = self.timeout
properties.update({'$api_key': self.api_key, '$type': event})
params = {}
if return_score:
params['return_score'] = 'true'
if return_action:
params['return_action'] = 'true'
if abuse_types:
params['abuse_types'] = ','.join(abuse_types)
if return_workflow_status:
params['return_workflow_status'] = 'true'
if return_route_info:
params['return_route_info'] = 'true'
if force_workflow_run:
params['force_workflow_run'] = 'true'
if include_score_percentiles:
field_types = ['SCORE_PERCENTILES']
params['fields'] = ','.join(field_types)
try:
response = self.session.post(
path,
data=json.dumps(properties, cls=DecimalEncoder),
headers=headers,
timeout=timeout,
params=params)
return Response(response)
except requests.exceptions.RequestException as e:
raise ApiException(str(e), path)
def score(self, user_id, timeout=None, abuse_types=None, version=None):
"""Retrieves a user's fraud score from the Sift Science API.
This call is blocking. Check out https://siftscience.com/resources/references/score_api.html
for more information on our Score response structure.
Args:
user_id: A user's id. This id should be the same as the user_id used in
event calls.
timeout(optional): Use a custom timeout (in seconds) for this call.
abuse_types(optional): List of abuse types, specifying for which abuse types a score
should be returned (if scores were requested). If not specified, a score will
be returned for every abuse_type to which you are subscribed.
version(optional): Use a different version of the Sift Science API for this call.
Returns:
A sift.client.Response object if the score call succeeded, or raises
an ApiException.
"""
_assert_non_empty_unicode(user_id, 'user_id')
if timeout is None:
timeout = self.timeout
if version is None:
version = self.version
headers = {'User-Agent': self._user_agent()}
params = {'api_key': self.api_key}
if abuse_types:
params['abuse_types'] = ','.join(abuse_types)
url = self._score_url(user_id, version)
try:
response = self.session.get(
url,
headers=headers,
timeout=timeout,
params=params)
return Response(response)
except requests.exceptions.RequestException as e:
raise ApiException(str(e), url)
def get_user_score(self, user_id, timeout=None, abuse_types=None):
"""Fetches the latest score(s) computed for the specified user and abuse types from the Sift Science API.
As opposed to client.score() and client.rescore_user(), this *does not* compute a new score for the user; it
simply fetches the latest score(s) which have computed. These scores may be arbitrarily old.
This call is blocking. See https://siftscience.com/developers/docs/python/score-api/get-score for more details.
Args:
user_id: A user's id. This id should be the same as the user_id used in
event calls.
timeout(optional): Use a custom timeout (in seconds) for this call.
abuse_types(optional): List of abuse types, specifying for which abuse types a score
should be returned (if scores were requested). If not specified, a score will
be returned for every abuse_type to which you are subscribed.
Returns:
A sift.client.Response object if the score call succeeded, or raises
an ApiException.
"""
_assert_non_empty_unicode(user_id, 'user_id')
if timeout is None:
timeout = self.timeout
url = self._user_score_url(user_id, self.version)
headers = {'User-Agent': self._user_agent()}
params = {'api_key': self.api_key}
if abuse_types:
params['abuse_types'] = ','.join(abuse_types)
try:
response = self.session.get(
url,
headers=headers,
timeout=timeout,
params=params)
return Response(response)
except requests.exceptions.RequestException as e:
raise ApiException(str(e), url)
def rescore_user(self, user_id, timeout=None, abuse_types=None):
"""Rescores the specified user for the specified abuse types and returns the resulting score(s).
This call is blocking. See https://siftscience.com/developers/docs/python/score-api/rescore for more details.
Args:
user_id: A user's id. This id should be the same as the user_id used in
event calls.
timeout(optional): Use a custom timeout (in seconds) for this call.
abuse_types(optional): List of abuse types, specifying for which abuse types a score
should be returned (if scores were requested). If not specified, a score will
be returned for every abuse_type to which you are subscribed.
Returns:
A sift.client.Response object if the score call succeeded, or raises
an ApiException.
"""
_assert_non_empty_unicode(user_id, 'user_id')
if timeout is None:
timeout = self.timeout
url = self._user_score_url(user_id, self.version)
headers = {'User-Agent': self._user_agent()}
params = {'api_key': self.api_key}
if abuse_types:
params['abuse_types'] = ','.join(abuse_types)
try:
response = self.session.post(
url,
headers=headers,
timeout=timeout,
params=params)
return Response(response)
except requests.exceptions.RequestException as e:
raise ApiException(str(e), url)
def label(self, user_id, properties, timeout=None, version=None):
"""Labels a user as either good or bad through the Sift Science API.
This call is blocking. Check out https://siftscience.com/resources/references/labels_api.html
for more information on what fields to send in properties.
Args:
user_id: A user's id. This id should be the same as the user_id used in
event calls.
properties: A dict of additional event-specific attributes to track.
timeout(optional): Use a custom timeout (in seconds) for this call.
version(optional): Use a different version of the Sift Science API for this call.
Returns:
A sift.client.Response object if the label call succeeded, otherwise
raises an ApiException.
"""
_assert_non_empty_unicode(user_id, 'user_id')
if version is None:
version = self.version
return self.track(
'$label',
properties,
path=self._label_url(user_id, version),
timeout=timeout,
version=version)
def unlabel(self, user_id, timeout=None, abuse_type=None, version=None):
"""unlabels a user through the Sift Science API.
This call is blocking. Check out https://siftscience.com/resources/references/labels_api.html
for more information.
Args:
user_id: A user's id. This id should be the same as the user_id used in
event calls.
timeout(optional): Use a custom timeout (in seconds) for this call.
abuse_type(optional): The abuse type for which the user should be unlabeled.
If omitted, the user is unlabeled for all abuse types.
version(optional): Use a different version of the Sift Science API for this call.
Returns:
A sift.client.Response object if the unlabel call succeeded, otherwise
raises an ApiException.
"""
_assert_non_empty_unicode(user_id, 'user_id')
if timeout is None:
timeout = self.timeout
if version is None:
version = self.version
url = self._label_url(user_id, version)
headers = {'User-Agent': self._user_agent()}
params = {'api_key': self.api_key}
if abuse_type:
params['abuse_type'] = abuse_type
try:
response = self.session.delete(
url,
headers=headers,
timeout=timeout,
params=params)
return Response(response)
except requests.exceptions.RequestException as e:
raise ApiException(str(e), url)
def get_workflow_status(self, run_id, timeout=None):
"""Gets the status of a workflow run.
Args:
run_id: The ID of a workflow run.
Returns:
A sift.client.Response object if the call succeeded.
Otherwise, raises an ApiException.
"""
_assert_non_empty_unicode(run_id, 'run_id')
url = self._workflow_status_url(self.account_id, run_id)
if timeout is None:
timeout = self.timeout
try:
return Response(self.session.get(
url,
auth=requests.auth.HTTPBasicAuth(self.api_key, ''),
headers={'User-Agent': self._user_agent()},
timeout=timeout))
except requests.exceptions.RequestException as e:
raise ApiException(str(e), url)
def get_decisions(self, entity_type, limit=None, start_from=None, abuse_types=None, timeout=None):
"""Get decisions available to customer
Args:
entity_type: only return decisions applicable to entity type {USER|ORDER|SESSION|CONTENT}
limit: number of query results (decisions) to return [optional, default: 100]
start_from: result set offset for use in pagination [optional, default: 0]
abuse_types: comma-separated list of abuse_types used to filter returned decisions (optional)
Returns:
A sift.client.Response object containing array of decisions if call succeeded
Otherwise raises an ApiException
"""
if timeout is None:
timeout = self.timeout
params = {}
_assert_non_empty_unicode(entity_type, 'entity_type')
if entity_type.lower() not in ['user', 'order', 'session', 'content']:
raise ValueError("entity_type must be one of {user, order, session, content}")
params['entity_type'] = entity_type
if limit:
params['limit'] = limit
if start_from:
params['from'] = start_from
if abuse_types:
params['abuse_types'] = abuse_types
url = self._get_decisions_url(self.account_id)
try:
return Response(self.session.get(url, params=params,
auth=requests.auth.HTTPBasicAuth(self.api_key, ''),
headers={'User-Agent': self._user_agent()}, timeout=timeout))
except requests.exceptions.RequestException as e:
raise ApiException(str(e), url)
def apply_user_decision(self, user_id, properties, timeout=None):
"""Apply decision to user
Args:
user_id: id of user
properties:
decision_id: decision to apply to user
source: {one of MANUAL_REVIEW | AUTOMATED_RULE | CHARGEBACK}
analyst: id or email, required if 'source: MANUAL_REVIEW'
time: in millis when decision was applied
Returns
A sift.client.Response object if the call succeeded, else raises an ApiException
"""
if timeout is None:
timeout = self.timeout
self._validate_apply_decision_request(properties, user_id)
url = self._user_decisions_url(self.account_id, user_id)
try:
return Response(self.session.post(
url,
data=json.dumps(properties),
auth=requests.auth.HTTPBasicAuth(self.api_key, ''),
headers={'Content-type': 'application/json',
'Accept': '*/*',
'User-Agent': self._user_agent()},
timeout=timeout))
except requests.exceptions.RequestException as e:
raise ApiException(str(e), url)
def apply_order_decision(self, user_id, order_id, properties, timeout=None):
"""Apply decision to order
Args:
user_id: id of user
order_id: id of order
properties:
decision_id: decision to apply to order
source: {one of MANUAL_REVIEW | AUTOMATED_RULE | CHARGEBACK}
analyst: id or email, required if 'source: MANUAL_REVIEW'
description: free form text (optional)
time: in millis when decision was applied (optional)
Returns
A sift.client.Response object if the call succeeded, else raises an ApiException
"""
if timeout is None:
timeout = self.timeout
_assert_non_empty_unicode(user_id, 'user_id')
_assert_non_empty_unicode(order_id, 'order_id')
self._validate_apply_decision_request(properties, user_id)
url = self._order_apply_decisions_url(self.account_id, user_id, order_id)
try:
return Response(self.session.post(
url,
data=json.dumps(properties),
auth=requests.auth.HTTPBasicAuth(self.api_key, ''),
headers={'Content-type': 'application/json',
'Accept': '*/*',
'User-Agent': self._user_agent()},
timeout=timeout))
except requests.exceptions.RequestException as e:
raise ApiException(str(e), url)
def _validate_apply_decision_request(self, properties, user_id):
_assert_non_empty_unicode(user_id, 'user_id')
if not isinstance(properties, dict):
raise TypeError("properties must be a dict")
elif not properties:
raise ValueError("properties dictionary may not be empty")
source = properties.get('source')
_assert_non_empty_unicode(source, 'source', error_cls=ValueError)
if source not in DECISION_SOURCES:
raise ValueError("decision 'source' must be one of [{0}]".format(", ".join(DECISION_SOURCES)))
properties.update({'source': source.upper()})
if source == 'MANUAL_REVIEW' and not properties.get('analyst', None):
raise ValueError("must provide 'analyst' for decision 'source': 'MANUAL_REVIEW'")
def get_user_decisions(self, user_id, timeout=None):
"""Gets the decisions for a user.
Args:
user_id: The ID of a user.
Returns:
A sift.client.Response object if the call succeeded.
Otherwise, raises an ApiException.
"""
_assert_non_empty_unicode(user_id, 'user_id')
if timeout is None:
timeout = self.timeout
url = self._user_decisions_url(self.account_id, user_id)
try:
return Response(self.session.get(
url,
auth=requests.auth.HTTPBasicAuth(self.api_key, ''),
headers={'User-Agent': self._user_agent()},
timeout=timeout))
except requests.exceptions.RequestException as e:
raise ApiException(str(e), url)
def get_order_decisions(self, order_id, timeout=None):
"""Gets the decisions for an order.
Args:
order_id: The ID of an order.
Returns:
A sift.client.Response object if the call succeeded.
Otherwise, raises an ApiException.
"""
_assert_non_empty_unicode(order_id, 'order_id')
if timeout is None:
timeout = self.timeout
url = self._order_decisions_url(self.account_id, order_id)
try:
return Response(self.session.get(
url,
auth=requests.auth.HTTPBasicAuth(self.api_key, ''),
headers={'User-Agent': self._user_agent()},
timeout=timeout))
except requests.exceptions.RequestException as e:
raise ApiException(str(e), url)
def get_content_decisions(self, user_id, content_id, timeout=None):
"""Gets the decisions for a piece of content.
Args:
user_id: The ID of the owner of the content.
content_id: The ID of a piece of content.
Returns:
A sift.client.Response object if the call succeeded.
Otherwise, raises an ApiException.
"""
_assert_non_empty_unicode(content_id, 'content_id')
_assert_non_empty_unicode(user_id, 'user_id')
if timeout is None:
timeout = self.timeout
url = self._content_decisions_url(self.account_id, user_id, content_id)
try:
return Response(self.session.get(
url,
auth=requests.auth.HTTPBasicAuth(self.api_key, ''),
headers={'User-Agent': self._user_agent()},
timeout=timeout))
except requests.exceptions.RequestException as e:
raise ApiException(str(e), url)
def get_session_decisions(self, user_id, session_id, timeout=None):
"""Gets the decisions for a user's session.
Args:
user_id: The ID of a user.
session_id: The ID of a session.
Returns:
A sift.client.Response object if the call succeeded.
Otherwise, raises an ApiException.
"""
_assert_non_empty_unicode(user_id, 'user_id')
_assert_non_empty_unicode(session_id, 'session_id')
if timeout is None:
timeout = self.timeout
url = self._session_decisions_url(self.account_id, user_id, session_id)
try:
return Response(self.session.get(
url,
auth=requests.auth.HTTPBasicAuth(self.api_key, ''),
headers={'User-Agent': self._user_agent()},
timeout=timeout))
except requests.exceptions.RequestException as e:
raise ApiException(str(e), url)
def apply_session_decision(self, user_id, session_id, properties, timeout=None):
"""Apply decision to session
Args:
user_id: id of user
session_id: id of session
properties:
decision_id: decision to apply to session
source: {one of MANUAL_REVIEW | AUTOMATED_RULE | CHARGEBACK}
analyst: id or email, required if 'source: MANUAL_REVIEW'
description: free form text (optional)
time: in millis when decision was applied (optional)
Returns
A sift.client.Response object if the call succeeded, else raises an ApiException
"""
if timeout is None:
timeout = self.timeout
_assert_non_empty_unicode(session_id, 'session_id')
self._validate_apply_decision_request(properties, user_id)
url = self._session_apply_decisions_url(self.account_id, user_id, session_id)
try:
return Response(self.session.post(
url,
data=json.dumps(properties),
auth=requests.auth.HTTPBasicAuth(self.api_key, ''),
headers={'Content-type': 'application/json',
'Accept': '*/*',
'User-Agent': self._user_agent()},
timeout=timeout))
except requests.exceptions.RequestException as e:
raise ApiException(str(e), url)
def apply_content_decision(self, user_id, content_id, properties, timeout=None):
"""Apply decision to content
Args:
user_id: id of user
content_id: id of content
properties:
decision_id: decision to apply to session
source: {one of MANUAL_REVIEW | AUTOMATED_RULE | CHARGEBACK}
analyst: id or email, required if 'source: MANUAL_REVIEW'
description: free form text (optional)
time: in millis when decision was applied (optional)
Returns
A sift.client.Response object if the call succeeded, else raises an ApiException
"""
if timeout is None:
timeout = self.timeout
_assert_non_empty_unicode(content_id, 'content_id')
self._validate_apply_decision_request(properties, user_id)
url = self._content_apply_decisions_url(self.account_id, user_id, content_id)
try:
return Response(self.session.post(
url,
data=json.dumps(properties),
auth=requests.auth.HTTPBasicAuth(self.api_key, ''),
headers={'Content-type': 'application/json',
'Accept': '*/*',
'User-Agent': self._user_agent()},
timeout=timeout))
except requests.exceptions.RequestException as e:
raise ApiException(str(e), url)
def create_psp_merchant_profile(self, properties, timeout=None):
"""Create a new PSP Merchant profile
Args:
properties: A dict of merchant profile data.
Returns
A sift.client.Response object if the call succeeded, else raises an ApiException
"""
if timeout is None:
timeout = self.timeout
url = self._psp_merchant_url(self.account_id)
try:
return Response(self.session.post(
url,
data=json.dumps(properties),
auth=requests.auth.HTTPBasicAuth(self.api_key, ''),
headers={'Content-type': 'application/json',
'Accept': '*/*',
'User-Agent': self._user_agent()},
timeout=timeout))
except requests.exceptions.RequestException as e:
raise ApiException(str(e), url)
def update_psp_merchant_profile(self, merchant_id, properties, timeout=None):
"""Update already existing PSP Merchant profile
Args:
merchant_id: id of merchant
properties: A dict of merchant profile data.
Returns
A sift.client.Response object if the call succeeded, else raises an ApiException
"""
if timeout is None:
timeout = self.timeout
url = self._psp_merchant_id_url(self.account_id, merchant_id)
try:
return Response(self.session.put(
url,
data=json.dumps(properties),
auth=requests.auth.HTTPBasicAuth(self.api_key, ''),
headers={'Content-type': 'application/json',
'Accept': '*/*',
'User-Agent': self._user_agent()},
timeout=timeout))
except requests.exceptions.RequestException as e:
raise ApiException(str(e), url)
def get_psp_merchant_profiles(self, batch_token=None, batch_size=None, timeout=None):
"""Gets all PSP merchant profiles.
Returns:
A sift.client.Response object if the call succeeded.
Otherwise, raises an ApiException.
"""
if timeout is None:
timeout = self.timeout
url = self._psp_merchant_url(self.account_id)
params = {}
if batch_size:
params['batch_size'] = batch_size
if batch_token:
params['batch_token'] = batch_token
try:
return Response(self.session.get(
url,
auth=requests.auth.HTTPBasicAuth(self.api_key, ''),
headers={'User-Agent': self._user_agent()},
params=params,
timeout=timeout))
except requests.exceptions.RequestException as e:
raise ApiException(str(e), url)
def get_a_psp_merchant_profile(self, merchant_id, timeout=None):
"""Gets a PSP merchant profile using merchant id.
Returns:
A sift.client.Response object if the call succeeded.
Otherwise, raises an ApiException.
"""
if timeout is None:
timeout = self.timeout
url = self._psp_merchant_id_url(self.account_id, merchant_id)
try:
return Response(self.session.get(
url,
auth=requests.auth.HTTPBasicAuth(self.api_key, ''),
headers={'User-Agent': self._user_agent()},
timeout=timeout))
except requests.exceptions.RequestException as e:
raise ApiException(str(e), url)
def verification_send(self, properties, timeout=None, version=None):
"""The send call triggers the generation of a OTP code that is stored by Sift and email/sms the code to the user.
This call is blocking. Check out https://sift.com/developers/docs/python/verification-api/send
for more information on our send response structure.
Args:
properties:
$user_id: User ID of user being verified, e.g. johndoe123.
$send_to: The phone / email to send the OTP to.
$verification_type: The channel used for verification. Should be either $email or $sms.
$brand_name(optional): Name of the brand of product or service the user interacts with.
$language(optional): Language of the content of the web site.
$site_country(optional): Country of the content of the site.
$event:
$session_id: The session being verified. See $verification in the Sift Events API documentation.
$verified_event: The type of the reserved event being verified.
$reason(optional): The trigger for the verification. See $verification in the Sift Events API documentation.
$ip(optional): The user's IP address.
$browser:
$user_agent: The user agent of the browser that is verifying. Represented by the $browser object.
Use this field if the client is a browser.
timeout(optional): Use a custom timeout (in seconds) for this call.
version(optional): Use a different version of the Sift Science API for this call.
Returns:
A sift.client.Response object if the send call succeeded, or raises an ApiException.
"""
if timeout is None:
timeout = self.timeout
self._validate_send_request(properties)
url = self._verification_send_url()
try:
return Response(self.session.post(
url,
data=json.dumps(properties),
auth=requests.auth.HTTPBasicAuth(self.api_key, ''),
headers={'Content-type': 'application/json',
'Accept': '*/*',
'User-Agent': self._user_agent()},
timeout=timeout))
except requests.exceptions.RequestException as e:
raise ApiException(str(e), url)
def _validate_send_request(self, properties):
""" This method is used to validate arguments passed to the send method. """
if not isinstance(properties, dict):
raise TypeError("properties must be a dict")
elif not properties:
raise ValueError("properties dictionary may not be empty")
user_id = properties.get('$user_id')
_assert_non_empty_unicode(user_id, 'user_id', error_cls=ValueError)
send_to = properties.get('$send_to')
_assert_non_empty_unicode(send_to, 'send_to', error_cls=ValueError)
verification_type = properties.get('$verification_type')
_assert_non_empty_unicode(
verification_type, 'verification_type', error_cls=ValueError)
event = properties.get('$event')
if not isinstance(event, dict):
raise TypeError("$event must be a dict")
elif not event:
raise ValueError("$event dictionary may not be empty")
session_id = event.get('$session_id')
_assert_non_empty_unicode(
session_id, 'session_id', error_cls=ValueError)
def verification_resend(self, properties, timeout=None, version=None):
"""A user can ask for a new OTP (one-time password) if they haven't received the previous one,
or in case the previous OTP expired.
This call is blocking. Check out https://sift.com/developers/docs/python/verification-api/resend
for more information on our send response structure.
Args:
properties:
$user_id: User ID of user being verified, e.g. johndoe123.
$verified_event(optional): This will be the event type that triggered the verification.
$verified_entity_id(optional): The ID of the entity impacted by the event being verified.
timeout(optional): Use a custom timeout (in seconds) for this call.
version(optional): Use a different version of the Sift Science API for this call.
Returns:
A sift.client.Response object if the send call succeeded, or raises an ApiException.
"""
if timeout is None:
timeout = self.timeout
self._validate_resend_request(properties)
url = self._verification_resend_url()
try:
return Response(self.session.post(
url,
data=json.dumps(properties),
auth=requests.auth.HTTPBasicAuth(self.api_key, ''),
headers={'Content-type': 'application/json',
'Accept': '*/*',
'User-Agent': self._user_agent()},
timeout=timeout))
except requests.exceptions.RequestException as e:
raise ApiException(str(e), url)
def _validate_resend_request(self, properties):
""" This method is used to validate arguments passed to the send method. """
if not isinstance(properties, dict):
raise TypeError("properties must be a dict")
elif not properties:
raise ValueError("properties dictionary may not be empty")
user_id = properties.get('$user_id')
_assert_non_empty_unicode(user_id, 'user_id', error_cls=ValueError)
def verification_check(self, properties, timeout=None, version=None):
"""The verification_check call is used for checking the OTP provided by the end user to Sift.
Sift then compares the OTP, checks rate limits and responds with a decision whether the user should be able to proceed or not.
This call is blocking. Check out https://sift.com/developers/docs/python/verification-api/check
for more information on our check response structure.
Args:
properties:
$user_id: User ID of user being verified, e.g. johndoe123.
$code: The code the user sent to the customer for validation..
$verified_event(optional): This will be the event type that triggered the verification.