# Tutorial

<p class="hide-from-github-pages">
<strong><a href="https://geta.github.io/checkout/docs/tutorial/readme.html">Read the tutorial here</a> to see live code examples</strong>
</p>

This tutorial shows how to implement Geta Checkout in a real project.

Start by installing the package, if you haven't already.

```bash
npm install --save geta-checkout
```

## Create a html structure

Create a HTML (or Razor) file.
<br>
For example, `checkout-page/index.html`.

<div>
<p style="min-height: 600px"
data-height="600"
data-theme-id="light"
data-slug-hash="GWYYJb"
data-preview="false"
data-default-tab="html"
data-user="Geta"
data-embed-version="2"
data-pen-title="Example"
class="codepen">
</p>
</div>

## Set up initial JavaScript

Next, we need to add some JavaScript to render UI components inside the `<div data-*>`-elements.

Create `checkout-page/index.js` and import functions, APIs and UI components from `geta-checkout`.
<br>
If using a module bundler that supports
[ES6 import statements](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import), you can import them like this:

```javascript
import { render, mockServer, /*...*/ } from 'geta-checkout';
```

For environments that do not support ES6 modules, there's a global `window.checkout` object.
<br>
The example below uses `window.checkout` as Codepen does not support ES6 modules.

```javascript
const { render, mockServer, /*...*/ } = window.checkout;
```

**Using ES6 syntax *is not* a requirement for using this package.**

<p style="min-height: 1100px"
data-height="1100"
data-theme-id="light"
data-slug-hash="GWYYJb"
data-preview="false"
data-default-tab="js"
data-user="Geta"
data-embed-version="2"
data-pen-title="Example"
class="codepen">
</p>

## Include the default theme

To add the default CSS theme, create `checkout-page/index.scss`.
<br>
Use a sass compiler that converts the sass file to `checkout-page/index.css`.
<br>
Then, add this line to `checkout-page/index.scss`:

```scss
@import 'node_modules/geta-checkout/src/ui/default-theme';
```

Later, we will see how the default theme can be modified or rewritten.

## That's it!

We now have a working prototype that displays dummy content.

<p style="min-height: 400px"
data-height="400"
data-theme-id="light"
data-slug-hash="GWYYJb"
data-default-tab="result"
data-user="Geta"
data-embed-version="2"
data-pen-title="Example"
data-embed-version="2"
data-preview="true"
class="codepen">
</p>

## Connect to a real backend

All the built-in APIs communicate with the server through a service-layer.
<br>
*Service-layer* is just a fancy word for functions that send ajax-requests, receive json-responses and return
[promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).

