npm package: @palenca/palenca-link
Description: Palenca Link is the client-side and the secure way to link the user accounts to Palenca and allow you to access their data via the Palenca API.
Author: Palenca team
Latest version: 2.1.12

# Palenca Link

Palenca Link is the client-side and the secure way to link the user accounts to Palenca and allow you to access their data via the Palenca API.

Palenca Link will handle credential validation, multi-factor authentication, and error handling for each platform that we support.

## How to use Palenca Link?

### Using the CDN

```html
<script src="https://link.palenca.com/v2/index.min.js"></script>
```

### Using ES6

```bash
npm install @palenca/palenca-link
```

```js
import { loadLink } from "@palenca/palenca-link";
```

## Load parameters
| Parameter         | Example                                       | Description            | Required | Order | 
| ----------------- | --------------------------------------------- | -----------------------|----------|-------| 
| publicApiKey      | `public_6187344f-d2e9-4ff1-a0ca-7a1ad512682d` | The public API key     | True     | 1     |
| widgetId          | `c379afec-8d47-4fcf-ae07-353093baed2b`        | The Widget Id          | True     | 2     |

#### Load Example
```js
const linkPromise = loadLink('public_6187344f-d2e9-4ff1-a0ca-7a1ad512682d', 'c379afec-8d47-4fcf-ae07-353093baed2b');
```

## Configuration parameters
| Parameter         | Example                                     | Description                                                                                        | Required |
| ----------------- | ------------------------------------------- | ---------------------------------------------------------------------------------------------------|----------|
| externalId        | `6187344f-d2e9-4ff1-a0ca-7a1ad512682d`      | User external id                                                                                   | False    |
| platform          | `uber`                                      | Presents to the user a single platform login form                                                  | False    |
| isSandbox         | `true`                                      | If set to `true`, the sandbox mode is enabled. `false` by default                                  | False    |
| platforms         | `['uber', 'rappi', 'runa]`                  | Array of platforms the user is able to select                                                      | False    |
| country           | `mx`                                        | The alpha-2 code of the country                                                                    | False    |
| redirectUrl       | `https://domain.com/step-2`                 | URL where the user must be redirected                                                              | False    |
| customPrivacyUrl  | `https://domain.com/privacy`                | Allow you to add a custom privacy terms checkbox, useful if you need a custom consent              | False    |
| whatsAppPhoneNumber | `+525511223344`                           | Phone number with country code to receive WhatsApp messages from users                             | False    |
| hideLogo          | `false`                                     | If set to `true`, your company logo is hidden. `false` by default                                  | False    |
| hideWhatsApp      | `false`                                     | If set to `true`, the whatsapp floating button is hidden. `false` by default                       | False    |
| hideConsent       | `false`                                     | If set to `true`, the consent page is hidden. `false` by default                                   | False    |
| lang              | `es`                                        | Replaces the browser's auto-detected language. Available languages: es, en & pt. `null` by default | False    |


## Appearance parameters
| Parameter         | Example   | Description                                                                                        | Required |
| ----------------- | ----------| ---------------------------------------------------------------------------------------------------|----------|
| primaryColor      | `#1F5BC0` | Hexadecimal color, the hexadecimal color values are supported in all browsers                      | False    |
| borderRadius      | `10px`    | The border-radius property defines the radius of the element's corners                             | False    |
| fontFamily        | `Roboto`  | The font-family property specifies the font for the PalencaLink, Only accept Google Fonts          | False    |

### Helpful link

