目錄
實例化
微信服務器推送事件
預授權
獲取預授權 Code
獲取預授權 URL
API 列表
使用授權碼換取公眾號的接口調用憑據和授權信息
獲取授權方的公眾號帳號基本信息
獲取授權方的選項設置信息
設置授權方的選項信息
調用授權方 API
實例化
<?php
use EasyWeChat\Foundation\Application;
$options = [
// ...
'open_platform' => [
'app_id' => 'component-app-id',
'secret' => 'component-app-secret',
'token' => 'component-token',
'aes_key' => 'component-aes-key'
],
// ...
];
$app = new Application($options);
$openPlatform = $app->open_platform;
微信服務器推送事件
公眾號第三方平台推送的有四個事件:
授權成功(authorized)
授權更新(updateauthorized)
授權取消(unauthorized)
推送 ComponentVerifyTicket(component_verify_ticket)
在公眾號第三方平台創建審核通過后,微信服務器會向其“授權事件接收URL”每隔 10 分鍾推送一次 component_verify_ticket。
SDK 內部已實現緩存 component_veirfy_ticket,開發者無需另行處理該事件。
其余事件需要開發者自行處理。
注:需要在URL路由中寫上觸發代碼,並且注冊路由后需要等待微信服務器推送 component_verify_ticket,才有權限進行其他操作,否則報”Component verify ticket does not exists.”
Example:
use EasyWeChat\OpenPlatform\Guard;
$server = $openPlatform->server;
$server->setMessageHandler(function($event) use ($openPlatform) {
// 事件類型常量定義在 \EasyWeChat\OpenPlatform\Guard 類里
switch ($event->InfoType) {
case Guard::EVENT_AUTHORIZED: // 授權成功
$authorizationInfo = $openPlatform->getAuthorizationInfo($event->AuthorizationCode);
// 保存數據庫操作等...
case Guard::EVENT_UPDATE_AUTHORIZED: // 更新授權
// 更新數據庫操作等...
case Guard::EVENT_UNAUTHORIZED: // 授權取消
// 更新數據庫操作等...
}
});
$response = $server->serve();
$response->send(); // Laravel 里請使用:return $response;
預授權
獲取預授權 Code
Example:
$openPlatform->pre_auth->getCode();
獲取預授權 URL
Example:
// 直接跳轉
$response = $openPlatform->pre_auth->redirect('https://your-domain.com/callback');
// 獲取跳轉的 URL
$response->getTargetUrl();
用戶授權后會帶上 auth_code 跳轉到 https://your-domain.com/callback?auth_code=xxxxxxx
API 列表
使用授權碼換取公眾號的接口調用憑據和授權信息
// 使用授權碼換取公眾號的接口調用憑據和授權信息
// Optional: $authorizationCode 不傳值時會自動獲取 URL 中 auth_code 值
$openPlatform->getAuthorizationInfo($authorizationCode = null);
獲取授權方的公眾號帳號基本信息
$openPlatform->getAuthorizerInfo($authorizerAppId);
獲取授權方的選項設置信息
$openPlatform->getAuthorizerOption($authorizerAppId, $optionName);
設置授權方的選項信息
$openPlatform->setAuthorizerOption($authorizerAppId, $optionName, $optionValue);
調用授權方 API
通過該方法會獲得一個 \EasyWeChat\Foundation\Application 實例。
當調用授權方 API 后,SDK 內部會自動獲取和刷新 AuthorizerAccessToken 有效期。
所以開發者無需處理授權方公眾號的接口調用憑據 AuthorizerAccessToken。
// 傳遞 AuthorizerAppId 和 AuthorizerRefreshToken(注意不是 AuthorizerAccessToken)即可。
$app = $openPlatform->createAuthorizerApplication($authorizerAppId, $authorizerRefreshToken);
// 調用方式與普通調用一致。