If the project is already using `jQuery`, you might want to use [`jQuery.ajax`](http://api.jquery.com/jquery.ajax/) for the service layers.
<br>
You could also use native [`XMLHttpRequest`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest)s, but that can be a bit tedious to get right.
<br>
If your site doesn't run jQuery, another option is to use [`axios`](https://github.com/mzabriskie/axios) - a *promise based HTTP client*.

The example below uses jQuery.
<br>
It also cancels the previous request if any, to prevent problems that will occur when the first request finish last.
<br>
A service-layer boilerplate can be found in **[the API docs](../../api/readme.md)**.

<p style="min-height: 1200px"
data-height="1200"
data-theme-id="light"
data-slug-hash="GWYYpV"
data-default-tab="js,result"
data-user="Geta"
data-embed-version="2"
data-pen-title="Checkout services"
class="codepen">
</p>

<br>
This is probably a good time to refactor some code.
<br>
For example, you may want to organize the services into separate files:

```markdown
checkout-page/services/cart.js
checkout-page/services/customer.js
checkout-page/services/language.js
checkout-page/services/payment.js
checkout-page/services/shipment.js
```

And import them into `checkout-page/index.js`:

```javascript
import cartServices from './services/cart.js';
```

## Convert responses

The example above sends the json response from the server through a `convertResponse`-function.
<br>
This is necessary if the server returns a different json-format than the one expected by the JavaScript API.
<br>
It may also be necessary for some ajax-libraries such as Axios, where the actual json is wrapped in a response-object.

```javascript
function convertResponse(jsonFromServer){
    var expectedJson = {
        totalQuantity: jsonFromServer.count,
        ...
    };
    return expectedJson;
}
```

## Manage complex responses

Sometimes, a server-request needs to return additional data.
<br>
For example, if the user adds an additional item to cart, the shipment costs may increase.

In that case, the response must contain both `cart` and `shipment`:

```http
POST /cart/add

{
    "cart": {},
    "shipment": {}
}
```

The pattern below shows how to keep all APIs in sync, and how to notify changes in data.

<p style="min-height: 1120px"
data-height="1120"
data-theme-id="light"
data-slug-hash="YZJJwg"
data-default-tab="js,result"
data-user="Geta"
data-embed-version="2"
data-pen-title="Checkout services 2"
class="codepen">
</p>

## UI

So far, we've been using the built-in components.
<br>
That's fine as long as they meet project requirements.

However, let's imagine the project specs look like this:

### The UI should use a green color

**See [how to customize CSS](../../ui/docs/css.html)**
<br>
In this case, modifying the default theme may be enough.
<br>
If the design is going to be extensively modified, it will make more sense to write CSS from scratch for one or more components.
<br>
If HTML needs to be modified for a component as well, it will be necessary to write a custom component.

### User behaviour should be tracked

Whenever the user adds an item to cart, the event should be tracked, e.g. in Google Analytics.

<p style="min-height: 480px"
data-height="480"
data-theme-id="light"
data-slug-hash="BWqqzN"
data-default-tab="js,result"
data-user="Geta"
data-embed-version="2"
data-pen-title="Checkout GA Tracking"
class="codepen">
</p>

### There should be an additional login form

#### Assumptions:

* The built-in login UI will work for both forms
* The project is using jQuery
* We will use the built-in `mockServer` for now

By creating an additional customer service, we can send an additional variable to the server.
<br>
For example, `userType: 'partner'`

```javascript
import { render, mockServer, CustomerApi, LoginUI } from 'geta-checkout';

const additionalCustomerServices = $.extend({}, mockServer.customerServices, {
    login({userId, password}){
        return $.ajax({
            url: '/login',
            method: 'post',
            data: {
                userId: userId,
                password: password,
                userType: 'partner'
            }
        });
    }
});
```

Then, we will create an `additionalCustomerApi` that uses `additionalCustomerServices`.
<br>
The additional `LoginUI` component must be set to use the `additionalCustomerApi`.
<br>
And `additionalCustomerApi` must be added to `render.init`.

```javascript
const additionalCustomerApi = new CustomerApi(additionalCustomerServices);

render('[data-additional-login]', LoginUI, { customerApi: additionalCustomerApi });

render.init({
    additionalCustomerApi: additionalCustomerApi
});
```

### An additional payment method should be added

Assuming that the server returns an additional payment method that looks like this:

```json
{
    "id": "CustomPayment",
    ...
}
```

Create a file called `checkout-page/payment-method-renderers.jsx` with the following contents:

```javascript
import React from 'react';
import * as methodRenderers from 'geta-checkout/ui/components/payment/methods';
import PaymentMethodBase from 'geta-checkout/ui/components/payment/methods/paymentmethodbase.jsx';

// Append to built-in payment method renderers

methodRenderers.CustomPayment = class extends PaymentMethodBase {
    render() {
        return (
            <div>This is a custom payment method</div>
        );
    }
};

export default methodRenderers;
```

Then, we must update `checkout-page/index.js` so that `PaymentUI` receives the custom payment method UI:

```javascript
import paymentMethodRenderers from './payment-method-renderers.jsx';

render('[data-payment]', PaymentUI, {
    methodRenderers: paymentMethodRenderers
});
```

You can also override built-in payment method renderers like this:

```javascript
methodRenderers.Nets = class extends PaymentMethodBase {
    render() { return <p>Override</p>; }
};
```

**The same pattern can be used for adding shipment method renderers**.

<script async src="https://production-assets.codepen.io/assets/embed/ei.js"></script>
<script>
    document.querySelector('.markdown-body').classList.add('tutorial');
</script>