· 7 years ago · Dec 12, 2017, 05:14 PM
1use GuzzleHttpClient;
2use GuzzleHttpHandlerStack;
3use GuzzleHttpSubscriberOauthOauth1;
4
5public function callback() {
6 // This function is called by Magento before the user is sent to the OAuthForm.
7
8 $oauthConsumerKey = $_POST['oauth_consumer_key'];
9 $oauthConsumerSecret = $_POST['oauth_consumer_secret'];
10 $storeBaseUrl = $_POST['store_base_url'];
11 $oauthVerifier = $_POST['oauth_verifier'];
12
13 /** @var DrupalCoreConfigConfig $config */
14 $config = Drupal::service('config.factory')->getEditable('mage_ninja.settings');
15
16 $config->set('oauth_consumer_key', $oauthConsumerKey)->save();
17 $config->set('oauth_consumer_secret', $oauthConsumerSecret)->save();
18 $config->set('oauth_verifier', $oauthVerifier)->save();
19 $config->set('store_base_url', $storeBaseUrl)->save();
20
21 return new Response();
22 }
23
24public function submitForm(array &$form, FormStateInterface $form_state) {
25 /** @var DrupalCoreConfigImmutableConfig $config */
26 $config = $this->config('mage_ninja.settings');
27
28 /** @var string $consumerKey */
29 $consumerKey = $_GET['oauth_consumer_key'];
30
31 /** @var string $consumerCallback */
32 $consumerCallback = $_GET['success_call_back'];
33
34 /** @var string $integrationKey */
35 $integrationKey = $form_state->getValue('integration_key');
36
37 /** @var string $integrationSecret */
38 $integrationSecret = $form_state->getValue('integration_secret');
39
40 // Make sure the consumerKey sent in the request is the same as the one received from Magento
41 if($config->get('oauth_consumer_key') === $consumerKey) {
42 $handlerStack = HandlerStack::create();
43
44 $middleware = new Oauth1([
45 'consumer_key' => $config->get('oauth_consumer_key'),
46 'consumer_secret' => $config->get('oauth_consumer_secret'),
47 'verifier' => $config->get('oauth_verifier'),
48 'token_secret' => ''
49 ]);
50 $handlerStack->push($middleware);
51
52 $client = new Client([
53 'base_uri' => $config->get('store_base_url'),
54 'handler' => $handlerStack,
55 'auth' => 'oauth'
56 ]);
57
58 $response = $client->post('/oauth/token/request');
59 $body = (string)$response->getBody();
60
61 // Format $body into usable variables.
62 // $body = 'oauth_token=hp0blt5hlel4qfq02utc03a98xkgnv7b&oauth_token_secret=0e14acixb3l5nl6io0mj4x8ek0147c83'
63 $bodyArray = explode('&', $body);
64 $oauthToken = explode('=', $bodyArray[0]);
65 $oauthTokenSecret = explode('=', $bodyArray[1]);
66
67 /** @var DrupalCoreConfigConfig $config */
68 $config = Drupal::service('config.factory')->getEditable('mage_ninja.settings');
69
70 $config->set('oauth_token', $oauthToken)->save();
71 $config->set('oauth_token_secret', $oauthTokenSecret)->save();
72
73 $form_state->setResponse(new TrustedRedirectResponse($consumerCallback));
74 } else {
75 throw new Exception('Consumer key is invalid.');
76 }
77 }