edy hub

プログラミングやライフスタイルについて書き綴っています

RailsでZendeskAPIを使ってチケット情報を取得する

準備

API TOKENの発行をしてください

ご自身の管理画面の /agent/admin/api/settings から発行可能です。

https://<your site>.zendesk.com/agent/admin/api/settings

手順

Gemの導入

gem "zendesk_api"

bundle install

configファイルを用意

class Zendesk
  def self.client
    @client ||= ZendeskAPI::Client.new do |config|
      # Mandatory:

      config.url = ENV['ZENDESK_URL']

      # Basic / Token Authentication
      config.username = ENV['ZENDESK_USERNAME']

      # authentication
      config.token = ENV['ZENDESK_TOKEN']

      # Optional:

      # Retry uses middleware to notify the user
      # when hitting the rate limit, sleep automatically,
      # then retry the request.
      config.retry = true

      # Raise error when hitting the rate limit.
      # This is ignored and always set to false when `retry` is enabled.
      # Disabled by default.
      # config.raise_error_when_rate_limited = false

      # Logger prints to STDERR by default, to e.g. print to stdout:
      require 'logger'
      config.logger = Logger.new(STDOUT)

      # Changes Faraday adapter
      # config.adapter = :patron

      # Merged with the default client options hash
      # config.client_options = {:ssl => {:verify => false}, :request => {:timeout => 30}}

      # When getting the error 'hostname does not match the server certificate'
      # use the API at https://yoursubdomain.zendesk.com/api/v2
    end
  end
end

環境変数の設定

.env で管理しています。

ZENDESK_URL=https://sample.zendesk.com/api/v2
ZENDESK_USERNAME=login.email@zendesk.com
ZENDESK_TOKEN=TOKEN

ZENDESK_TOKEN は冒頭で取得したトークンを割り当ててください。

コンソールで疏通確認

> client  = Zendesk.client
> client.tickets
# => チケット一覧を返します