- [Google Fonts](https://fonts.google.com/)
- [Color Picker](https://www.w3schools.com/colors/colors_picker.asp)
- [Border radius](https://developer.mozilla.org/en-US/docs/Web/CSS/border-radius)

### Templates

| Template | Font    | Color     | Border radius |
|----------|---------|-----------|---------------|
| Black    | Lato    | `#000000` | `0px`         |
| Default  | Poppins | `#1F5BC0` | `10px`        |
| Nature   | Lato    | `#000000` | `0px`         |

## Events
The only way to communicate with Link is by listening to an event. All events have a payload object with the [API Envelope](https://documentation.palenca.com/docs/Responses/Envelope)


The Palenca Link 
The events are listed here:

|Event name             | Description                                                                                          |
|-----------------------|------------------------------------------------------------------------------------------------------|
| ready                 | Indicates that your Public API key and Widget it is correct and that the widget has been initialized |
| user_created          | The user was successfully created                                                                    |
| connection_success    | The user was connected successfully with the platform                                                |
| connection_error      | An error occurred meanwhile trying to connect a user with the platform                               |

### Events envelope
The envelope is always the same with the following structure:

``` javascript
{
    "success": bool,
    "data": Data Object,
    "error": Error Object
}
```

### Events examples

*ready*
``` javascript
{
    "success": true,
    "data": null,
    "error": null
}
```

*user_created*
``` javascript
{
    "success": true,
    "data": {
        "user_id": "054d0a9d-38ec-40cb-a31c-09b483242e4a",
        "external_id": "4a0e32bd-c3df-4172-a89d-f173d6816926",
        "widget_id": "feecb679-a3cc-47ef-8fd4-600799f12a39"
    },
    "error": null
}
```

*connection_success*
``` javascript
{
    "success": true,
    "data": {
        "user_id": "054d0a9d-38ec-40cb-a31c-09b483242e4a",
        "country": "mx",
        "platform": "imss",
        "account_id": "472f02e8-6b24-43a7-b529-3f71d6ecc81c"
    },
    "error": null
}
```

*connection_error*
``` javascript
{
    "success": false,
    "error": {
        "code": "invalid_credentials",
        "message": "The username/password combination is wrong",
        "errors": null
    },
    "data": null
}
```

### Standalone

#### Available Methods

| Method   |  Descriptions                            | Params                              |
|----------| -----------------------------------------|-------------------------------------|
| on       | To add event listener subscribtions      | event: string, callback: Function   |
| render   | To render the widget                     | containerId: string, config: object | 
| destroy  | To remove the iframe and event listeners | N/A                                 |



```html
<div id="container"></div>
```

```js
  let widgetId = "YOUR_WIDGET_ID";
    let publicApiKey = "YOUR_PUBLIC_API_KEY";
    let renderConfig = {
      "configuration": {
        "hideConsent": true,
        "country": "mx"
      },
      appearance: {
        primaryColor: "#ea4c89",
        borderRadius: "9999px"
      }
    }

    let link = palenca.loadLink(publicApiKey, widgetId).then(link => {

      link.on("ready", () => {
        console.log("Widget is ready")
      })

      link.on("user_created", (event) => {
        console.log("User created", event)
      })

      link.on("connection_success", (event) => {
        console.log(`Connection success for userId ${event.data.user_id} and accountId ${event.data.account_id}`)
      })

      link.on("connection_error", (event) => {
        console.log(`Connection error ${event.data.error.code}`)
      })

      link.render("container", renderConfig);
      
      // You can destroy the iframe and event listeners with the destroy method
      window.addEventListener('unload', () => {
          link.destroy()
      })

    }, error => {
      console.log(error);
    })

```

### React

```js
import { loadLink, PalencaLinkReact } from '@palenca/palenca-link';
import { useCallback } from 'react';

// Make sure to call `loadLink` outside of a component’s render to avoid recreating the object
const linkPromise = loadLink('YOUR_PUBLIC_API_KEY', 'YOUR_WIDGET_ID');

const Home = () => {
  const handleEvent = useCallback((event: string, data: object) => {
    console.log(event);
    console.log(data)
  }, []);

  const options = {
    configuration: {
      hideConsent: true,
      country: 'mx',
    },
    appearance: {
      primaryColor: '#ea4c89',
      borderRadius: '999px',
    },
  };

  return (
      <div>
            <PalencaLinkReact
              link={linkPromise}
              options={options}
              onEvent={handleEvent}
            />
      </div>
  );
};

export default Home;

```