Создание тикета zoho с помощью скрипта Google Apps - PullRequest
0 голосов
/ 20 марта 2020

Я пытаюсь использовать zoho desk api в скрипте Google Apps.

Я пытаюсь создать тикет через скрипт Google. Но получаю ошибку. Принимая во внимание, что если я делаю это в PHP, он работает нормально.

Пожалуйста, найдите оба кода для справки:

PHP КОД, который работает

            $auth_token = '12345ab';//your_auth_token
            $org_id=12345; //your_organization_id

            $ticket_data=array(
                "departmentId"=>$getdepartmentid,
                "contactId"=>$getcontactid,
                "subject"=>$ticket_subject,
                "description"=>$ticket_desc,
                "priority"=>$priority,
                "status"=>$ticketstatus,
                "email"=>$contact_email,
                "classification"=>$classification,
                "channel"=>"Application"
            );

        $headers=array(
            "Authorization: $auth_token",
            "orgId: $org_id",
            "contentType: application/json; charset=utf-8",
        );

        $url="https://desk.zoho.in/api/v1/tickets";

        $ticket_data=(gettype($ticket_data)==="array")? json_encode($ticket_data):$ticket_data;

        $ch= curl_init($url);
        curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,TRUE);
        curl_setopt($ch,CURLOPT_POST,TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS,$ticket_data); //convert ticket data array to json
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);    


        $response= curl_exec($ch);
        $info= curl_getinfo($ch);

СЦЕНАРИЙ GOOGLE APPS (который не работает)

        var authtoken = "12345ab"; //your_auth_token
        var org_id=12345; //your_organization_id
        var department=23220000000057620; // ID of department
        var contact=23220000000066959; //ID of customer
        var subject=location_urgent_inbox_folder_name + ' /' + Name_of_file_to_be_attached;
        var description="Ticked via drive";
        var status="open";
        const ticketData = {
         subject: subject, 
         departmentId: department, // Replace this with whatever yours is.
         contactId: contact, // Replace this with whatever yours is.
         description: description,
         status: status
        };
        const zohoUrl = 'https://desk.zoho.in/api/v1/tickets';
        try {
          var response = UrlFetchApp.fetch(zohoUrl, {
          "method": 'POST',
          "muteHttpExceptions": true,
           "headers": {
           Authorization: authtoken,
          orgId: org_id,
          contentType: 'application/json',
         },
        "payload": JSON.stringify(ticketData),
        });
        Logger.log(response.getContentText());
        const parsed = JSON.parse(response.getContentText());
        } catch (error) {
          Logger.log(error.toString());
        }             

Ответы [ 2 ]

1 голос
/ 20 марта 2020

Предполагая, что я смотрю на правильный раздел нужной документации (https://desk.zoho.com/DeskAPIDocument#Tickets_Createaticket), я думаю, что это ваши проблемы:

  1. Серверный JSON кодированный ответ не содержит message свойства, следовательно Logger.log(result.message); logs undefined. (Возможно, попытайтесь зарегистрировать response.getContentText(), чтобы увидеть, какие свойства доступны в вашем случае, или обратитесь к документации API.) В отправляемом запросе отсутствуют заголовки
  2. Authorization и orgId. (Похоже, что автокены устарели (https://desk.zoho.com/DeskAPIDocument#Authentication), и вместо этого вам нужно использовать OAuth 2.0 (https://desk.zoho.com/DeskAPIDocument#OauthTokens) .)
  3. Данные необходимо отправлять в тело запроса. (Похоже, вы отправляете его в строке запроса.)
  4. Я не читал документацию подробно, но не вижу упоминания о параметрах строки запроса authtoken и JSONString (CTRL + F не возвращает совпадений). Поэтому вы можете захотеть избавиться от них в своем коде и вместо этого следовать тому, что написано в документации.

Приведенный ниже код не проверен и не будет работать (так как вам нужно заменить его своими учетными данными) , Но это должно дать вам представление о том, как вы можете выполнить sh.

// See: https://desk.zoho.com/DeskAPIDocument#Tickets#Tickets_Createaticket
// Required: subject, departmentId, contactId
const ticketData = {
    subject: location_urgent_inbox_folder_name + ‘ /’ + Name_of_file_to_be_attached, // Taken from your question. Presume these are declared, valid and in scope.
    departmentId: '12345', // Replace this with whatever yours is.
    contactId: '12345', // Replace this with whatever yours is.
    description: 'Ticked via drive',
    status: 'open'
};

const zohoUrl = 'https://desk.zoho.in/api/v1/tickets';

try {
    // See: https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app#fetchurl,-params
    const response = UrlFetchApp.fetch(zohoUrl, {
        method: 'POST',
        contentType: 'application/json',
        headers: {
            orgId: '12345' // Replace this with whatever yours is.
            Authorization: 'Zoho-oauthtoken ....' // See: https://desk.zoho.com/DeskAPIDocument#OauthTokens
        },
        payload: JSON.stringify(ticketData),
    });
    Logger.log(response.getContentText());
    const parsed = JSON.parse(response.getContentText());
} catch (error) {
   Logger.log(error.toString());
}

Я никогда не работал ни с одним из API Zoho и некоторое время не работал с Google Apps Script, поэтому извиняюсь, если что-то упустил.

0 голосов
/ 26 марта 2020

Проблема решена, публикация ответа, чтобы он мог кому-то помочь

         //create ticket in zoho

        var authtoken = "abcd"; //your_auth_token
        var org_id="12345"; //your_organization_id
        var department="54321"; // ID of department in which ticket to be raised
        var contact="9999"; //ID of customer
        var subject="Ticket via google script";
        var description="Ticket via google script";
        var status="open";
        const ticketData = {
           subject: subject, 
           departmentId: department, // Replace this with whatever yours is.
           contactId: contact, // Replace this with whatever yours is.
           description: description,
           status: status
        };
        const zohoUrl = 'https://desk.zoho.in/api/v1/tickets';
        try {
          var response = UrlFetchApp.fetch(zohoUrl, {
          "method": 'POST',
          "muteHttpExceptions": true,
          "headers": {
           Authorization: authtoken,
           orgId: org_id,
           contentType: 'application/json',
         },
         "payload": JSON.stringify(ticketData),
         });
         const parsed = JSON.parse(response.getContentText());
         } catch (error) {
          Logger.log(error.toString());
         }             
...