Spaces:
Sleeping
Sleeping
Update paypal_integration.py
Browse files- paypal_integration.py +1008 -1004
paypal_integration.py
CHANGED
@@ -1,1004 +1,1008 @@
|
|
1 |
-
import requests
|
2 |
-
import json
|
3 |
-
import sqlite3
|
4 |
-
from datetime import datetime, timedelta
|
5 |
-
import uuid
|
6 |
-
import os
|
7 |
-
import logging
|
8 |
-
from requests.adapters import HTTPAdapter
|
9 |
-
from requests.packages.urllib3.util.retry import Retry
|
10 |
-
from auth import get_db_connection
|
11 |
-
from dotenv import load_dotenv
|
12 |
-
|
13 |
-
# PayPal API Configuration - Remove default values for production
|
14 |
-
PAYPAL_CLIENT_ID = os.getenv("PAYPAL_CLIENT_ID")
|
15 |
-
PAYPAL_SECRET = os.getenv("PAYPAL_SECRET")
|
16 |
-
PAYPAL_BASE_URL = os.getenv("PAYPAL_BASE_URL", "https://api-m.sandbox.paypal.com")
|
17 |
-
|
18 |
-
# Add validation to ensure credentials are provided
|
19 |
-
# Set up logging
|
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 |
-
response = session.
|
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 |
-
return
|
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 |
-
if "
|
568 |
-
logger.info("Adding '
|
569 |
-
cursor.execute("ALTER TABLE subscriptions ADD COLUMN
|
570 |
-
|
571 |
-
if "
|
572 |
-
logger.info("Adding '
|
573 |
-
cursor.execute("ALTER TABLE subscriptions ADD COLUMN
|
574 |
-
|
575 |
-
if "
|
576 |
-
logger.info("Adding '
|
577 |
-
cursor.execute("ALTER TABLE subscriptions ADD COLUMN
|
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 |
-
logger.
|
718 |
-
return {}
|
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 |
-
logger.error("
|
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 |
-
return
|
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 |
-
return
|
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 |
-
|
1001 |
-
|
1002 |
-
|
1003 |
-
|
1004 |
-
|
|
|
|
|
|
|
|
|
|
1 |
+
import requests
|
2 |
+
import json
|
3 |
+
import sqlite3
|
4 |
+
from datetime import datetime, timedelta
|
5 |
+
import uuid
|
6 |
+
import os
|
7 |
+
import logging
|
8 |
+
from requests.adapters import HTTPAdapter
|
9 |
+
from requests.packages.urllib3.util.retry import Retry
|
10 |
+
from auth import get_db_connection
|
11 |
+
from dotenv import load_dotenv
|
12 |
+
|
13 |
+
# PayPal API Configuration - Remove default values for production
|
14 |
+
PAYPAL_CLIENT_ID = os.getenv("PAYPAL_CLIENT_ID")
|
15 |
+
PAYPAL_SECRET = os.getenv("PAYPAL_SECRET")
|
16 |
+
PAYPAL_BASE_URL = os.getenv("PAYPAL_BASE_URL", "https://api-m.sandbox.paypal.com")
|
17 |
+
|
18 |
+
# Add validation to ensure credentials are provided
|
19 |
+
# Set up logging
|
20 |
+
LOG_DIR = os.path.abspath("/tmp/logs")
|
21 |
+
os.makedirs(LOG_DIR, exist_ok=True)
|
22 |
+
LOG_FILE = os.path.join(LOG_DIR, "paypal.log")
|
23 |
+
|
24 |
+
logging.basicConfig(
|
25 |
+
level=logging.INFO,
|
26 |
+
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
27 |
+
handlers=[
|
28 |
+
logging.FileHandler(LOG_FILE),
|
29 |
+
logging.StreamHandler()
|
30 |
+
]
|
31 |
+
)
|
32 |
+
logger = logging.getLogger("paypal_integration")
|
33 |
+
|
34 |
+
# Then replace print statements with logger calls
|
35 |
+
# For example:
|
36 |
+
if not PAYPAL_CLIENT_ID or not PAYPAL_SECRET:
|
37 |
+
logger.warning("PayPal credentials not found in environment variables")
|
38 |
+
|
39 |
+
|
40 |
+
# Get PayPal access token
|
41 |
+
# Add better error handling for production
|
42 |
+
# Create a session with retry capability
|
43 |
+
def create_retry_session(retries=3, backoff_factor=0.3):
|
44 |
+
session = requests.Session()
|
45 |
+
retry = Retry(
|
46 |
+
total=retries,
|
47 |
+
read=retries,
|
48 |
+
connect=retries,
|
49 |
+
backoff_factor=backoff_factor,
|
50 |
+
status_forcelist=[500, 502, 503, 504],
|
51 |
+
)
|
52 |
+
adapter = HTTPAdapter(max_retries=retry)
|
53 |
+
session.mount('http://', adapter)
|
54 |
+
session.mount('https://', adapter)
|
55 |
+
return session
|
56 |
+
|
57 |
+
# Then use this session for API calls
|
58 |
+
# Replace get_access_token with logger instead of print
|
59 |
+
def get_access_token():
|
60 |
+
url = f"{PAYPAL_BASE_URL}/v1/oauth2/token"
|
61 |
+
headers = {
|
62 |
+
"Accept": "application/json",
|
63 |
+
"Accept-Language": "en_US"
|
64 |
+
}
|
65 |
+
data = "grant_type=client_credentials"
|
66 |
+
|
67 |
+
try:
|
68 |
+
session = create_retry_session()
|
69 |
+
response = session.post(
|
70 |
+
url,
|
71 |
+
auth=(PAYPAL_CLIENT_ID, PAYPAL_SECRET),
|
72 |
+
headers=headers,
|
73 |
+
data=data
|
74 |
+
)
|
75 |
+
|
76 |
+
if response.status_code == 200:
|
77 |
+
return response.json()["access_token"]
|
78 |
+
else:
|
79 |
+
logger.error(f"Error getting access token: {response.status_code}")
|
80 |
+
return None
|
81 |
+
except Exception as e:
|
82 |
+
logger.error(f"Exception in get_access_token: {str(e)}")
|
83 |
+
return None
|
84 |
+
|
85 |
+
def call_paypal_api(endpoint, method="GET", data=None, token=None):
|
86 |
+
"""
|
87 |
+
Helper function to make PayPal API calls
|
88 |
+
|
89 |
+
Args:
|
90 |
+
endpoint: API endpoint (without base URL)
|
91 |
+
method: HTTP method (GET, POST, etc.)
|
92 |
+
data: Request payload (for POST/PUT)
|
93 |
+
token: PayPal access token (will be fetched if None)
|
94 |
+
|
95 |
+
Returns:
|
96 |
+
tuple: (success, response_data or error_message)
|
97 |
+
"""
|
98 |
+
try:
|
99 |
+
if not token:
|
100 |
+
token = get_access_token()
|
101 |
+
if not token:
|
102 |
+
return False, "Failed to get PayPal access token"
|
103 |
+
|
104 |
+
url = f"{PAYPAL_BASE_URL}{endpoint}"
|
105 |
+
headers = {
|
106 |
+
"Content-Type": "application/json",
|
107 |
+
"Authorization": f"Bearer {token}"
|
108 |
+
}
|
109 |
+
|
110 |
+
session = create_retry_session()
|
111 |
+
|
112 |
+
if method.upper() == "GET":
|
113 |
+
response = session.get(url, headers=headers)
|
114 |
+
elif method.upper() == "POST":
|
115 |
+
response = session.post(url, headers=headers, data=json.dumps(data) if data else None)
|
116 |
+
elif method.upper() == "PUT":
|
117 |
+
response = session.put(url, headers=headers, data=json.dumps(data) if data else None)
|
118 |
+
else:
|
119 |
+
return False, f"Unsupported HTTP method: {method}"
|
120 |
+
|
121 |
+
if response.status_code in [200, 201, 204]:
|
122 |
+
if response.status_code == 204: # No content
|
123 |
+
return True, {}
|
124 |
+
return True, response.json() if response.text else {}
|
125 |
+
else:
|
126 |
+
logger.error(f"PayPal API error: {response.status_code} - {response.text}")
|
127 |
+
return False, f"PayPal API error: {response.status_code} - {response.text}"
|
128 |
+
|
129 |
+
except Exception as e:
|
130 |
+
logger.error(f"Error calling PayPal API: {str(e)}")
|
131 |
+
return False, f"Error calling PayPal API: {str(e)}"
|
132 |
+
|
133 |
+
def create_paypal_subscription(user_id, tier):
|
134 |
+
"""Create a PayPal subscription for a user"""
|
135 |
+
try:
|
136 |
+
# Get the price from the subscription tier
|
137 |
+
from auth import SUBSCRIPTION_TIERS
|
138 |
+
|
139 |
+
if tier not in SUBSCRIPTION_TIERS:
|
140 |
+
return False, f"Invalid tier: {tier}"
|
141 |
+
|
142 |
+
price = SUBSCRIPTION_TIERS[tier]["price"]
|
143 |
+
currency = SUBSCRIPTION_TIERS[tier]["currency"]
|
144 |
+
|
145 |
+
# Create a PayPal subscription (implement PayPal API calls here)
|
146 |
+
# For now, just return a success response
|
147 |
+
return True, {
|
148 |
+
"subscription_id": f"test_sub_{uuid.uuid4()}",
|
149 |
+
"status": "ACTIVE",
|
150 |
+
"tier": tier,
|
151 |
+
"price": price,
|
152 |
+
"currency": currency
|
153 |
+
}
|
154 |
+
except Exception as e:
|
155 |
+
logger.error(f"Error creating PayPal subscription: {str(e)}")
|
156 |
+
return False, f"Failed to create PayPal subscription: {str(e)}"
|
157 |
+
|
158 |
+
|
159 |
+
# Create a product in PayPal
|
160 |
+
def create_product(name, description):
|
161 |
+
"""Create a product in PayPal"""
|
162 |
+
payload = {
|
163 |
+
"name": name,
|
164 |
+
"description": description,
|
165 |
+
"type": "SERVICE",
|
166 |
+
"category": "SOFTWARE"
|
167 |
+
}
|
168 |
+
|
169 |
+
success, result = call_paypal_api("/v1/catalogs/products", "POST", payload)
|
170 |
+
if success:
|
171 |
+
return result["id"]
|
172 |
+
else:
|
173 |
+
logger.error(f"Failed to create product: {result}")
|
174 |
+
return None
|
175 |
+
|
176 |
+
# Create a subscription plan in PayPal
|
177 |
+
# Update create_plan to use INR instead of USD
|
178 |
+
def create_plan(product_id, name, price, interval="MONTH", interval_count=1):
|
179 |
+
"""Create a subscription plan in PayPal"""
|
180 |
+
payload = {
|
181 |
+
"product_id": product_id,
|
182 |
+
"name": name,
|
183 |
+
"billing_cycles": [
|
184 |
+
{
|
185 |
+
"frequency": {
|
186 |
+
"interval_unit": interval,
|
187 |
+
"interval_count": interval_count
|
188 |
+
},
|
189 |
+
"tenure_type": "REGULAR",
|
190 |
+
"sequence": 1,
|
191 |
+
"total_cycles": 0, # Infinite cycles
|
192 |
+
"pricing_scheme": {
|
193 |
+
"fixed_price": {
|
194 |
+
"value": str(price),
|
195 |
+
"currency_code": "USD"
|
196 |
+
}
|
197 |
+
}
|
198 |
+
}
|
199 |
+
],
|
200 |
+
"payment_preferences": {
|
201 |
+
"auto_bill_outstanding": True,
|
202 |
+
"setup_fee": {
|
203 |
+
"value": "0",
|
204 |
+
"currency_code": "USD"
|
205 |
+
},
|
206 |
+
"setup_fee_failure_action": "CONTINUE",
|
207 |
+
"payment_failure_threshold": 3
|
208 |
+
}
|
209 |
+
}
|
210 |
+
|
211 |
+
success, result = call_paypal_api("/v1/billing/plans", "POST", payload)
|
212 |
+
if success:
|
213 |
+
return result["id"]
|
214 |
+
else:
|
215 |
+
logger.error(f"Failed to create plan: {result}")
|
216 |
+
return None
|
217 |
+
|
218 |
+
# Update initialize_subscription_plans to use INR pricing
|
219 |
+
def initialize_subscription_plans():
|
220 |
+
"""
|
221 |
+
Initialize PayPal subscription plans for the application.
|
222 |
+
This should be called once to set up the plans in PayPal.
|
223 |
+
"""
|
224 |
+
try:
|
225 |
+
# Check if plans already exist
|
226 |
+
existing_plans = get_subscription_plans()
|
227 |
+
if existing_plans and len(existing_plans) >= 2:
|
228 |
+
logger.info("PayPal plans already initialized")
|
229 |
+
return existing_plans
|
230 |
+
|
231 |
+
# First, create products for each tier
|
232 |
+
products = {
|
233 |
+
"standard_tier": {
|
234 |
+
"name": "Standard Legal Document Analysis",
|
235 |
+
"description": "Standard subscription with document analysis features",
|
236 |
+
"type": "SERVICE",
|
237 |
+
"category": "SOFTWARE"
|
238 |
+
},
|
239 |
+
"premium_tier": {
|
240 |
+
"name": "Premium Legal Document Analysis",
|
241 |
+
"description": "Premium subscription with all document analysis features",
|
242 |
+
"type": "SERVICE",
|
243 |
+
"category": "SOFTWARE"
|
244 |
+
}
|
245 |
+
}
|
246 |
+
|
247 |
+
product_ids = {}
|
248 |
+
for tier, product_data in products.items():
|
249 |
+
success, result = call_paypal_api("/v1/catalogs/products", "POST", product_data)
|
250 |
+
if success:
|
251 |
+
product_ids[tier] = result["id"]
|
252 |
+
logger.info(f"Created PayPal product for {tier}: {result['id']}")
|
253 |
+
else:
|
254 |
+
logger.error(f"Failed to create product for {tier}: {result}")
|
255 |
+
return None
|
256 |
+
|
257 |
+
# Define the plans with product IDs - Changed currency to USD
|
258 |
+
plans = {
|
259 |
+
"standard_tier": {
|
260 |
+
"product_id": product_ids["standard_tier"],
|
261 |
+
"name": "Standard Plan",
|
262 |
+
"description": "Standard subscription with basic features",
|
263 |
+
"billing_cycles": [
|
264 |
+
{
|
265 |
+
"frequency": {
|
266 |
+
"interval_unit": "MONTH",
|
267 |
+
"interval_count": 1
|
268 |
+
},
|
269 |
+
"tenure_type": "REGULAR",
|
270 |
+
"sequence": 1,
|
271 |
+
"total_cycles": 0,
|
272 |
+
"pricing_scheme": {
|
273 |
+
"fixed_price": {
|
274 |
+
"value": "9.99",
|
275 |
+
"currency_code": "USD"
|
276 |
+
}
|
277 |
+
}
|
278 |
+
}
|
279 |
+
],
|
280 |
+
"payment_preferences": {
|
281 |
+
"auto_bill_outstanding": True,
|
282 |
+
"setup_fee": {
|
283 |
+
"value": "0",
|
284 |
+
"currency_code": "USD"
|
285 |
+
},
|
286 |
+
"setup_fee_failure_action": "CONTINUE",
|
287 |
+
"payment_failure_threshold": 3
|
288 |
+
}
|
289 |
+
},
|
290 |
+
"premium_tier": {
|
291 |
+
"product_id": product_ids["premium_tier"],
|
292 |
+
"name": "Premium Plan",
|
293 |
+
"description": "Premium subscription with all features",
|
294 |
+
"billing_cycles": [
|
295 |
+
{
|
296 |
+
"frequency": {
|
297 |
+
"interval_unit": "MONTH",
|
298 |
+
"interval_count": 1
|
299 |
+
},
|
300 |
+
"tenure_type": "REGULAR",
|
301 |
+
"sequence": 1,
|
302 |
+
"total_cycles": 0,
|
303 |
+
"pricing_scheme": {
|
304 |
+
"fixed_price": {
|
305 |
+
"value": "19.99",
|
306 |
+
"currency_code": "USD"
|
307 |
+
}
|
308 |
+
}
|
309 |
+
}
|
310 |
+
],
|
311 |
+
"payment_preferences": {
|
312 |
+
"auto_bill_outstanding": True,
|
313 |
+
"setup_fee": {
|
314 |
+
"value": "0",
|
315 |
+
"currency_code": "USD"
|
316 |
+
},
|
317 |
+
"setup_fee_failure_action": "CONTINUE",
|
318 |
+
"payment_failure_threshold": 3
|
319 |
+
}
|
320 |
+
}
|
321 |
+
}
|
322 |
+
|
323 |
+
# Create the plans in PayPal
|
324 |
+
created_plans = {}
|
325 |
+
for tier, plan_data in plans.items():
|
326 |
+
success, result = call_paypal_api("/v1/billing/plans", "POST", plan_data)
|
327 |
+
if success:
|
328 |
+
created_plans[tier] = result["id"]
|
329 |
+
logger.info(f"Created PayPal plan for {tier}: {result['id']}")
|
330 |
+
else:
|
331 |
+
logger.error(f"Failed to create plan for {tier}: {result}")
|
332 |
+
|
333 |
+
# Save the plan IDs to a file
|
334 |
+
if created_plans:
|
335 |
+
save_subscription_plans(created_plans)
|
336 |
+
return created_plans
|
337 |
+
else:
|
338 |
+
logger.error("Failed to create any PayPal plans")
|
339 |
+
return None
|
340 |
+
except Exception as e:
|
341 |
+
logger.error(f"Error initializing subscription plans: {str(e)}")
|
342 |
+
return None
|
343 |
+
|
344 |
+
# Update create_subscription_link to use call_paypal_api helper
|
345 |
+
def create_subscription_link(plan_id):
|
346 |
+
# Get the plan IDs
|
347 |
+
plans = get_subscription_plans()
|
348 |
+
if not plans:
|
349 |
+
return None
|
350 |
+
|
351 |
+
# Use environment variable for the app URL to make it work in different environments
|
352 |
+
app_url = os.getenv("APP_URL", "http://localhost:8501")
|
353 |
+
|
354 |
+
payload = {
|
355 |
+
"plan_id": plans[plan_id],
|
356 |
+
"application_context": {
|
357 |
+
"brand_name": "Legal Document Analyzer",
|
358 |
+
"locale": "en_US",
|
359 |
+
"shipping_preference": "NO_SHIPPING",
|
360 |
+
"user_action": "SUBSCRIBE_NOW",
|
361 |
+
"return_url": f"{app_url}?status=success&subscription_id={{id}}",
|
362 |
+
"cancel_url": f"{app_url}?status=cancel"
|
363 |
+
}
|
364 |
+
}
|
365 |
+
|
366 |
+
success, data = call_paypal_api("/v1/billing/subscriptions", "POST", payload)
|
367 |
+
if not success:
|
368 |
+
logger.error(f"Error creating subscription: {data}")
|
369 |
+
return None
|
370 |
+
|
371 |
+
try:
|
372 |
+
return {
|
373 |
+
"subscription_id": data["id"],
|
374 |
+
"approval_url": next(link["href"] for link in data["links"] if link["rel"] == "approve")
|
375 |
+
}
|
376 |
+
except Exception as e:
|
377 |
+
logger.error(f"Exception processing subscription response: {str(e)}")
|
378 |
+
return None
|
379 |
+
|
380 |
+
# Fix the webhook handler function signature to match how it's called in app.py
|
381 |
+
def handle_subscription_webhook(payload):
|
382 |
+
"""
|
383 |
+
Handle PayPal subscription webhooks
|
384 |
+
|
385 |
+
Args:
|
386 |
+
payload: The full webhook payload
|
387 |
+
|
388 |
+
Returns:
|
389 |
+
tuple: (success, result)
|
390 |
+
- success: True if successful, False otherwise
|
391 |
+
- result: Success message or error message
|
392 |
+
"""
|
393 |
+
try:
|
394 |
+
event_type = payload.get("event_type")
|
395 |
+
resource = payload.get("resource", {})
|
396 |
+
|
397 |
+
logger.info(f"Received PayPal webhook: {event_type}")
|
398 |
+
|
399 |
+
# Handle different event types
|
400 |
+
if event_type == "BILLING.SUBSCRIPTION.CREATED":
|
401 |
+
# A subscription was created
|
402 |
+
subscription_id = resource.get("id")
|
403 |
+
if not subscription_id:
|
404 |
+
return False, "Missing subscription ID in webhook"
|
405 |
+
|
406 |
+
# Update subscription status in database
|
407 |
+
conn = get_db_connection()
|
408 |
+
cursor = conn.cursor()
|
409 |
+
cursor.execute(
|
410 |
+
"UPDATE subscriptions SET status = 'pending' WHERE paypal_subscription_id = ?",
|
411 |
+
(subscription_id,)
|
412 |
+
)
|
413 |
+
conn.commit()
|
414 |
+
conn.close()
|
415 |
+
|
416 |
+
return True, "Subscription created successfully"
|
417 |
+
|
418 |
+
elif event_type == "BILLING.SUBSCRIPTION.ACTIVATED":
|
419 |
+
# A subscription was activated
|
420 |
+
subscription_id = resource.get("id")
|
421 |
+
if not subscription_id:
|
422 |
+
return False, "Missing subscription ID in webhook"
|
423 |
+
|
424 |
+
# Update subscription status in database
|
425 |
+
conn = get_db_connection()
|
426 |
+
cursor = conn.cursor()
|
427 |
+
cursor.execute(
|
428 |
+
"UPDATE subscriptions SET status = 'active' WHERE paypal_subscription_id = ?",
|
429 |
+
(subscription_id,)
|
430 |
+
)
|
431 |
+
conn.commit()
|
432 |
+
conn.close()
|
433 |
+
|
434 |
+
return True, "Subscription activated successfully"
|
435 |
+
|
436 |
+
elif event_type == "BILLING.SUBSCRIPTION.CANCELLED":
|
437 |
+
# A subscription was cancelled
|
438 |
+
subscription_id = resource.get("id")
|
439 |
+
if not subscription_id:
|
440 |
+
return False, "Missing subscription ID in webhook"
|
441 |
+
|
442 |
+
# Update subscription status in database
|
443 |
+
conn = get_db_connection()
|
444 |
+
cursor = conn.cursor()
|
445 |
+
cursor.execute(
|
446 |
+
"UPDATE subscriptions SET status = 'cancelled' WHERE paypal_subscription_id = ?",
|
447 |
+
(subscription_id,)
|
448 |
+
)
|
449 |
+
conn.commit()
|
450 |
+
conn.close()
|
451 |
+
|
452 |
+
return True, "Subscription cancelled successfully"
|
453 |
+
|
454 |
+
elif event_type == "BILLING.SUBSCRIPTION.SUSPENDED":
|
455 |
+
# A subscription was suspended
|
456 |
+
subscription_id = resource.get("id")
|
457 |
+
if not subscription_id:
|
458 |
+
return False, "Missing subscription ID in webhook"
|
459 |
+
|
460 |
+
# Update subscription status in database
|
461 |
+
conn = get_db_connection()
|
462 |
+
cursor = conn.cursor()
|
463 |
+
cursor.execute(
|
464 |
+
"UPDATE subscriptions SET status = 'suspended' WHERE paypal_subscription_id = ?",
|
465 |
+
(subscription_id,)
|
466 |
+
)
|
467 |
+
conn.commit()
|
468 |
+
conn.close()
|
469 |
+
|
470 |
+
return True, "Subscription suspended successfully"
|
471 |
+
|
472 |
+
else:
|
473 |
+
# Unhandled event type
|
474 |
+
logger.info(f"Unhandled webhook event type: {event_type}")
|
475 |
+
return True, f"Unhandled event type: {event_type}"
|
476 |
+
|
477 |
+
except Exception as e:
|
478 |
+
logger.error(f"Error handling webhook: {str(e)}")
|
479 |
+
return False, f"Error handling webhook: {str(e)}"
|
480 |
+
# Add this function to update user subscription
|
481 |
+
def update_user_subscription(user_email, subscription_id, tier):
|
482 |
+
"""
|
483 |
+
Update a user's subscription status
|
484 |
+
|
485 |
+
Args:
|
486 |
+
user_email: The email of the user
|
487 |
+
subscription_id: The PayPal subscription ID
|
488 |
+
tier: The subscription tier
|
489 |
+
|
490 |
+
Returns:
|
491 |
+
tuple: (success, result)
|
492 |
+
- success: True if successful, False otherwise
|
493 |
+
- result: Success message or error message
|
494 |
+
"""
|
495 |
+
try:
|
496 |
+
# Get user ID from email
|
497 |
+
conn = get_db_connection()
|
498 |
+
cursor = conn.cursor()
|
499 |
+
cursor.execute("SELECT id FROM users WHERE email = ?", (user_email,))
|
500 |
+
user_result = cursor.fetchone()
|
501 |
+
|
502 |
+
if not user_result:
|
503 |
+
conn.close()
|
504 |
+
return False, f"User not found: {user_email}"
|
505 |
+
|
506 |
+
user_id = user_result[0]
|
507 |
+
|
508 |
+
# Update the subscription status
|
509 |
+
cursor.execute(
|
510 |
+
"UPDATE subscriptions SET status = 'active' WHERE user_id = ? AND paypal_subscription_id = ?",
|
511 |
+
(user_id, subscription_id)
|
512 |
+
)
|
513 |
+
|
514 |
+
# Deactivate any other active subscriptions for this user
|
515 |
+
cursor.execute(
|
516 |
+
"UPDATE subscriptions SET status = 'inactive' WHERE user_id = ? AND paypal_subscription_id != ? AND status = 'active'",
|
517 |
+
(user_id, subscription_id)
|
518 |
+
)
|
519 |
+
|
520 |
+
# Update the user's subscription tier
|
521 |
+
cursor.execute(
|
522 |
+
"UPDATE users SET subscription_tier = ? WHERE email = ?",
|
523 |
+
(tier, user_email)
|
524 |
+
)
|
525 |
+
|
526 |
+
conn.commit()
|
527 |
+
conn.close()
|
528 |
+
|
529 |
+
return True, f"Subscription updated to {tier} tier"
|
530 |
+
|
531 |
+
except Exception as e:
|
532 |
+
logger.error(f"Error updating user subscription: {str(e)}")
|
533 |
+
return False, f"Error updating subscription: {str(e)}"
|
534 |
+
|
535 |
+
# Add this near the top with other path definitions
|
536 |
+
# Update the PLAN_IDS_PATH definition to use the correct path
|
537 |
+
PLAN_IDS_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "data", "plan_ids.json"))
|
538 |
+
|
539 |
+
# Make sure the data directory exists
|
540 |
+
os.makedirs(os.path.dirname(PLAN_IDS_PATH), exist_ok=True)
|
541 |
+
|
542 |
+
# Add this debug log to see where the file is expected
|
543 |
+
logger.info(f"PayPal plans will be stored at: {PLAN_IDS_PATH}")
|
544 |
+
|
545 |
+
# Add this function if it's not defined elsewhere
|
546 |
+
def get_db_connection():
|
547 |
+
"""Get a connection to the SQLite database"""
|
548 |
+
DB_PATH = os.getenv("DB_PATH", os.path.join(os.path.dirname(__file__), "../data/user_data.db"))
|
549 |
+
# Make sure the data directory exists
|
550 |
+
os.makedirs(os.path.dirname(DB_PATH), exist_ok=True)
|
551 |
+
return sqlite3.connect(DB_PATH)
|
552 |
+
|
553 |
+
# Add this function to create subscription tables if needed
|
554 |
+
def initialize_database():
|
555 |
+
"""Initialize the database tables needed for subscriptions"""
|
556 |
+
conn = get_db_connection()
|
557 |
+
cursor = conn.cursor()
|
558 |
+
|
559 |
+
# Check if subscriptions table exists
|
560 |
+
cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='subscriptions'")
|
561 |
+
if cursor.fetchone():
|
562 |
+
# Table exists, check if required columns exist
|
563 |
+
cursor.execute("PRAGMA table_info(subscriptions)")
|
564 |
+
columns = [column[1] for column in cursor.fetchall()]
|
565 |
+
|
566 |
+
# Check for missing columns and add them if needed
|
567 |
+
if "user_id" not in columns:
|
568 |
+
logger.info("Adding 'user_id' column to subscriptions table")
|
569 |
+
cursor.execute("ALTER TABLE subscriptions ADD COLUMN user_id TEXT NOT NULL DEFAULT ''")
|
570 |
+
|
571 |
+
if "created_at" not in columns:
|
572 |
+
logger.info("Adding 'created_at' column to subscriptions table")
|
573 |
+
cursor.execute("ALTER TABLE subscriptions ADD COLUMN created_at TIMESTAMP")
|
574 |
+
|
575 |
+
if "expires_at" not in columns:
|
576 |
+
logger.info("Adding 'expires_at' column to subscriptions table")
|
577 |
+
cursor.execute("ALTER TABLE subscriptions ADD COLUMN expires_at TIMESTAMP")
|
578 |
+
|
579 |
+
if "paypal_subscription_id" not in columns:
|
580 |
+
logger.info("Adding 'paypal_subscription_id' column to subscriptions table")
|
581 |
+
cursor.execute("ALTER TABLE subscriptions ADD COLUMN paypal_subscription_id TEXT")
|
582 |
+
else:
|
583 |
+
# Create subscriptions table with all required columns
|
584 |
+
cursor.execute('''
|
585 |
+
CREATE TABLE IF NOT EXISTS subscriptions (
|
586 |
+
id TEXT PRIMARY KEY,
|
587 |
+
user_id TEXT NOT NULL,
|
588 |
+
tier TEXT NOT NULL,
|
589 |
+
status TEXT NOT NULL,
|
590 |
+
created_at TIMESTAMP NOT NULL,
|
591 |
+
expires_at TIMESTAMP,
|
592 |
+
paypal_subscription_id TEXT
|
593 |
+
)
|
594 |
+
''')
|
595 |
+
logger.info("Created subscriptions table with all required columns")
|
596 |
+
|
597 |
+
# Create PayPal plans table if it doesn't exist
|
598 |
+
cursor.execute('''
|
599 |
+
CREATE TABLE IF NOT EXISTS paypal_plans (
|
600 |
+
plan_id TEXT PRIMARY KEY,
|
601 |
+
tier TEXT NOT NULL,
|
602 |
+
price REAL NOT NULL,
|
603 |
+
currency TEXT NOT NULL,
|
604 |
+
created_at TIMESTAMP NOT NULL
|
605 |
+
)
|
606 |
+
''')
|
607 |
+
|
608 |
+
conn.commit()
|
609 |
+
conn.close()
|
610 |
+
logger.info("Database initialization completed")
|
611 |
+
|
612 |
+
|
613 |
+
def create_user_subscription_mock(user_email, tier):
|
614 |
+
"""
|
615 |
+
Create a mock subscription for testing
|
616 |
+
|
617 |
+
Args:
|
618 |
+
user_email: The email of the user
|
619 |
+
tier: The subscription tier
|
620 |
+
|
621 |
+
Returns:
|
622 |
+
tuple: (success, result)
|
623 |
+
"""
|
624 |
+
try:
|
625 |
+
logger.info(f"Creating mock subscription for {user_email} at tier {tier}")
|
626 |
+
|
627 |
+
# Get user ID from email
|
628 |
+
conn = get_db_connection()
|
629 |
+
cursor = conn.cursor()
|
630 |
+
cursor.execute("SELECT id FROM users WHERE email = ?", (user_email,))
|
631 |
+
user_result = cursor.fetchone()
|
632 |
+
|
633 |
+
if not user_result:
|
634 |
+
conn.close()
|
635 |
+
return False, f"User not found: {user_email}"
|
636 |
+
|
637 |
+
user_id = user_result[0]
|
638 |
+
|
639 |
+
# Create a mock subscription ID
|
640 |
+
subscription_id = f"mock_sub_{uuid.uuid4()}"
|
641 |
+
|
642 |
+
# Store the subscription in database
|
643 |
+
sub_id = str(uuid.uuid4())
|
644 |
+
start_date = datetime.now()
|
645 |
+
|
646 |
+
cursor.execute(
|
647 |
+
"INSERT INTO subscriptions (id, user_id, tier, status, created_at, expires_at, paypal_subscription_id) VALUES (?, ?, ?, ?, ?, ?, ?)",
|
648 |
+
(sub_id, user_id, tier, "active", start_date, start_date + timedelta(days=30), subscription_id)
|
649 |
+
)
|
650 |
+
|
651 |
+
# Update user's subscription tier
|
652 |
+
cursor.execute(
|
653 |
+
"UPDATE users SET subscription_tier = ? WHERE id = ?",
|
654 |
+
(tier, user_id)
|
655 |
+
)
|
656 |
+
|
657 |
+
conn.commit()
|
658 |
+
conn.close()
|
659 |
+
|
660 |
+
# Use environment variable for the app URL
|
661 |
+
app_url = os.getenv("APP_URL", "http://localhost:3000")
|
662 |
+
|
663 |
+
# Return success with mock approval URL that matches the real PayPal URL pattern
|
664 |
+
return True, {
|
665 |
+
"subscription_id": subscription_id,
|
666 |
+
"approval_url": f"{app_url}/subscription/callback?status=success&subscription_id={subscription_id}",
|
667 |
+
"tier": tier
|
668 |
+
}
|
669 |
+
|
670 |
+
except Exception as e:
|
671 |
+
logger.error(f"Error creating mock subscription: {str(e)}")
|
672 |
+
return False, f"Error creating subscription: {str(e)}"
|
673 |
+
|
674 |
+
# Add this at the end of the file
|
675 |
+
def initialize():
|
676 |
+
"""Initialize the PayPal integration module"""
|
677 |
+
try:
|
678 |
+
# Create necessary directories
|
679 |
+
os.makedirs(os.path.dirname(PLAN_IDS_PATH), exist_ok=True)
|
680 |
+
|
681 |
+
# Initialize database
|
682 |
+
initialize_database()
|
683 |
+
|
684 |
+
# Initialize subscription plans
|
685 |
+
plans = get_subscription_plans()
|
686 |
+
if plans:
|
687 |
+
logger.info(f"Subscription plans initialized: {plans}")
|
688 |
+
else:
|
689 |
+
logger.warning("Failed to initialize subscription plans")
|
690 |
+
|
691 |
+
return True
|
692 |
+
except Exception as e:
|
693 |
+
logger.error(f"Error initializing PayPal integration: {str(e)}")
|
694 |
+
return False
|
695 |
+
|
696 |
+
# Call initialize when the module is imported
|
697 |
+
initialize()
|
698 |
+
|
699 |
+
# Add this function to get subscription plans
|
700 |
+
def get_subscription_plans():
|
701 |
+
"""
|
702 |
+
Get all available subscription plans with correct pricing
|
703 |
+
"""
|
704 |
+
try:
|
705 |
+
# Check if we have plan IDs saved in a file
|
706 |
+
if os.path.exists(PLAN_IDS_PATH):
|
707 |
+
try:
|
708 |
+
with open(PLAN_IDS_PATH, 'r') as f:
|
709 |
+
plans = json.load(f)
|
710 |
+
logger.info(f"Loaded subscription plans from {PLAN_IDS_PATH}: {plans}")
|
711 |
+
return plans
|
712 |
+
except Exception as e:
|
713 |
+
logger.error(f"Error reading plan IDs file: {str(e)}")
|
714 |
+
return {}
|
715 |
+
|
716 |
+
# If no file exists, return empty dict
|
717 |
+
logger.warning(f"No plan IDs file found at {PLAN_IDS_PATH}. Please initialize subscription plans.")
|
718 |
+
return {}
|
719 |
+
|
720 |
+
except Exception as e:
|
721 |
+
logger.error(f"Error getting subscription plans: {str(e)}")
|
722 |
+
return {}
|
723 |
+
|
724 |
+
# Add this function to create subscription tables if needed
|
725 |
+
def initialize_database():
|
726 |
+
"""Initialize the database tables needed for subscriptions"""
|
727 |
+
conn = get_db_connection()
|
728 |
+
cursor = conn.cursor()
|
729 |
+
|
730 |
+
# Create subscriptions table if it doesn't exist
|
731 |
+
cursor.execute('''
|
732 |
+
CREATE TABLE IF NOT EXISTS subscriptions (
|
733 |
+
id TEXT PRIMARY KEY,
|
734 |
+
user_id TEXT NOT NULL,
|
735 |
+
tier TEXT NOT NULL,
|
736 |
+
status TEXT NOT NULL,
|
737 |
+
created_at TIMESTAMP NOT NULL,
|
738 |
+
expires_at TIMESTAMP,
|
739 |
+
paypal_subscription_id TEXT
|
740 |
+
)
|
741 |
+
''')
|
742 |
+
|
743 |
+
# Create PayPal plans table if it doesn't exist
|
744 |
+
cursor.execute('''
|
745 |
+
CREATE TABLE IF NOT EXISTS paypal_plans (
|
746 |
+
plan_id TEXT PRIMARY KEY,
|
747 |
+
tier TEXT NOT NULL,
|
748 |
+
price REAL NOT NULL,
|
749 |
+
currency TEXT NOT NULL,
|
750 |
+
created_at TIMESTAMP NOT NULL
|
751 |
+
)
|
752 |
+
''')
|
753 |
+
|
754 |
+
conn.commit()
|
755 |
+
conn.close()
|
756 |
+
|
757 |
+
|
758 |
+
def create_user_subscription(user_email, tier):
|
759 |
+
"""
|
760 |
+
Create a real PayPal subscription for a user
|
761 |
+
|
762 |
+
Args:
|
763 |
+
user_email: The email of the user
|
764 |
+
tier: The subscription tier (standard_tier or premium_tier)
|
765 |
+
|
766 |
+
Returns:
|
767 |
+
tuple: (success, result)
|
768 |
+
- success: True if successful, False otherwise
|
769 |
+
- result: Dictionary with subscription details or error message
|
770 |
+
"""
|
771 |
+
try:
|
772 |
+
# Validate tier
|
773 |
+
valid_tiers = ["standard_tier", "premium_tier"]
|
774 |
+
if tier not in valid_tiers:
|
775 |
+
return False, f"Invalid tier: {tier}. Must be one of {valid_tiers}"
|
776 |
+
|
777 |
+
# Get the plan IDs
|
778 |
+
plans = get_subscription_plans()
|
779 |
+
|
780 |
+
# Log the plans for debugging
|
781 |
+
logger.info(f"Available subscription plans: {plans}")
|
782 |
+
|
783 |
+
# If no plans found, check if the file exists and try to load it directly
|
784 |
+
if not plans:
|
785 |
+
if os.path.exists(PLAN_IDS_PATH):
|
786 |
+
logger.info(f"Plan IDs file exists at {PLAN_IDS_PATH}, but couldn't load plans. Trying direct load.")
|
787 |
+
try:
|
788 |
+
with open(PLAN_IDS_PATH, 'r') as f:
|
789 |
+
plans = json.load(f)
|
790 |
+
logger.info(f"Directly loaded plans: {plans}")
|
791 |
+
except Exception as e:
|
792 |
+
logger.error(f"Error directly loading plans: {str(e)}")
|
793 |
+
else:
|
794 |
+
logger.error(f"Plan IDs file does not exist at {PLAN_IDS_PATH}")
|
795 |
+
|
796 |
+
# If still no plans, return error
|
797 |
+
if not plans:
|
798 |
+
logger.error("No PayPal plans found. Please initialize plans first.")
|
799 |
+
return False, "PayPal plans not configured. Please contact support."
|
800 |
+
|
801 |
+
# Check if the tier exists in plans
|
802 |
+
if tier not in plans:
|
803 |
+
return False, f"No plan found for tier: {tier}"
|
804 |
+
|
805 |
+
# Use environment variable for the app URL
|
806 |
+
app_url = os.getenv("APP_URL", "http://localhost:3000")
|
807 |
+
|
808 |
+
# Create the subscription with PayPal
|
809 |
+
payload = {
|
810 |
+
"plan_id": plans[tier],
|
811 |
+
"subscriber": {
|
812 |
+
"email_address": user_email
|
813 |
+
},
|
814 |
+
"application_context": {
|
815 |
+
"brand_name": "Legal Document Analyzer",
|
816 |
+
"locale": "en-US", # Changed from en_US to en-US
|
817 |
+
"shipping_preference": "NO_SHIPPING",
|
818 |
+
"user_action": "SUBSCRIBE_NOW",
|
819 |
+
"return_url": f"{app_url}/subscription/callback?status=success",
|
820 |
+
"cancel_url": f"{app_url}/subscription/callback?status=cancel"
|
821 |
+
}
|
822 |
+
}
|
823 |
+
|
824 |
+
# Make the API call to PayPal
|
825 |
+
success, subscription_data = call_paypal_api("/v1/billing/subscriptions", "POST", payload)
|
826 |
+
if not success:
|
827 |
+
return False, subscription_data # This is already an error message
|
828 |
+
|
829 |
+
# Extract the approval URL
|
830 |
+
approval_url = next((link["href"] for link in subscription_data["links"]
|
831 |
+
if link["rel"] == "approve"), None)
|
832 |
+
|
833 |
+
if not approval_url:
|
834 |
+
return False, "No approval URL found in PayPal response"
|
835 |
+
|
836 |
+
# Get user ID from email
|
837 |
+
conn = get_db_connection()
|
838 |
+
cursor = conn.cursor()
|
839 |
+
cursor.execute("SELECT id FROM users WHERE email = ?", (user_email,))
|
840 |
+
user_result = cursor.fetchone()
|
841 |
+
|
842 |
+
if not user_result:
|
843 |
+
conn.close()
|
844 |
+
return False, f"User not found: {user_email}"
|
845 |
+
|
846 |
+
user_id = user_result[0]
|
847 |
+
|
848 |
+
# Store pending subscription in database
|
849 |
+
sub_id = str(uuid.uuid4())
|
850 |
+
start_date = datetime.now()
|
851 |
+
|
852 |
+
cursor.execute(
|
853 |
+
"INSERT INTO subscriptions (id, user_id, tier, status, created_at, expires_at, paypal_subscription_id) VALUES (?, ?, ?, ?, ?, ?, ?)",
|
854 |
+
(sub_id, user_id, tier, "pending", start_date, None, subscription_data["id"])
|
855 |
+
)
|
856 |
+
|
857 |
+
conn.commit()
|
858 |
+
conn.close()
|
859 |
+
|
860 |
+
# Return success with approval URL
|
861 |
+
return True, {
|
862 |
+
"subscription_id": subscription_data["id"],
|
863 |
+
"approval_url": approval_url,
|
864 |
+
"tier": tier
|
865 |
+
}
|
866 |
+
|
867 |
+
except Exception as e:
|
868 |
+
logger.error(f"Error creating user subscription: {str(e)}")
|
869 |
+
return False, f"Error creating subscription: {str(e)}"
|
870 |
+
|
871 |
+
# Add a function to cancel a subscription
|
872 |
+
def cancel_subscription(subscription_id, reason="Customer requested cancellation"):
|
873 |
+
"""
|
874 |
+
Cancel a PayPal subscription
|
875 |
+
|
876 |
+
Args:
|
877 |
+
subscription_id: The PayPal subscription ID
|
878 |
+
reason: The reason for cancellation
|
879 |
+
|
880 |
+
Returns:
|
881 |
+
tuple: (success, result)
|
882 |
+
- success: True if successful, False otherwise
|
883 |
+
- result: Success message or error message
|
884 |
+
"""
|
885 |
+
try:
|
886 |
+
# Cancel the subscription with PayPal
|
887 |
+
payload = {
|
888 |
+
"reason": reason
|
889 |
+
}
|
890 |
+
|
891 |
+
success, result = call_paypal_api(
|
892 |
+
f"/v1/billing/subscriptions/{subscription_id}/cancel",
|
893 |
+
"POST",
|
894 |
+
payload
|
895 |
+
)
|
896 |
+
|
897 |
+
if not success:
|
898 |
+
return False, result
|
899 |
+
|
900 |
+
# Update subscription status in database
|
901 |
+
conn = get_db_connection()
|
902 |
+
cursor = conn.cursor()
|
903 |
+
cursor.execute(
|
904 |
+
"UPDATE subscriptions SET status = 'cancelled' WHERE paypal_subscription_id = ?",
|
905 |
+
(subscription_id,)
|
906 |
+
)
|
907 |
+
|
908 |
+
# Get the user ID for this subscription
|
909 |
+
cursor.execute(
|
910 |
+
"SELECT user_id FROM subscriptions WHERE paypal_subscription_id = ?",
|
911 |
+
(subscription_id,)
|
912 |
+
)
|
913 |
+
user_result = cursor.fetchone()
|
914 |
+
|
915 |
+
if user_result:
|
916 |
+
# Update user to free tier
|
917 |
+
cursor.execute(
|
918 |
+
"UPDATE users SET subscription_tier = 'free_tier' WHERE id = ?",
|
919 |
+
(user_result[0],)
|
920 |
+
)
|
921 |
+
|
922 |
+
conn.commit()
|
923 |
+
conn.close()
|
924 |
+
|
925 |
+
return True, "Subscription cancelled successfully"
|
926 |
+
|
927 |
+
except Exception as e:
|
928 |
+
logger.error(f"Error cancelling subscription: {str(e)}")
|
929 |
+
return False, f"Error cancelling subscription: {str(e)}"
|
930 |
+
|
931 |
+
def verify_subscription_payment(subscription_id):
|
932 |
+
"""
|
933 |
+
Verify a subscription payment with PayPal
|
934 |
+
|
935 |
+
Args:
|
936 |
+
subscription_id: The PayPal subscription ID
|
937 |
+
|
938 |
+
Returns:
|
939 |
+
tuple: (success, result)
|
940 |
+
- success: True if successful, False otherwise
|
941 |
+
- result: Dictionary with subscription details or error message
|
942 |
+
"""
|
943 |
+
try:
|
944 |
+
# Get subscription details from PayPal using our helper
|
945 |
+
success, subscription_data = call_paypal_api(f"/v1/billing/subscriptions/{subscription_id}")
|
946 |
+
if not success:
|
947 |
+
return False, subscription_data # This is already an error message
|
948 |
+
|
949 |
+
# Check subscription status
|
950 |
+
status = subscription_data.get("status", "").upper()
|
951 |
+
|
952 |
+
if status not in ["ACTIVE", "APPROVED"]:
|
953 |
+
return False, f"Subscription is not active: {status}"
|
954 |
+
|
955 |
+
# Return success with subscription data
|
956 |
+
return True, subscription_data
|
957 |
+
|
958 |
+
except Exception as e:
|
959 |
+
logger.error(f"Error verifying subscription: {str(e)}")
|
960 |
+
return False, f"Error verifying subscription: {str(e)}"
|
961 |
+
|
962 |
+
def verify_paypal_subscription(subscription_id):
|
963 |
+
"""
|
964 |
+
Verify a PayPal subscription
|
965 |
+
|
966 |
+
Args:
|
967 |
+
subscription_id: The PayPal subscription ID
|
968 |
+
|
969 |
+
Returns:
|
970 |
+
tuple: (success, result)
|
971 |
+
"""
|
972 |
+
try:
|
973 |
+
# Skip verification for mock subscriptions
|
974 |
+
if subscription_id.startswith("mock_sub_"):
|
975 |
+
return True, {"status": "ACTIVE"}
|
976 |
+
|
977 |
+
# For real subscriptions, call PayPal API
|
978 |
+
success, result = call_paypal_api(f"/v1/billing/subscriptions/{subscription_id}", "GET")
|
979 |
+
|
980 |
+
if success:
|
981 |
+
# Check subscription status
|
982 |
+
if result.get("status") == "ACTIVE":
|
983 |
+
return True, result
|
984 |
+
else:
|
985 |
+
return False, f"Subscription is not active: {result.get('status')}"
|
986 |
+
else:
|
987 |
+
logger.error(f"PayPal API error: {result}")
|
988 |
+
return False, f"Failed to verify subscription: {result}"
|
989 |
+
except Exception as e:
|
990 |
+
logger.error(f"Error verifying PayPal subscription: {str(e)}")
|
991 |
+
return False, f"Error verifying subscription: {str(e)}"
|
992 |
+
|
993 |
+
# Add this function to save subscription plans
|
994 |
+
def save_subscription_plans(plans):
|
995 |
+
"""
|
996 |
+
Save subscription plans to a file
|
997 |
+
|
998 |
+
Args:
|
999 |
+
plans: Dictionary of plan IDs by tier
|
1000 |
+
"""
|
1001 |
+
try:
|
1002 |
+
with open(PLAN_IDS_PATH, 'w') as f:
|
1003 |
+
json.dump(plans, f)
|
1004 |
+
logger.info(f"Saved subscription plans to {PLAN_IDS_PATH}")
|
1005 |
+
return True
|
1006 |
+
except Exception as e:
|
1007 |
+
logger.error(f"Error saving subscription plans: {str(e)}")
|
1008 |
+
return False
|