Browse Source

Got a proper payload from GiveButter. Modified relevant functions accordingly

deadtom 4 tuần trước cách đây
mục cha
commit
713e909640
2 tập tin đã thay đổi với 51 bổ sung48 xóa
  1. 7 17
      ownchatbot/donation_handlers.py
  2. 44 31
      ownchatbot/webhooks.py

+ 7 - 17
ownchatbot/donation_handlers.py

@@ -28,11 +28,11 @@ def accept_donation(donation_info, donation_points, donation_service):
                     for user in get_all_users_with_user_id(db, id[0]):
                         name = user[1]
                         if not name:
-                            name = 'Someone (not yet registered with OCB)'
+                            name = 'Someone'
                     current_app.logger.info(f'Granted user id {id[0]} {porps(points)} for their ${amount} donation.')
         if is_public:
             message = f'{name} got {porps(points)} for donating ${amount} on {donation_service}!'
-            current_app.logger.info(f'Public donation of ${amount} received from {name} via {donation_service}')
+            current_app.logger.info(f'Public donation of ${amount} received from {name} via {donation_service}. Granted {porps(points)}.')
         else:
             message = None
             current_app.logger.info(f'Anonymous donation of ${amount} received via {donation_service}')
@@ -70,11 +70,11 @@ def accept_kofi_sub(sub_info, sub_points):
         if is_public:
             if not name:  # If no name in points table
                 name = 'Someone'
-            if first_sub:
-                message = f'{name} got {porps(points)} for their one month membership on Kofi!'
+            if first_sub:  # Kofi-only field
+                message = f'{name} got {porps(points)} for their one month membership on {donation_service}!'
                 current_app.logger.info(f'Public subscription received from {name}')
             else:
-                message = f'{name} got {porps(points)} for renewing their membership on Kofi!'
+                message = f'{name} got {porps(points)} for renewing their membership on {donation_service}!'
                 current_app.logger.info(f'Anonymous {donation_service} subcription renewal received.')
             send_chat(message)  # Send message publicly if a public membership
         else:
@@ -84,10 +84,10 @@ def accept_kofi_sub(sub_info, sub_points):
             if not name:  # If no name in points table
                 name = sub_info[1]  # Assign name from Kofi response
             if first_sub:
-                message = f'Thanks so much for your subscribing to my Kofi! You\'ve been awarded {porps(points)}!'
+                message = f'Thanks so much for your subscribing to my {donation_service}! You\'ve been awarded {porps(points)}!'
                 current_app.logger.info(f'Anonymous {donation_service} subscription received.')
             else:
-                message = f'Thanks so much for renewing your membership to my Kofi! You\'ve been awarded {porps(points)}!'
+                message = f'Thanks so much for renewing your membership to my {donation_service}! You\'ve been awarded {porps(points)}!'
                 current_app.logger.info(f'Anonymous {donation_service} subscription renewal received.')
             send_private_chat(id[0], message)
         return True
@@ -121,13 +121,3 @@ def save_gb_settings(gbsettings_info):  # Write settings to givebutter.py
         return False
 
     return True
-
-
-def kofi_pngs():  # Create a list of all pngs in the kofi img dir
-    png_dir = 'static/img/kofi'
-    png_dir = os.path.join(current_app.root_path, png_dir)
-    png_files = []
-    for file in os.listdir(png_dir):
-        if file.lower().endswith('.png'):
-            png_files.append(file)
-    return png_files

+ 44 - 31
ownchatbot/webhooks.py

@@ -180,13 +180,14 @@ def sign_payload(payload, secret):  # For TESTING purposes
 
 
 def verify_gbhook_signature(payload, signature, secret):
+    current_app.logger.info(f'\n\nRecieved Signature: {signature}\n\n')
     expected_signature = hmac.new(
         secret.encode(),
         payload.encode(),
         hashlib.sha256
     ).hexdigest()
     do_sig_check = hmac.compare_digest(signature, expected_signature)
-    current_app.logger.info(f'\n\nExpected Signature: {expected_signature}\nTest output: {do_sig_check}\n\n')
+    current_app.logger.debug(f'\n\nExpected Signature: {expected_signature}\nResult: {do_sig_check}\n\n')
     return do_sig_check
 
 
