# Handling Events

## Handling actions <a href="#handling-actions" id="handling-actions"></a>

The handleResponse function can be used to update user information in your database regarding the customers subscription information, to do redirects on signup, or present notifications.

### Parameters <a href="#parameters" id="parameters"></a>

handleResponse will pass a variable which contains the following properties

| Variable Name | Description                              |
| ------------- | ---------------------------------------- |
| **event**     | The name of the event that occurred      |
| **response**  | The response object returned from Stripe |

### Events <a href="#events" id="events"></a>

| Event Name                | Description                                                                                                                                                                                                                                                                                          | Response Object                                                                                                                     |
| ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| **pre\_load**             | First thing run after the embed javascript loads, before any API calls have been made. Use to inject React components or tell when the embed has loaded.                                                                                                                                             | Embed Configuration                                                                                                                 |
| **post\_load**            | <p>billingData: null — means the subscription portal is not loaded yet</p><p>billingData: {no\_user: true} — means the current email is not a customer</p><p>productData: null — means pricing (products) are not loaded yet</p><p>productData: \[ … ] — means the pricing (products) are loaded</p> | <p>billingData</p><p>currentConfig</p><p>productData</p>                                                                            |
| **pre\_subscribe**        | <p>This event allows you to do some actions before creating a subscription. For example, you can use it for checking if a user exists in your system.</p><p>Throwing an error here will prevent Billflow from creating a subscription. </p>                                                          | <p>email</p><p>service</p><p>tier</p>                                                                                               |
| **create\_subscription**  | Triggered when a subscription is created from a billing page. Use this event to update your user system with the Stripe subscription ID and tier. Learn more on the install guide.                                                                                                                   | ​[Subscription](https://stripe.com/docs/api/subscriptions/object)​                                                                  |
| **pre\_change\_plan**     | Triggered before when a user clicks on the confirm button, but before the API call is made to change plan.                                                                                                                                                                                           | <p>email</p><p>service</p><p>tier</p>                                                                                               |
| **change\_plan**          | Triggered when a user upgrades or downgrades using the Plan Picker. You can use this to update their tier information or create notifications.                                                                                                                                                       | ​[Subscription](https://stripe.com/docs/api/subscriptions/object)​                                                                  |
| **select\_plan**          | Triggered when a user selects a plan from the pricing page or plan picker. Use this to redirect to other pages or forms to create custom on-boarding flows.                                                                                                                                          | Tier name & [Plan](https://stripe.com/docs/api/plans/object)​                                                                       |
| **pre\_resubscribe**      | Triggered when a customer clicks on the resubscribe button, but before the API call is made to resubscribe.                                                                                                                                                                                          | <p>email</p><p>service</p><p>subscription\_id</p><p><a href="https://stripe.com/docs/api/subscriptions/object">Subscription</a></p> |
| **resubscribe**           | Triggered when a customer resubscribes from the portal. This occurs when a customer was cancelled, they come back to the portal and choose to resubscribe to a plan. Use this event to update your user system with the Stripe subscription ID and tier.                                             | ​[Subscription](https://stripe.com/docs/api/subscriptions/object)​                                                                  |
| **pre\_cancel**           | Triggered when a customer clicks on the cancellation button. Use this to create a custom cancellation flow.                                                                                                                                                                                          |                                                                                                                                     |
| **cancel\_subscription**  | Triggered when a customer requests a cancellation. Use this event to update subscription status for a user.                                                                                                                                                                                          | ​[Subscription](https://stripe.com/docs/api/subscriptions/object)​                                                                  |
| **pre\_change\_card**     | Triggered when a customer clicks on change card button, but before the API call is made to change card.                                                                                                                                                                                              | <p>email</p><p>service</p><p>subscription\_id</p><p><a href="https://stripe.com/docs/api/subscriptions/object">Subscription</a></p> |
| **update\_card**          | Triggered when a customer updates their Credit Card information or enters it for the first time. Use for presenting notifications to the user.                                                                                                                                                       | ​[Customer](https://stripe.com/docs/api/customers/object)​                                                                          |
| **request\_error**        | Triggered when any of our API requests failed. User for custom handling of any request failures.                                                                                                                                                                                                     | The Request Error                                                                                                                   |
| **pre\_update\_quantity** | Triggered before quantity is updated on a subscription from the customer portal                                                                                                                                                                                                                      | <p>Price</p><p>quantity</p><p>subscription\_id</p>                                                                                  |
| **update\_quantity**      | Triggered after a quantity has been updated from the customer portal                                                                                                                                                                                                                                 | [Subscription](https://stripe.com/docs/api/subscriptions/object)                                                                    |
| **add\_coupon**           | Triggered after a coupon has been added. Can be used to create custom coupon restriction logic.                                                                                                                                                                                                      | [Coupon](https://stripe.com/docs/api/coupons/object)                                                                                |

## Sample Redirect on Subscribe <a href="#sample-portal-code" id="sample-portal-code"></a>

Redirect to a URL after subscription

```markup
<div id="billflow-embed"></div>
<script>
  window.billflowSettings = {
    billing_page_id: "B4bD7TzIKxnsZfcgJoFk",
    email: "example@somemail.com",
    handleResponse: async function(payload) {
      console.log("Event ", payload.event);
      console.log("Response Object ", payload.response);
      //Redirect on Signup example
      if (payload.event == "create_subscription") {
        window.location.href = "https://google.com";
      }
    }
  };
  (function() {
    var s = document.createElement('script');
    s.src = 'https://js.billflow.io/billflow-embed.js';
    s.async = true;
    s.type = 'text/javascript';
    var x = document.getElementsByTagName('script')[0];
    x.parentNode.insertBefore(s, x);
  })();
</script>
```

## Sample Redirect based on Tier Subscribed

{% embed url="<https://codepen.io/kmidkiff/pen/XWjxqXp>" %}

## Sample Pricing Page redirect for specific tier <a href="#sample-portal-code" id="sample-portal-code"></a>

Redirect to a URL after subscription

```markup
<div id="billflow-embed"></div>
<script>
  window.billflowSettings = {
    "billing_page_id": "B4bD7TzIKxnsZfcgJoFk",
    "loader": "2",
    handleResponse: async function(payload) {
      let event = payload.event;
      let response = payload.response;
      //Redirect for free plan (update tiername check to yours)
      if (event == "select_plan") {
        let tierName = response.tier.tierName;
        if (tierName == "Starter") {
          window.location.href = "https://google.com"; //CHANGE ME
        }
      }
    }
  };
  (function() {
    var s = document.createElement('script');
    s.src = 'https://js.billflow.io/billflow-embed.js';
    s.async = true;
    s.type = 'text/javascript';
    var x = document.getElementsByTagName('script')[0];
    x.parentNode.insertBefore(s, x);
  })();
</script>
```

## Sample Existing User check

Skip subscription creation if a user already exists

```javascript
window.billflowSettings = {
	handleResponse: async function(payload) {
		// Implement pre subscribe hook example
    let { event, response } = payload;
		if (event === 'pre_subscribe') {
			// implement your logic for checking user exist in your system
			let { email, service, tier } = response;
			let exists = true;
			// throw an error for billflow to stop the subscribe action.
			if (exists) {
				throw {
					// displays an error message in servicebot
					message: 'User already exist, please login.',
					callback: () => {
						// call back to redirect or other actions you want to take.
						window.location = '/login';
					}
				};
			}
		}
	}
}
```

## Sample Track conversions with Google Analytics

Use GA to track signups

```javascript
window.billflowSettings = {
  handleResponse: async function (payload) {
    let { event, response } = payload;
    console.log("Event ", event);
    console.log("Response Object ", response); //Send record to google
    if (payload.event == "create_subscription") {
      let { email, seravice, tier } = response;
      var eventData = {
        event: "subscriptionPurchased",
        email: email
      };
      window.dataLayer.push(eventData);
    }
  }
};
```

## Sample Coupon restriction logic

Use to prevent a specific coupon based on logic

```javascript
  window.billflowSettings = {
    "billing_page_id": "MsPV2xxqNmPUjJVOEnu8",
    "handleResponse": function handleResponse(response) {
      // your code here 
      console.log("response", response)
      if (response.event === "add_coupon") {
        const coupon_id = response.response.coupon.id
        const bad_coupon = 'BAD'
        if (coupon_id == bad_coupon) {
          throw ({
            response: {
              data: {
                custom_error: "Custom Coupon Error~"
              }
            }
          })
        }
      }
    }
  };
```
