Как получить доступ к данным таблицы, связанной с модулем в комплекте crm, используя REST API - PullRequest
0 голосов
/ 09 мая 2018
<code>   $entryArgs = array(
   'session' => $sessId,
  'module_name' => 'SecurityGroups',
  'query' => "securitygroups_users.securitygroup_id = 'id`enter code 
   here`'",
  'order_by' => '',
  'offset' => 0,
   'select_fields' => array('id','name'),
    'max_results' => 10,
    'deleted' => 0 );
   $module_result = restRequest('get_entry_list',$entryArgs);
   echo "<pre>";
   print_r($module_result);
   echo "
";

Я хочу получить данные из таблицы securitygroup_users в комплекте CRM через REST API. Но я ничего не получаю. Любая помощь будет оценена.

1 Ответ

0 голосов
/ 10 мая 2018

Если вы хотите написать собственный API для отдыха, перейдите по этой ссылке Custom API для отдыха

Расширение веб-сервисов Обзор

В руководстве будет показано, как добавить свои собственные пользовательские методы в API REST и SOAP или расширить существующие. Расширение API

В следующем примере будет продемонстрировано, как расширить API v4_1. Определение местоположения точки входа

Здесь вы определяете каталог, который будет содержать ваши новые точки входа REST и SOAP. Мы рекомендуем путь в следующем формате:

./custom/service/{version}_custom/

Фактическое расположение точек входа не имеет значения, однако использование такого пути позволит вам называть свои точки входа следующим образом:

http://{sugar_url}/custom/service/{version}_custom/rest.php http://{sugar_url}/custom/service/{version}_custom/soap.php

Определение класса SugarWebServiceImpl

Следующим шагом является определение нового класса SugarWebServiceImpl. Поскольку мы используем v4_1, нам нужно расширить файл 'service/v4_1/SugarWebServiceImplv4_1.php' и добавить наш новый метод. Для этого создадим файл:

./custom/service/v4_1_custom/SugarWebServiceImplv4_1_custom.php

<?php

    if(!defined('sugarEntry'))define('sugarEntry', true);
    require_once('service/v4_1/SugarWebServiceImplv4_1.php');
    class SugarWebServiceImplv4_1_custom extends SugarWebServiceImplv4_1
    {
        /*
         * Returns the session id if authenticated
         *
         * @param string $session
         * @return string $session - false if invalid.
         *
         */

        function example_method($session)
        {
            $GLOBALS['log']->info('Begin: SugarWebServiceImplv4_1_custom->example_method');
            $error = new SoapError();

            //authenticate
            if (!self::$helperObject->checkSessionAndModuleAccess($session, 'invalid_session', '', '', '',  $error))
            {
                $GLOBALS['log']->info('End: SugarWebServiceImplv4_1_custom->example_method.');
                return false;
            }
            return $session;
        }
    }
?>

Определение класса реестра

Далее мы определим класс реестра, который будет регистрировать нашу новую функцию. Этот файл будет находиться по адресу:

./custom/service/v4_1_custom/registry.php

<?php
    require_once('service/v4_1/registry.php');
    class registry_v4_1_custom extends registry_v4_1
    {
        protected function registerFunction()
        {
            parent::registerFunction();
            $this->serviceClass->registerFunction('example_method', array('session'=>'xsd:string'), array('return'=>'xsd:string'));
        }
    }
?>

Определение точки входа в REST

Эта точка входа в REST будет расположена по адресу:

./custom/service/v4_1_custom/rest.php

<?php
    chdir('../../..');
    require_once('SugarWebServiceImplv4_1_custom.php');
    $webservice_path = 'service/core/SugarRestService.php';
    $webservice_class = 'SugarRestService';
    $webservice_impl_class = 'SugarWebServiceImplv4_1_custom';
    $registry_path = 'custom/service/v4_1_custom/registry.php';
    $registry_class = 'registry_v4_1_custom';
    $location = 'custom/service/v4_1_custom/rest.php';
    require_once('service/core/webservice.php');
?>

Определение точки входа SOAP

Эта точка входа SOAP будет расположена по адресу:

./custom/service/v4_1_custom/soap.php

<?php
    chdir('../../..');
    require_once('SugarWebServiceImplv4_1_custom.php');
    $webservice_class = 'SugarSoapService2';
    $webservice_path = 'service/v2/SugarSoapService2.php';
    $webservice_impl_class = 'SugarWebServiceImplv4_1_custom';
    $registry_class = 'registry_v4_1_custom';
    $registry_path = 'custom/service/v4_1_custom/registry.php';
    $location = 'custom/service/v4_1_custom/soap.php';
    require_once('service/core/webservice.php');    
?>

API ИСПОЛЬЗОВАНИЯ ДАННЫХ МОДУЛЯ FETCH Привет, я получаю модуль данных, как это с помощью API, я получил много APIS для получения данных.

Вы должны написать этот API в

custom\clients\base\api\filename.php

<?php

header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept');
header('Access-Control-Allow-Headers: Authorization, Content-Type');
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Origin:", "*");


if (!defined('sugarEntry') || !sugarEntry)
    die('Not A Valid Entry Point');


require_once('include/SugarOAuth2/SugarOAuth2Server.php');
require_once('custom/include/api/CustomApiException.php');

class CustomApi extends ModuleApi {

    const CustomPortalAPIUser = 'b6ab0b1c-b371-0bb9-6653-570f2a0a5b47'; 

    /** @var RelateRecordApi */
    public function registerApiRest() {

        return array(

            'cRetrieve' => array(
                'reqType' => 'GET',
                'path' => array('portal', '<module>', '?'),
                'pathVars' => array('portal', 'module', 'record'),
                'method' => 'customRetrieveRecord',
                'shortHelp' => 'Returns a single record',
                'longHelp' => 'include/api/help/module_record_get_help.html',
            ),
        );
    }


    public function customAuthenticateUser($api, $args) {

        if (isset($api->request_headers['OAUTH_TOKEN'])) {
            $oauthServer = SugarOAuth2Server::getOAuth2Server();
            $oauthServer->verifyAccessToken($api->request_headers['OAUTH_TOKEN']);
            //$args_user['platform'] = $api->request_headers['OAUTH_TOKEN'];
        } else {
            //$args_user['platform'] = "base";
        }

        global $fields;

        require_once('clients/base/api/OAuth2Api.php');
        require_once('include/SugarOAuth2/SugarOAuth2Server.php');
        $args_user['platform'] = "base";
        $args_user['username'] = 'username';
        $args_user['password'] = 'password';
        $args_user['client_id'] = 'sugar';
        $args_user['grant_type'] = 'password';
        $args_user['client_secret'] = '';
        $args_user['current_language'] = 'en_us';
        $oAuth = new OAuth2Api();
        $token_data = $oAuth->token($api, $args_user);

        $admin = Administration::getSettings();

        if (isset($admin->settings['portal_defaultUser']) && !empty($admin->settings['portal_defaultUser'])) {
            $fields['assigned_user_id'] = json_decode(html_entity_decode($admin->settings['portal_defaultUser']));
        }
        return $token_data;
    }



    public function customRetrieveRecord($api, $args) {
        $is_authenticate = $this->customAuthenticateUser($api, $args);
        $result = parent::retrieveRecord($api, $args);
        if ($args['module'] == 'Module_name') {
            $result['data'] = self::data;
               your code and logic ....
        }
        return $result;
    }



}
...