def process_payment(db, raw_message, payment_message): parrot = Parrots.findOne(db, {'_id': ObjectId(payment_message.get('parrot_id'))}) if parrot: message = get_message_to_share(db, payment_message) twitter_json = tweet_message(parrot, message, raw_message.id) payment = store_payment(db, twitter_json, payment_message, message, raw_message) if payment.success: if Queue.delete_message('payments', raw_message): log('cron2', 'Payments succeded', payment_message.get('subscription_id')) send_notification(db, payment, 'payment_success') log('cron2', 'Notification sent', payment_message.get('subscription_id')) create_next_payment(db, payment) log('cron2', 'Next payment created', payment_message.get('subscription_id')) add_payment_to_parrot(db, parrot, payment_message, twitter_json) else: log('cron2', 'ERROR: Couldnt delete message', payment_message.get('subscription_id')) else: total_payments_attempts = Payments.find(db, {'message_id_sqs': raw_message.id}).count() subscription = Subscriptions.findOne(db, {'account_id': payment.account_id, 'parrot_id': payment.parrot_id}) if subscription: if total_payments_attempts > 3: log('cron2', 'Too many payments attempts', payment_message.get('subscription_id')) subscription.update({'active': False}) if Queue.delete_message('payments', raw_message): send_notification(db, payment,'subscription_deactivated') else: log('cron2', 'ERROR: Couldnt delete message', payment_message.get('subscription_id')) else: log('cron2', 'Attempt %s' % total_payments_attempts, payment_message.get('subscription_id'))
def store_payment(db, twitter_json, payment_message, message, raw_message): subscription = Subscriptions.findOne(db, {'account_id': ObjectId(payment_message.get('account_id')),'parrot_id': ObjectId(payment_message.get('parrot_id'))}) payment_data = { 'twitter_response': twitter_json, # action date means when this payment has to be tweeted 'action_date': datetime.now(), 'account_id': ObjectId(payment_message.get('account_id')), 'subscription_id': ObjectId(subscription.id), 'parrot_id': ObjectId(payment_message.get('parrot_id')), 'message_id': ObjectId(message.get('id')), 'message_id_sqs': raw_message.id, 'callback_url': message.get('url', ''), 'success': True } if twitter_json.get('error'): payment_data['success'] = False log('cron2', 'ERROR: Payment coulndt be processed because of twitter error %s' % json.dumps(twitter_json), payment_message.get('subscription_id')) else: log('cron2', 'Payment executed successfully', payment_message.get('subscription_id')) payment = Payments(db, payment_data) payment.insert() return payment
def redirect_from_message(message_id, db): payment = Payments.findOne(db, {'message_id_sqs': message_id}) if payment: redirect(payment.callback_url) else: response.status = 404