2
2
3
3
namespace Bigcommerce \Api ;
4
4
5
+ use Firebase \JWT \JWT ;
5
6
use \Exception as Exception ;
6
7
7
8
/**
@@ -16,6 +17,7 @@ class Client
16
17
static private $ resource ;
17
18
static private $ path_prefix = '/api/v2 ' ;
18
19
static private $ client_id ;
20
+ static private $ client_secret ;
19
21
static private $ auth_token ;
20
22
static private $ store_hash ;
21
23
static private $ stores_prefix = '/stores/%s/v2 ' ;
@@ -94,6 +96,9 @@ public static function configureOAuth($settings)
94
96
self ::$ client_id = $ settings ['client_id ' ];
95
97
self ::$ auth_token = $ settings ['auth_token ' ];
96
98
self ::$ store_hash = $ settings ['store_hash ' ];
99
+
100
+ self ::$ client_secret = isset ($ settings ['client_secret ' ]) ? $ settings ['client_secret ' ] : null ;
101
+
97
102
self ::$ api_path = self ::$ api_url . sprintf (self ::$ stores_prefix , self ::$ store_hash );
98
103
self ::$ connection = false ;
99
104
}
@@ -392,6 +397,41 @@ public static function getAuthToken($object)
392
397
return $ connection ->post (self ::$ login_url . '/oauth2/token ' , $ context );
393
398
}
394
399
400
+ /**
401
+ * generate login token
402
+ *
403
+ * @param int $id
404
+ * @param string $redirectUrl
405
+ * @param string $requestIp
406
+ * @return mixed
407
+ * @throws Exception
408
+ */
409
+ public static function getCustomerLoginToken ($ id , $ redirectUrl = '' , $ requestIp = '' )
410
+ {
411
+ if (empty (self ::$ client_secret )) {
412
+ throw new Exception ('Cannot sign customer login tokens without a client secret ' );
413
+ }
414
+
415
+ $ payload = array (
416
+ 'iss ' => self ::$ client_id ,
417
+ 'iat ' => time (),
418
+ 'jti ' => bin2hex (random_bytes (32 )),
419
+ 'operation ' => 'customer_login ' ,
420
+ 'store_hash ' => self ::$ store_hash ,
421
+ 'customer_id ' => $ id
422
+ );
423
+
424
+ if (!empty ($ redirectUrl )) {
425
+ $ payload ['redirect_to ' ] = $ redirectUrl ;
426
+ }
427
+
428
+ if (!empty ($ requestIp )) {
429
+ $ payload ['request_ip ' ] = $ requestIp ;
430
+ }
431
+
432
+ return JWT ::encode ($ payload , self ::$ client_secret , 'HS256 ' );
433
+ }
434
+
395
435
/**
396
436
* Pings the time endpoint to test the connection to a store.
397
437
*
0 commit comments