@@ -194,7 +195,13 @@ def verify_gbhook_signature(payload, signature, secret):
 def gb_hook():
     current_app.logger.info(f'----------------------------------------------------------------------------')
     current_app.logger.info(f'GiveButter request')
-    signature = request.headers.get('X-Givebutter-Signature')
+
+    headers = request.headers
+    current_app.logger.debug('Headers:')
+    for header, value in headers.items():
+        current_app.logger.debug(f'> {header}: {value}')
+
+    signature = request.headers.get('Signature')
     gb_secret = current_app.config['GB_SETTINGS']['secret']
 
     raw_data = request.get_data(as_text=True)
@@ -202,36 +209,42 @@ def gb_hook():
     # signature = sign_payload(raw_data, gb_secret)  # For TESTING purposes
 
     event = request.json
-    transaction = event['data']  # TESTING
-    from_name = f'{transaction["first_name"]} {transaction["last_name"]}'  # TESTING
-    email = transaction['email']  # TESTING
-    amount = transaction['amount']  # TESTING
-    current_app.logger.info(f'\n\n{raw_data}\n\nSignature: {signature}\nFrom: {from_name}\nEmail: {email}\nAmount: {amount}\n\n')  # TESTING
-
-    if not verify_gbhook_signature(raw_data, signature, gb_secret):
-        return jsonify({'error': 'Invalid signature'}), 401
-    if current_app.config['GB_SETTINGS']['integration']:
-        try:
-            event_type = event['event']
-
-            if event_type == 'transaction.succeeded':
-                transaction = event['data']
-                from_name = f'{transaction["first_name"]} {transaction["last_name"]}'
-                email = transaction['email']
-                amount = transaction['amount']
-                donation_info = [True, from_name, email, amount, '']
-                donation_points = current_app.config['GB_SETTINGS']['donation_points']
-                if accept_donation(donation_info, donation_points, 'GiveButter'):
-                    current_app.logger.info(f'Donation processed.')
-            else:
-                current_app.logger.info(f'Unhandled event type: {event_type}')
-        except Exception as pgberror:
-            current_app.logger.error(f'General exception processing gbhook: {pgberror}')
-    else:
-        current_app.logger.error(f'GiveButter donation recieved, but GiveButter integration is turned off. Doing nothing.')
-        return jsonify({'status': 'Failed. Not currently accepting GiveButter donations.'}), 400
 
-    return jsonify({'received': True}), 200
+    # if not verify_gbhook_signature(raw_data, signature, gb_secret):  # GB is not currently signing payloads. Just sending the signing secret
+    #     return jsonify({'error': 'Invalid signature'}), 401  # Leaving this here in case they ever decide to sign it
+
+    if signature == gb_secret:
+        if current_app.config['GB_SETTINGS']['integration']:
+            try:
+                event_type = event['event']
+
+                if event_type == 'transaction.succeeded':
+                    transaction = event['data']
+                    from_name = f'{transaction["first_name"]} {transaction["last_name"]}'
+                    email = transaction['email']
+                    amount = transaction['amount']
+                    current_app.logger.debug(f'From: {from_name}\nEmail: {email}\nAmount: {amount}\n\n')
+                    donation_info = [True, from_name, email, amount, '']
+                    donation_points = current_app.config['GB_SETTINGS']['donation_points']
+                    points_for_donations = current_app.config['GB_SETTINGS']['donations']
+                    if points_for_donations:  # Are we giving points for donations?
+                        if accept_donation(donation_info, donation_points, 'GiveButter'):
+                            current_app.logger.info(f'Donation processed.')
+                    else:
+                        current_app.logger.info(f'Points for donations is disabled. Doing nothing.')
+                else:
+                    current_app.logger.info(f'Unhandled event type: {event_type}')
+            except Exception as pgberror:
+                current_app.logger.error(f'General exception processing gbhook: {pgberror}')
+
+        else:
+            current_app.logger.error(f'GiveButter donation recieved, but GiveButter integration is turned off. Doing nothing.')
+            return jsonify({'status': 'Failed. Not currently accepting GiveButter donations.'}), 400
+
+        return jsonify({'status': 'Success'}), 200  # If signature matched
+
+    else:
+        return jsonify({'status': 'Signature invalid'}), 401  # If signature didn't match
 
 
 @ocb.route('/checkFollows')  # Polled by follower.html template to check for new followers