Пример #1
0
def cancel_subscription():
    json_dict = request.json
    user_id = json_dict['user_id']
    userSub = UserSubscription.get_subscription(user_id=user_id)
    userSubscription = {}
    if len(userSub) > 0:
        userSubscription = userSub[0]
    subscriptionId = userSubscription.subscription_id
    user = User.query.get(user_id)

    stripe.api_key =  ConfigValues.get_config_value('STRIPE_SK')

    try:
         # Cancel the subscription by deleting it
        deletedSubscription = stripe.Subscription.delete(subscriptionId)
        print(deletedSubscription)
        
        user_subscription_dict = {}
        
        user_subscription_dict['user_id'] = user.id
        user_subscription_dict['subscription_id'] = deletedSubscription['id']
        user_subscription_dict['subscription_type_id'] = userSubscription.subscription_type_id
        s_date = datetime.fromtimestamp(deletedSubscription['current_period_start'])
        user_subscription_dict['current_start_date'] = s_date
        e_date = datetime.fromtimestamp(deletedSubscription['current_period_end'])
        user_subscription_dict['current_end_date'] = e_date
        user_subscription_dict['application_fee_percent'] = deletedSubscription['application_fee_percent']
        user_subscription_dict['billing_cycle_anchor'] = deletedSubscription['billing_cycle_anchor']
        user_subscription_dict['billing_thresholds'] = deletedSubscription['billing_thresholds']
        user_subscription_dict['cancel_at'] = deletedSubscription['cancel_at']
        user_subscription_dict['cancel_at_period_end'] = deletedSubscription['cancel_at_period_end']
        ca_date = datetime.fromtimestamp(deletedSubscription['canceled_at'])
        user_subscription_dict['canceled_at'] = ca_date
        user_subscription_dict['collection_method'] = deletedSubscription['collection_method']
       
        userSubscription.update(user_subscription_dict)
        Payment.send_subscription_cancelled_email(user_email=user.email)

        if datetime.now() > userSubscription.current_end_date:  # else, there is another check when user makes an order and sets to 0 if it fails this validation
            user.update({'subscribed':0})
           

        return jsonify(deletedSubscription).json
    except Exception as e:
        return jsonify(error=str(e)), 403
Пример #2
0
def webhook_received():

    # You can use webhooks to receive information about asynchronous payment events.
    # For more about our webhook events check out https://stripe.com/docs/webhooks.
    webhook_secret = ConfigValues.get_config_value('STRIPE_WHS') #"whsec_Z5rqV5EyWqGAcsGVsf1id7kfCk8hQXkI" #os.getenv('STRIPE_WEBHOOK_SECRET')
    request_data = json.loads(request.data)

    if webhook_secret:
        # Retrieve the event by verifying the signature using the raw body and secret if webhook signing is configured.
        signature = request.headers.get('stripe-signature')
        try:
            event = stripe.Webhook.construct_event(
                payload=request.data, sig_header=signature, secret=webhook_secret)
            data = event['data']
        except Exception as e:
            return e
        # Get the type of webhook event sent - used to check the status of PaymentIntents.
        event_type = event['type']
    else:
        data = request_data['data']
        event_type = request_data['type']

    data_object = data['object']

    if event_type == 'invoice.payment_succeeded':
        # Used to provision services after the trial has ended.
        # The status of the invoice will show up as paid. Store the status in your
        # database to reference when a user accesses your service to avoid hitting rate
        # limits.
        print(data)
        sid = request_data['data']['object']['customer']
        user = User.get_user_by_stripe_id(stripe_id=sid)
        email = user.email
        Payment.send_subscription_renewal_success_email(user_email=email)
        userSub = UserSubscription.get_subscription(user_id=user.id)
        userSubscription = {}
        if len(userSub > 0):
            userSubscription = userSub[0]

        user_subscription_dict = {}
        user_subscription_dict['user_id'] = user.id
        user_subscription_dict['subscription_type_id'] = userSubscription.subscription_type_id
        s_date = datetime.fromtimestamp(data['object']['period_start'])
        user_subscription_dict['current_start_date'] = s_date
        e_date = datetime.fromtimestamp(data['object']['period_end'])
        user_subscription_dict['current_end_date'] = e_date

        userSubscription.update(user_subscription_dict)
        user.update({'subscribed': 1, 'number_of_items_ordered_this_month' : 0})

    if event_type == 'invoice.payment_failed':
        # If the payment fails or the customer does not have a valid payment method,
        # an invoice.payment_failed event is sent, the subscription becomes past_due.
        # Use this webhook to notify your user that their payment has
        # failed and to retrieve new card details.
        print(data)
        
        sid = request_data['data']['object']['customer']
        user = User.get_user_by_stripe_id(stripe_id=sid)
        email = user.email
        Payment.send_subscription_renewal_failure_email(user_email=email)
                
        userSub = UserSubscription.get_subscription(user_id=user.id)
        userSubscription = {}
        if len(userSub > 0):
            userSubscription = userSub[0]

        user_subscription_dict = {}
        user_subscription_dict['user_id'] = user.id
        user_subscription_dict['subscription_type_id'] = userSubscription.subscription_type_id
        s_date = datetime.fromtimestamp(data['object']['period_start'])
        user_subscription_dict['current_start_date'] = s_date
        e_date = datetime.fromtimestamp(data['object']['period_end'])
        user_subscription_dict['current_end_date'] = e_date

        userSubscription.update(user_subscription_dict)
        user.update({'subscribed': 0, 'number_of_items_ordered_this_month' : 0})

    if event_type == 'invoice.finalized':
        # If you want to manually send out invoices to your customers
        # or store them locally to reference to avoid hitting Stripe rate limits.
        print(data)

    if event_type == 'customer.subscription.deleted':
        # handle subscription cancelled automatically based
        # upon your subscription settings. Or if the user cancels it.
        print(data)
        sid = request_data['data']['object']['customer']
        user = User.get_user_by_stripe_id(stripe_id=sid)
        email = user.email
        
        userSub = UserSubscription.get_subscription(user_id=user.id)
        userSubscription = {}
        if len(userSub > 0):
            userSubscription = userSub[0]

        user_subscription_dict = {}
        user_subscription_dict['user_id'] = user.id
        user_subscription_dict['subscription_type_id'] = userSubscription.subscription_type_id
        s_date = datetime.fromtimestamp(data['object']['period_start'])
        user_subscription_dict['current_start_date'] = s_date
        e_date = datetime.fromtimestamp(data['object']['period_end'])
        user_subscription_dict['current_end_date'] = e_date

        userSubscription.update(user_subscription_dict)
        Payment.send_subscription_cancelled_email(user_email=email)
        if datetime.now() > userSubscription.current_end_date:  # else, there is another check when user makes an order and sets to 0 if it fails this validation
            user.update({'subscribed': 0, 'number_of_items_ordered_this_month' : 0})
          

    if event_type == 'customer.subscription.trial_will_end':
        # Send notification to your user that the trial will end
        print(data)

    return jsonify({'status': 'success'})