Magento 2: Programmatically create, activate and authorize a ‘New Integration’

The question:

I have to create, activate and authorize a ‘New Integration’ programmatically. And then return it’s ‘Access Token’.
I followed the guide: http://devdocs.magento.com/guides/v2.0/howdoi/webapi/integration.html but unable to solve.

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

// Code to initiate Object Manager
use MagentoFrameworkAppBootstrap;
include_once('../app/bootstrap.php');

$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();


//Set your Data
$name = 'Your-Integration-Name';
$email = 'Set-Your-EmailId';
$endpoint = 'Set-Your-Url';


// Code to check whether the Integration is already present or not
$integrationExists = $objectManager->get('MagentoIntegrationModelIntegrationFactory')->create()->load($name,'name')->getData();
if(empty($integrationExists)){
    $integrationData = array(
        'name' => $name,
        'email' => $email,
        'status' => '1',
        'endpoint' => $endpoint,
        'setup_type' => '0'
    );
    try{
        // Code to create Integration
        $integrationFactory = $objectManager->get('MagentoIntegrationModelIntegrationFactory')->create();
        $integration = $integrationFactory->setData($integrationData);
        $integration->save();
        $integrationId = $integration->getId();$consumerName = 'Integration' . $integrationId;


        // Code to create consumer
        $oauthService = $objectManager->get('MagentoIntegrationModelOauthService');
        $consumer = $oauthService->createConsumer(['name' => $consumerName]);
        $consumerId = $consumer->getId();
        $integration->setConsumerId($consumer->getId());
        $integration->save();


        // Code to grant permission
        $authrizeService = $objectManager->get('MagentoIntegrationModelAuthorizationService');
        $authrizeService->grantAllPermissions($integrationId);


        // Code to Activate and Authorize
        $token = $objectManager->get('MagentoIntegrationModelOauthToken');
        $uri = $token->createVerifierToken($consumerId);
        $token->setType('access');
        $token->save();

    }catch(Exception $e){
        echo 'Error : '.$e->getMessage();
    }
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment