Bonjour,

je débute sur Silex ; j'ai commencé à me créer un projet avec login, accès bdd, etc... pour une application interne.
La structure de mon projet est la suivante :
composer.json
composer.lock
vendor/
 |-> autoload.php
 |-> composer/
 |-> doctrine/
 |-> monolog/
 |-> pimple/
 |-> silex/
 |-> swiftmailer/
 |-> symfony/
 L-> twig/
app/
 |-> config/
 L-> views/
src/
 |-> app.php
 |-> routes.php
 L-> MyAppliName/
|-> Controller/
|-> Entity/
|-> Form/
|-> Repository/
L-> Service/
web/ L->index.php

Et là, je bloque pour ajouter et utiliser correctement une librairie externe à mon projet Silex.
Il s'agit de l'API de Sellsy, permettant d’interagir directement avec Sellsy (CRM + facturation) sans utiliser l’interface web du service.
Cette API est écrite en PHP et elle utilise OAuth. (La description ici : http://api.sellsy.fr/documentation/oauth)

Mon composer.json contient
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
"autoload": {
        "psr-0": {"MyAppliName": "src/"}
    }
J'ai donc installer dans mon Silex les classes de l'API Sellsy dans src/MyAppliName/Service/class :

  • SellsyConnect.php utilisant la classe Oauth native à PHP :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
     
    /*
     * @desc Sellsy Connect, offer stuff to use the api. Singleton class
     */
    class sellsyConnect {
     
    	/*
    	 * the api urls
    	 */
     
    	private static $api_url			= "https://apifeed.sellsy.com/0/";
    	private static $req_token_url	= "https://apifeed.sellsy.com/0/request_token";
    	private static $acc_token_url	= "https://apifeed.sellsy.com/0/access_token";
     
    	/*
    	 * enabling oauth debug mode
    	 */
    	private static $debug = true;
     
    	/*
    	 * your consumer token/secret (consumer is your application)
    	 */
    	private static $consumer_key = "{{consumer_token}}";
    	private static $consumer_Secret = "{{consumer_secret}}";
     
    	private static $callback_url = "{{your_callback_url}}";
    	/*
    	 * singleton stuff
    	 */
    	private static $instance;
    	private static $oauth_client;
     
    	/**
    	 * @desc load new oauth instance
    	 */
    	private function __construct() {
    		$oauth_client = new Oauth(self::$consumer_key, self::$consumer_Secret, PLAINTEXT, OAUTH_AUTH_TYPE_FORM);
    		if (self::$debug){ $oauth_client->enableDebug(); }
    		self::$oauth_client = $oauth_client;
    	}
     
    	/**
    	 * @desc singleton
    	 * @return type 
    	 */
    	public static function load() {
    		if (!isset(self::$instance)) {
    			$c = __CLASS__;
    			self::$instance = new $c;
    		}
    		return self::$instance;
        }
     
    	/**
    	 * @desc check for token in storage or redirect to the loggin page
    	 * @return type 
    	 */
    	public function checkApi() {
     
    		if (!isset($_REQUEST['oauth_token']) && !sellsyTools::storageGet('step')) { 
    			sellsyTools::storageSet('step', 'getRequestToken');
    		}
     
    		try {	 
     
    			if (sellsyTools::storageGet('step') == "getRequestToken"){	
    				$oauth_datas = self::$oauth_client->getRequestToken(self::$req_token_url . "?oauth_callback=" . self::$callback_url);
    				sellsyTools::storageSet('oauth_token_secret', $oauth_datas['oauth_token_secret']);
    				sellsyTools::storageSet('step', 'getAccessToken');
    				header('Location: '.$oauth_datas['authentification_url']."?oauth_token=".$oauth_datas['oauth_token']);
    				exit;
    			}
     
    			if (sellsyTools::storageGet('step') == "getAccessToken"){
    				self::$oauth_client->setToken($_REQUEST['oauth_token'], sellsyTools::storageGet('oauth_token_secret'));
    				$oauth_datas = self::$oauth_client->getAccessToken(self::$acc_token_url, null, $_REQUEST['oauth_verifier']);
    				sellsyTools::storageSet('oauth_token', $oauth_datas['oauth_token']);
    				sellsyTools::storageSet('oauth_token_secret', $oauth_datas['oauth_token_secret']);
    				sellsyTools::storageSet('step', 'accessApi');
    			}
     
    			if (!sellsyTools::storageGet('step')) {
    				sellsyTools::storageSet('step', 'getRequestToken');
    				header('Location : index.php');
    			}
     
    		} catch(OAuthException $E){
    			sellsyTools::storageSet('step', 'getRequestToken');
    			sellsyTools::storageSet('oauth_error', self::$oauth_client->getLastResponse());
    		}
    	}
     
    	/**
    	 * @desc request the api
    	 * @param type $requestSettings
    	 * @return type 
    	 */
    	public function requestApi($requestSettings, $showJSON=false) {
     
    		try {
    			if (sellsyTools::storageGet('step') == 'accessApi'){
    				self::$oauth_client->setToken(
    						sellsyTools::storageGet('oauth_token'), 
    						sellsyTools::storageGet('oauth_token_secret'));
    				self::$oauth_client->fetch(
    						self::$api_url, array( 
    							'request' => 1, 
    							'io_mode' =>  'json', 
    							'do_in' => json_encode($requestSettings)), 
    							OAUTH_HTTP_METHOD_POST
    						);
     
    				$back = json_decode(self::$oauth_client->getLastResponse());
    				if ($showJSON){
    					self::debug(self::$oauth_client->getLastResponse()); exit;
    				}
    				if ($back->status == 'error'){
    					sellsyTools::storageSet('process_error', $back->error);
    				} 
    				return $back;
    			}
    		} catch(OAuthException $E){
    			sellsyTools::storageSet('step', 'getRequestToken');
    			sellsyTools::storageSet('oauth_error', self::$oauth_client->getLastResponse());
    		}
     
    	}
     
    	/**
    	 * @desc logout the current user
    	 */
    	public function logout(){
    		sellsyTools::storageReset();
    		$this->checkApi();
    		header('Location: index.php');
    	}
     
    	/**
    	 * @desc get the api infos
    	 */
    	public function getInfos(){
    			$requestSettings = array(
    			'method' => 'Infos.getInfos',
    			'params' => array(),
    		);
    		return $this->requestApi($requestSettings);
    	}
     
    	/**
    	 * @desc gift, debug function.
    	 * @param type $value
    	 * @param type $message 
    	 */
    	public static function debug($value=NULL, $message=null) {
     
    		$trace = debug_backtrace();
    		$fichier = basename($trace[0]["file"]);
    		$ligne = $trace[0]["line"];
    		$print_trace = create_function('$trace','
    		  unset($trace[0]);
    		  $disp = null;
    		  if (count($trace) > 0) {
    			 $disp = "<ul class=\"caller\">";
    			 foreach ($trace as $entry) {
    				$disp .= "<li class=\"caller\">Call : <b>";
    				if (isset($entry["class"])) {
    				   $disp .= $entry["class"] . "::" . $entry["function"];
    				} else {
    				   $disp .= $entry["function"];
    				}
    				$disp .= "()</b>";
    				if (isset($entry["file"])) {
    				   $disp .= "<br>Into : <i>";
    				   $disp .= $entry["file"];
    				   $disp .= " on line " . $entry["line"];
    				   $disp .= "</i>";
    				}
    				$disp .= "</li>";
    			 }
    			 $disp .= "</ul>";
    		  }
    		  return $disp;
    		');
     
    		$intro = '<div class="file">Into : ' . $fichier . " on line " . $ligne . "</div>";
     
    		$disp = ''
    			. PHP_EOL . '<style>'
    			. PHP_EOL . 'div.Debug {text-align:left; }'
    			. PHP_EOL . 'div.Debug pre {padding:10px; color:#333333; background-color:#DDDDDD; font-family: mono; font-size: 9pt; line-height:10pt;}'
    			. PHP_EOL . 'div.Debug .file {color:#060606; font-style:italic; padding-bottom:5px;}'
    			. PHP_EOL . 'div.Debug .message {color:#006600;}'
    			. PHP_EOL . 'div.Debug .stabilo {background-color:yellow; padding-left:3px; padding-right:3px;}'
    			. PHP_EOL . 'div.Debug .caller {color:#C0222A; list-style:square; margin:5px; line-height:9pt;}'
    			. PHP_EOL . 'div.Debug pre strong em {color:#993300;}'
    			. PHP_EOL . '/* fin styles pour Debug */'
    			. PHP_EOL . '</style>'
    			. PHP_EOL;
     
    		$disp .= PHP_EOL . PHP_EOL . '<!-- START DEBUG -->' . PHP_EOL . '<div class="Debug">' . PHP_EOL . '<pre>' . PHP_EOL;
     
    		if (is_object($value)) {
    			$disp .= $intro . '<span class="message">' . $message . '</span> => ';
    			$disp .= print_r($value, true);
    			$disp .= $print_trace($trace);
    		} elseif (is_array($value)) {
    			$disp .= $intro . '<span class="message">' . $message . '</span> => ';
    			$disp .= print_r($value, true);
    			$disp .= $print_trace($trace);
    		} elseif (is_bool($value)){
    			$disp .= $intro . '<span class="message">' . $message . '</span> => ' . ucfirst(gettype($value)) . PHP_EOL;
    			if ($value) {
    				$value = 'True'.PHP_EOL;
    			} else{
    				$value = 'False'.PHP_EOL;
    			}
    			$disp .= '{' . PHP_EOL . '    [] => ' . $value . '}' . PHP_EOL;
    			$disp .= $print_trace($trace);
    		} elseif (is_null($value)){
    			$disp .= $intro . '<span class="stabilo">' . $message . '</span>';
    			$disp .= $print_trace($trace);
    		} elseif (is_string($value) && is_file($value)) {
    			$disp .= $intro . '<span class="message">' . $message . '</span> => File' . PHP_EOL;
    			$disp .= '{' . PHP_EOL . '    [] => ' . $value . PHP_EOL . '}' . PHP_EOL;
    		} else {
    			$disp .= $intro . '<span class="message">' . $message . '</span> => ' . ucfirst(gettype($value)) . PHP_EOL;
    			$disp .= '{' . PHP_EOL . '    [] => ' . $value . PHP_EOL . '}' . PHP_EOL;
    			$disp .= $print_trace($trace);
    		}
    		$disp .= '</pre>' . PHP_EOL . '</div>' . PHP_EOL . '<!-- END DEBUG -->' . PHP_EOL . PHP_EOL;
    		echo $disp;
     
    	}
     
    }
  • SellsyTools.php, une classe d'utilitaires :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
     
    /**
     * @desc offered dev tools
     */
    class sellsyTools {
     
    	/**
    	 * @desc api storage, here i use SESSION, but feel free
    	 * @param type $name
    	 * @param type $value
    	 * @return type 
    	 */
    	public static function storageSet($name, $value){
    		$_SESSION[$name] = $value;
    		return true;
    	}
     
    	/**
    	 * @desc api storage, here i use SESSION, but feel free
    	 * @param type $name
    	 * @return type 
    	 */
    	public static function storageGet($name){
    		if (isset($_SESSION[$name])){
    			return $_SESSION[$name];
    		} else {
    			return false;
    		}
    	}
     
    	/**
    	 * @desc api storage, here i use SESSION, but feel free
    	 * @param type $name 
    	 */
    	public static function storageUnset($name){
    		if (isset($_SESSION[$name])){
    			unset($_SESSION[$name]);
    		}
    	}
     
    	/*
    	 * @desc destroy the current storage 
    	 */
    	public static function storageReset(){
    		session_destroy();
    	}
     
    	/**
    	 * @desc translate to timestamp
    	 * @param type $date
    	 * @return type 
    	 */
    	public static function frToTimestamp($date) {
    	  list($day, $month, $year) = explode('/', $date);
    	  $timestamp = mktime(0, 0, 0, $month, $day, $year);
    	  return $timestamp;
    	}
     
    	/**
    	 * display errors
    	 */
    	public static function showErrors(){
    		if (sellsyTools::storageGet('process_error')){?>
    			<div class="alert alert-error">
    				<a class="close" data-dismiss="alert">×</a>
    				<strong>process_error detected in the api response : </strong>
    				<strong>Code</strong> : <? echo sellsyTools::storageGet('process_error')->code ?>
    				<strong>Message</strong> : <? echo sellsyTools::storageGet('process_error')->message ?>
    				<strong>More</strong> : <? echo sellsyTools::storageGet('process_error')->more ?>
    			</div> 	
    		<?} 
     
    		if (sellsyTools::storageGet('oauth_error')){?>
    			<div class="alert alert-error">
    				<a class="close" data-dismiss="alert">×</a>
    				<strong>oauth_error detected in the api response : </strong>
    				<strong>Message</strong> : <? echo sellsyTools::storageGet('oauth_error') ?>
    			</div> 	
    		<?} 
     
    		sellsyTools::storageUnset('process_error');
    		sellsyTools::storageUnset('oauth_error');
    	}
     
    }


Mon application étant privée (pas d'authentification tiers), j'ai aussi ajouté dans src/MyAppliName/Service, le fichier sellsy.php contenant :
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
 
/*
 * initliase api
 */
require_once('class/sellsyconnect.php');
require_once('class/sellsytools.php');
 
/**
 * For private apps only
 */
sellsyTools::storageSet('oauth_token', '{{token_utilisateur}}');
sellsyTools::storageSet('oauth_token_secret', '{{secret_utilisateur}}');
sellsyTools::storageSet('step', 'accessApi');
 
/*
 * check if the user is logged
 */
sellsyConnect::load()->checkApi();
 
/*
 * load api infos into session
 */
if (!sellsyTools::storageGet('infos')){
	sellsyTools::storageSet('infos', sellsyConnect::load()->getInfos());
}
et dans mon index.php, j'ai ajouté :
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
require __DIR__.'/../src/MyAppliName/Service/sellsy.php';
Maintenant, je voudrais savoir comment je dois faire pour avoir accès aux fonctions de cette API dans mon projet, dans un controller par exemple, comme celui pour l'index :
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
namespace MyAppliName\Controller;

use Silex\Application;
use Symfony\Component\Form\FormError;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Validator\Constraints as Assert;

class IndexController
{
	public function indexAction(Request $request, Application $app)
    {
        //Récupérer ici les données de l'API

        $data = array(
            //données de l'API
        );
        return $app['twig']->render('index.html.twig', $data);
    }
}
En php from scratch ou dans Wordpress, il suffit de le faire avec une requête à l'API, comme par exemple pour récupérer un client :
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
 
$request = array(
	'method' => 'Client.getOne',
	'params' => array( 
		'clientid'	=>  {{clientid}} 
	)
);
$client = sellsyConnect::load()->requestApi($request);
sellsyTools::showErrors();
Mais là ça me fait une belle page blanche...
Merci pour votre aide !!!