Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/auth with API KEY #32

Merged
merged 12 commits into from
May 15, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
.history
composer.phar
/vendor/
.idea/
.php*
!.php_cs
!.php-cs-fixer.php
Expand Down
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
],
"homepage": "https://www.cocolis.fr",
"license": "MIT",
"version": "2.1.1",
"version": "2.1.2",
"require": {
"php": ">=5.3.0"
},
Expand Down
32 changes: 31 additions & 1 deletion docs/Introduction.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,37 @@ Le principe de la librairie étant essentiellement basé sur la **documentation
> Avant toute chose, vous devez avoir un compte développeur, vous trouverez plus d'information ici :
> [Demander un compte développeur](https://doc.cocolis.fr/docs/cocolis-api/docs/Tutoriel-impl%C3%A9mentation/Getting-Started.md#2-demander-un-compte-d%C3%A9veloppeur)

> Pour savoir comment obtenir votre token d'authentification vous pouvez lire [ceci](docs/Tutoriel-implémentation/Get-API-KEY.md).

Avec la librairie, vous pouvez vous authentifier facilement de cette façon et **une seule fois** :

<!-- theme: danger -->

> #### Mise à jour 2022
>
> Changement de la méthode d'authentification, à partir de maintenant nous recommandons l'authentification par clée API.

<!--
type: tab
title: Authentification recommandée (API KEY)
-->

```php
$client = Client::create(
[
'api_key' => 'mon_api_key',
'live' => false
]
);

// Contrairement à l'authentification dépréciée, celle-ci ne nécessite pas un sign-in.
```

<!--
type: tab
title: Authentification dépréciée (Tokens)
-->

```php
$client = Client::create(array(
'app_id' => 'mon_appid',
Expand All @@ -44,6 +73,8 @@ $client = Client::create(array(
$client->signIn(); // Cet appel fait l'authentification
```

<!-- type: tab-end -->

Vous n'avez plus qu'à utiliser l'objet `$client` pour effectuer un appel.

Par exemple, pour **vérifier la disponibilité** d'une Ride :
Expand Down Expand Up @@ -81,4 +112,3 @@ Si le token n'est plus valide, il suffit de refaire un `$client->signIn()`
## Environnements

Il existe **deux environnements**, l'environnement de test (**sandbox**) et l'environnement de **production**, vous pouvez en savoir plus [ici](https://doc.cocolis.fr/docs/cocolis-api/docs/Installation-et-utilisation/01-Environnements.md).

22 changes: 22 additions & 0 deletions docs/Tutorials/Get-API-KEY.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# Comment obtenir son token d'authentification

Tous les appels à l'API doivent se faire de manière authentifiée. Voici les étapes pour pouvoir faire votre premier appel à l'API.

Un **administrateur Cocolis** doit vous créer une **"API application"**, qui vous sera associée.

## Obtenir son token d'authentification

Rendez vous sur la [page de gestion](https://www.cocolis.fr/my-account/api-keys) de votre clé api, puis créer votre clé api.

<!--
focus: top
bg: primary
-->

![API KEY 1](https://res.cloudinary.com/cocolis-prod/image/upload/v1643208527/Documentation/api/dev/tuto_api_key_bowouk.png 'Allez dans la page de gestion de votre clé API sur votre profil, puis créer votre clé API')

Gardez précieusement le token généré. C'est votre mot de passe API, toute personne ayant accès à ce token pourra se faire passer pour vous via des appels API.

![API KEY 2](https://res.cloudinary.com/cocolis-prod/image/upload/v1643208527/Documentation/api/dev/tuto_api_key_2_irbwqh.png 'Une fois créer, gardez la précieusement, elle ne sera plus affichée')

**Ce token ne pourra plus être récupéré plus tard, le seul moyen sera d'en régénérer un nouveau.**
119 changes: 67 additions & 52 deletions docs/Tutorials/Getting-Started.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ Le prélèvement du montant de la livraison est effectué sur le compte MangoPay

## 2. Demander un compte développeur

Vous pouvez demander la création d'un compte développeur en remplissant [ce formulaire](https://docs.google.com/forms/d/e/1FAIpQLSe9DZntip2_5jSR5BVRBD8S84vtBdeI834K9-Mj7euLCNit4A/viewform?usp=pp_url). Une clé API vous sera alors fournie pour **Sandbox** et **Production**.
Vous pouvez demander la création d'un compte développeur en remplissant [ce formulaire](https://docs.google.com/forms/d/e/1FAIpQLSe9DZntip2_5jSR5BVRBD8S84vtBdeI834K9-Mj7euLCNit4A/viewform?usp=pp_url).

## 3. Authentification

Expand All @@ -24,6 +24,27 @@ Toutes les requêtes API doivent être authentifiées grâce à notre librairie

1. Créez un Client HTTP avec notre API en vous authentifiant :

<!--
type: tab
title: Authentification recommandée (API KEY)
-->

```php
$client = Client::create(
[
'api_key' => 'mon_api_key',
'live' => false
]
);

// Contrairement à l'authentification dépréciée, celle-ci ne nécessite pas un sign-in.
```

<!--
type: tab
title: Authentification dépréciée (Tokens)
-->

```php
$client = Client::create(array(
'app_id' => 'mon_appid',
Expand All @@ -33,8 +54,9 @@ $client = Client::create(array(
$client->signIn(); // Cet appel fait l'authentification
```

> La librairie PHP se chargera d'utiliser vos tokens d'authentification pour vous authentifier lors de vos prochains appels
<!-- type: tab-end -->

> La librairie PHP se chargera d'utiliser vos tokens d'authentification pour vous authentifier lors de vos prochains appels

## 4. Gérer l'expiration d'un token

Expand All @@ -58,12 +80,14 @@ Si le token n'est plus valide, il suffit de refaire un `$client->signIn()`
## 5. Eligibilité d'une livraison

<!-- theme: warning -->

> ### Tous nos prix sont en centimes

<!--
type: tab
title: Doc
-->

Pour savoir si la livraison Cocolis est éligible d'un code postal A à un code postal B, il faut appeler l'URL :

```php
Expand All @@ -74,47 +98,39 @@ $client->getRideClient()->canMatch(75000, 31400, 10); // Code postal de départ,

```json json_schema
{
"title": "Response",
"type": "object",
"properties": {
"from": {
"type": "object",
"properties": {
"postal_code": {
"type": "string",
"description": "Code postal du point de départ"
}
},
"required": [
"postal_code"
]
},
"to": {
"type": "object",
"properties": {
"postal_code": {
"type": "string",
"description": "Code postal du point d'arrivée"
}
},
"required": [
"postal_code"
]
},
"volume": {
"type": "number",
"description": "Somme des volumes en m3 des produits à livrer"
},
"content_value": {
"type": "number",
"description": "Valeur de la livraison en Centimes (Valeur de la commande)"
"title": "Response",
"type": "object",
"properties": {
"from": {
"type": "object",
"properties": {
"postal_code": {
"type": "string",
"description": "Code postal du point de départ"
}
},
"required": ["postal_code"]
},
"required": [
"from",
"to",
"volume"
]
"to": {
"type": "object",
"properties": {
"postal_code": {
"type": "string",
"description": "Code postal du point d'arrivée"
}
},
"required": ["postal_code"]
},
"volume": {
"type": "number",
"description": "Somme des volumes en m3 des produits à livrer"
},
"content_value": {
"type": "number",
"description": "Valeur de la livraison en Centimes (Valeur de la commande)"
}
},
"required": ["from", "to", "volume"]
}
```

Expand Down Expand Up @@ -174,6 +190,7 @@ La réponse sera un stdClass du format :
## 6. Création d'une annonce :

<!-- theme: warning -->

> ### Tous nos prix sont en centimes

Quand une vente a été réalisée sur votre site avec notre mode de livraison, il faut ensuite la créer sur Cocolis. Nous vous recommandons de la créer 30 minutes après le paiement pour gérer des cas d'annulation rapide sur votre site.
Expand Down Expand Up @@ -239,6 +256,7 @@ $params = [
];
$ride = $rideClient->create($params);
```

---

```json json_schema
Expand Down Expand Up @@ -281,11 +299,10 @@ type: tab
title: Paramètres
-->


| Paramètre | Valeur | Commentaire |
| ------------- | :-----------: | -----: |
| :domain | `www.cocolis.fr` | En sandbox, le domaine sera `sandbox.cocolis.fr` |
| :buyer_tracking | ride.buyer_tracking | Lors de la création de la ride, nous vous avons renvoyé ce paramètre dans la clé `buyer_tracking` |
| Paramètre | Valeur | Commentaire |
| --------------- | :-----------------: | ------------------------------------------------------------------------------------------------: |
| :domain | `www.cocolis.fr` | En sandbox, le domaine sera `sandbox.cocolis.fr` |
| :buyer_tracking | ride.buyer_tracking | Lors de la création de la ride, nous vous avons renvoyé ce paramètre dans la clé `buyer_tracking` |

> Nous vous conseillons de remonter cette information sur la page de suivi de commande de votre client.

Expand Down Expand Up @@ -326,10 +343,10 @@ type: tab
title: Paramètres
-->

| Paramètre | Valeur | Commentaire |
| ------------- | :-----------: | -----: |
| :domain | `www.cocolis.fr` | En sandbox, le domaine sera `sandbox.cocolis.fr` |
| :seller_tracking | ride.seller_tracking | Lors de la création de la ride, nous vous avons renvoyé ce paramètre dans la clé `seller_tracking` |
| Paramètre | Valeur | Commentaire |
| ---------------- | :------------------: | -------------------------------------------------------------------------------------------------: |
| :domain | `www.cocolis.fr` | En sandbox, le domaine sera `sandbox.cocolis.fr` |
| :seller_tracking | ride.seller_tracking | Lors de la création de la ride, nous vous avons renvoyé ce paramètre dans la clé `seller_tracking` |

> Nous vous conseillons de remonter cette information sur la page de suivi de commande de votre client.

Expand All @@ -351,5 +368,3 @@ https://sandbox.cocolis.fr/rides/seller/7E20B021BF8721A2
```

<!-- type: tab-end -->


5 changes: 5 additions & 0 deletions docs/toc.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,11 @@
"title": "Implémentation standard",
"uri": "docs/Tutoriel-implémentation/Getting-Started.md"
},
{
"type": "item",
"title": "Comment obtenir un token d'authentification",
"uri": "docs/Tutorials/Get-API-KEY.md"
},
{
"type": "item",
"title": "Webhooks",
Expand Down
32 changes: 27 additions & 5 deletions src/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ class Client
// Local informations
private static $_app_id;
private static $_password;
private static $_api_key;
private static $_live = false;

private static $_client;
Expand Down Expand Up @@ -91,6 +92,16 @@ public static function setAuth($auth)
self::$_auth = $auth;
}

public static function getApiKey()
{
return self::$_api_key;
}

public static function setApiKey($api_key)
{
self::$_api_key = $api_key;
}

public static function getCurrentAuthInfo()
{
return self::$_auth;
Expand All @@ -117,18 +128,26 @@ public static function create(array $auth)
{
$client = new static();

if (!isset($auth['app_id']) || empty($auth['app_id'])) {
if (empty($auth['api_key']) && empty($auth['app_id']) && empty($auth['password'])) {
throw new \InvalidArgumentException('Key api_key is missing or your app_id and password are missing');
} elseif (empty($auth['app_id']) && !empty($auth['password'])) {
throw new \InvalidArgumentException('Key app_id is missing');
} elseif (!isset($auth['password']) || empty($auth['password'])) {
} elseif (empty($auth['password']) && !empty($auth['app_id'])) {
throw new \InvalidArgumentException('Key password is missing');
}
btnalexandre marked this conversation as resolved.
Show resolved Hide resolved

if (isset($auth['live'])) {
self::setLive($auth['live']);
}

self::setAppId($auth['app_id']);
self::setPassword($auth['password']);
if (!empty($auth['api_key'])) {
self::setApiKey($auth['api_key']);
}

if (!empty($auth['password']) && !empty($auth['app_id'])) {
self::setAppId($auth['app_id']);
self::setPassword($auth['password']);
}

self::setClient($client);

Expand Down Expand Up @@ -168,11 +187,14 @@ public function callAuthentificated($url, $method = 'GET', $body = [])
{
$client = $this->getHttpClient();

if (self::getCurrentAuthInfo()) {
if (self::getApiKey()) {
$client->appendRequestHeader('X-API-KEY', self::getApiKey());
} elseif (self::getCurrentAuthInfo()) {
foreach (self::getCurrentAuthInfo() as $key => $value) {
$client->appendRequestHeader($key, $value);
}
}

return $client->$method(self::getBaseUrl() . $url, $body);
}
}
3 changes: 2 additions & 1 deletion src/Version.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ class Version
{
public function __toString(): string
{
return '2.0.2';
$json = json_decode(file_get_contents('./composer.json'));
return $json->version;
btnalexandre marked this conversation as resolved.
Show resolved Hide resolved
}
}
Loading
Loading