Download the PHP package trust-medical/laravel-chatwork-api without Composer

On this page you can find all versions of the php package trust-medical/laravel-chatwork-api. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package laravel-chatwork-api

laravel-chatwork-api

Chatwork API v2 を Laravel から安全に利用するための Composer パッケージです。Facade / DI / Laravel Notification の3経路を公式サポートします。

特長

インストール

ServiceProvider と Facade は Laravel のパッケージ自動検出で登録されるため、手動登録は不要です。

設定ファイルを publish します:

.env に最低限の認証情報を設定します:

設定

config/chatwork.php の主なキー:

キー 既定値 説明
default default 使用する connection 名(CHATWORK_CONNECTION
base_uri https://api.chatwork.com/v2 API ベース URI
timeout 10 リクエストタイムアウト秒
response.mode dto 既定の戻り値モード(CHATWORK_RESPONSE_MODE。無効値は ChatworkConfigurationException
connections API Token connection 1件 複数 connection 定義可
oauth OAuth2 設定(後述)
oauth.timeout 10 OAuth トークン要求のタイムアウト秒(CHATWORK_OAUTH_TIMEOUT

複数 connection の例:

基本的な使い方

connection の切り替え

connection() / withApiToken() / withBearerToken() / as*() は新しい manager を返すイミュータブル設計のため、安全にチェーンできます。ChatworkManager はコンテナ singleton ですが、これらは共有インスタンスを mutate せず clone を返すため、Laravel Octane / Swoole / キューワーカー等の常駐プロセスでもリクエスト間で connection・認証情報・戻り値モードが漏れません

戻り値モード

既定は asDto()。呼び出し側でチェーンして変更できます。

モード 成功時 4xx / 5xx
asDto() readonly DTO ChatworkRequestException を throw
asArray() 配列 ChatworkRequestException を throw
asCollection() Illuminate\Support\Collection ChatworkRequestException を throw
asResponse() Laravel HTTP Response throw しない
asPsrResponse() PSR-7 Response throw しない
asResult() ResultHttp\Result throw しない

送信前バリデーション失敗は戻り値モードに関わらず常に ChatworkValidationException を throw します。

メソッド別の戻り値型(asDto() 契約)

各 Resource メソッドのネイティブ署名は : mixed です(戻り値型は ResponseMode により実行時に変わるため)。下表は 既定の asDto() モード での戻り値型です。 asArray() / asCollection() / asResponse() / asPsrResponse() / asResult() へ切り替えた場合は宣言型・下表の型と実行時型が乖離し、その型解釈は呼び出し側の 責務になります(設計判断の詳細は docs/03-package-architecture/response-strategy.md)。

メソッド asDto() 戻り値型
rooms()->list() list<RoomData>
rooms()->create() CreatedRoom
rooms()->find() RoomData
rooms()->update() UpdatedRoom
rooms()->leaveRoom() / deleteRoom() NoContentData
rooms()->messages()->create() CreatedMessage
rooms()->messages()->list() list<MessageData>
rooms()->messages()->find() MessageData
rooms()->messages()->update() UpdatedMessage
rooms()->messages()->deleteMessage() DeletedMessage
rooms()->messages()->markAsRead() MarkReadResult
rooms()->messages()->markAsUnread() MarkUnreadResult
rooms()->members()->list() list<RoomMemberData>
rooms()->members()->replaceMembers() ReplacedRoomMembers
rooms()->tasks()->list() list<RoomTaskData>
rooms()->tasks()->create() CreatedTask
rooms()->tasks()->find() / updateStatus() RoomTaskData
rooms()->files()->list() list<RoomFileData>
rooms()->files()->upload() UploadedRoomFile
rooms()->files()->find() RoomFileData
rooms()->links()->find() / create() / update() / deleteLink() RoomLinkData
contacts()->list() list<ContactData>
me()->get() MyAccountData
my()->status() MyStatusData
my()->tasks() list<MyTaskData>
incomingRequests()->list() list<IncomingRequestData>
incomingRequests()->accept() ContactData
incomingRequests()->decline() NoContentData

list<…> 系で Chatwork が 204 を返す場合、asDto() では [] に縮退します (contacts()->list() / my()->tasks() / incomingRequests()->list())。

リソース別の例

Rooms

Messages

Members

Tasks

Files

Invitation Links

Me / My / Contacts / Incoming Requests

エラーハンドリング

例外

例外 発生条件
ChatworkValidationException 送信前バリデーション失敗(戻り値モードに関わらず常に throw)
ChatworkRequestException 4xx / 5xx(throw 系モード時)
ChatworkAuthenticationException 認証情報の解決失敗(connection 不正・OAuth refresh 失敗等)
ChatworkConfigurationException 設定・配線が不正(oauth.state_store / oauth.token_repository に不正クラス、oauth.route_throttle 形式不正、base_uri スキーム不正など)

すべての例外は marker interface ChatworkException を実装します。本パッケージ由来の例外を一括捕捉したい場合は catch (ChatworkException $e) が使えます(status() / violations() などの固有メソッドは具象例外型で分岐してください)。

ChatworkRequestException はエラーボディ2系統を取り出せます:

asResult()(例外を投げない)

Notification チャンネル

Notification から Chatwork へ送信できます。チャンネルは内部的に asResult() 固定で、4xx は permanent failure として例外化、5xx / 429 / ネットワークエラーはそのまま伝播してキュー再試行に委譲されます。

ChatworkMessage はメッセージ組み立て専用のビルダー / DTO です(Notification ではありません)。ChatworkNotification を継承すると via() は自動で ChatworkChannel に接続されるため、toChatwork() を実装するだけで送信できます。

ChatworkNotification を使わず通常の Notificationvia()[ChatworkChannel::class] を返し、toChatwork($notifiable): ChatworkMessage を実装しても構いません(queueable・複数チャンネル併用などはこちら)。

メッセージビルダーは body() / title() / code() / hr() / plain() / escape() / to()(TO 付与)/ toRoom() / selfUnread() を提供します。

送信先は ChatworkMessage::toRoom() のほか、notifiable 側の routeNotificationForChatwork() でも指定できます(両方指定は競合エラー):

OAuth2

config/chatwork.phpoauth セクションで設定します。

Confidential / Public Client の自動判定: Chatwork は OAuth クライアント 種別ごとにトークンエンドポイントの認証方式が異なります。Confidential Client (client_secret あり) は Authorization: Basic Base64(client_id:client_secret) ヘッダーが必須、Public Client (client_secret なし) は body に client_id のみを 含めて Basic 認証ヘッダーを送りません。本ライブラリは CHATWORK_OAUTH_CLIENT_SECRET の有無 (空文字含む) で自動判定します。Confidential / Public を切り替える追加 設定キーはありません。

callback ルートは既定で無効です(セキュリティのため)。利用する場合は config/chatwork.php で有効化します:

有効化すると GET {route_prefix}/callback(ルート名 chatwork.oauth.callback)が登録されます。callback では state 検証が必須で、token は設定した TokenRepository に保存されます。取得済みトークンは Chatwork::connection('oauth-connection') 経由で利用でき、期限切れ時は Cache::lock で多重発行を防ぎつつ自動 refresh されます。

本番環境の推奨: 既定の StateStore / TokenRepository は Cache ストアを使います。state の一度きりの消費(リプレイ攻撃防止)には read-and-delete のアトミック性が必要なため、本番では redis または database キャッシュドライバを使用してください。array / file ドライバは read→delete が非アトミックで、同一 state の二重消費が理論上成立し得ます。永続トークンには独自の TokenRepository(例: DB 実装)を設定することを推奨します。

トークンの暗号化: 既定の CacheTokenRepository は access/refresh トークンを Laravel の EncrypterAPP_KEY)で暗号化してからキャッシュへ保存します。Redis / Memcached を直接参照されてもトークンは平文露出しません。APP_KEY 未設定だと MissingAppKeyException になります(通常の Laravel アプリでは設定済み)。APP_KEY をローテーションした場合、暗号化済みの既存トークンは復号できず「未保存」とみなされ、利用者は再認証が必要になります。独自の TokenRepository を使う場合は暗号化も自実装の責務です。

callback ルートの throttle

config/chatwork.phpoauth.route_throttle(既定 '10,1' = 1分あたり10回)が callback ルートに throttle ミドルウェアとして適用され、state / code のブルートフォースを抑制します。"max,decayMinutes" 形式の文字列、または名前付き rate limiter 名を指定できます。null / 空文字で throttle を無効化します。形式不正値は ServiceProvider 起動時に ChatworkConfigurationException になります。

独自 RouteServiceProvider からの手動登録

routes_enabledfalse のままにしつつ、任意の middleware / ドメイン / プレフィックス配下で callback ルートを登録したい場合は、ChatworkServiceProvider::registerOAuthRoutes() を独自の RouteServiceProvider から呼び出せます(意図的に public)。

route:cache 利用時の注意: OAuth callback ルートは packageBooted() 内のクロージャで登録されます。php artisan route:cache が有効な環境ではこのクロージャが実行されず、callback ルートが登録されず、また route_throttle の形式検証も行われませんregisterOAuthRoutes() を独自 RouteServiceProvider から手動呼び出しする場合も route:cache 下では同様にスキップされます。route:cache を使う環境で OAuth callback を利用する場合は、ルートをアプリ側の実 routes ファイルに明示登録し、route_throttle の指定が実際に効いているか(php artisan route:list 等で)確認してください。

動的 (per-tenant) OAuth コネクション

Laravel のユーザーごとに別の OAuth access_token を持つ SaaS / マルチテナント環境では、Chatwork::forOAuthKey($key) を使うと TokenRepository の検索キーをランタイムに指定して OAuth コネクションを組み立てられます。

固定 OAuth connection(config/chatwork.phpauth: 'oauth' を宣言する方式)との違い:

固定 OAuth connection forOAuthKey()
config/chatwork.php への connection 定義 必要 不要
TokenRepository の検索キー config 固定(connection_name ランタイム指定($key
Cache::lock による refresh 直列化 あり あり(同じ OAuthTokenProvider 経由)
baseUri / timeout 当該 connection から $base 引数(省略時は config('chatwork.default') の connection)から継承

$base を明示すると、その connection の base_uri / timeout を継承しつつ TokenRepository のキーには $key を使います($baseauth 値を問わず baseUri / timeout のメタデータ源としてのみ参照されます)。$base 指定が config に存在しない場合は ChatworkAuthenticationException を投げます。

$key の選び方: $keyTokenRepository::find() / save() および Cache::lock のキー(chatwork:oauth:refresh:<sha256($key)>)として使われます。メールアドレス等の PII を直接渡さず、DB の User PK 等の安定 ID を使ってください。Connection::$name"oauth:{$key}" 形式となり、例外メッセージ・ログに現れます。

manager を長期保持しない: forOAuthKey() は呼び出し時点で BearerTokenCredentials を確定して Connection に焼き込みます(connection() と同じ resolve-at-bind セマンティクス)。access_token の expire 後に再利用できないため、Queue worker / Octane でもリクエスト直前に都度呼び出してください。

テスト

すべてのテストは Http::fake() で実 API を叩かずに検証しています。

セキュリティ

脆弱性を発見した場合は公開 issue ではなく非公開でご連絡ください。

ライセンス

MIT License


All versions of laravel-chatwork-api with dependencies

PHP Build Version
Package Version
Requires php Version ^8.3
composer-runtime-api Version ^2.0
illuminate/cache Version ^11.0 || ^12.0 || ^13.0
illuminate/contracts Version ^11.0 || ^12.0 || ^13.0
illuminate/http Version ^11.0 || ^12.0 || ^13.0
illuminate/notifications Version ^11.0 || ^12.0 || ^13.0
illuminate/routing Version ^11.0 || ^12.0 || ^13.0
illuminate/support Version ^11.0 || ^12.0 || ^13.0
psr/http-message Version ^1.1 || ^2.0
spatie/laravel-package-tools Version ^1.16
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package trust-medical/laravel-chatwork-api contains the following files

Loading the files please wait ...