PHP code example of likry / juguang-sdk
1. Go to this page and download the library: Download likry/juguang-sdk library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
likry / juguang-sdk example snippets
use likry\juguangSdk\Client;
// 1. 创建客户端 - 统一入口
$client = Client::create($appId, $secret);
// 2. 认证授权
$client->authenticate($authCode);
// 3. 调用API - 所有功能通过client访问
$balance = $client->finance()->queryBalance($userId, $vsellerIds);
$accountInfo = $client->account()->getAccountInfo();
$reportData = $client->report()->getDailyReport($params);
// 使用配置数组
$client = Client::fromConfig([
'app_id' => 123,
'secret' => 'your-secret-here',
'access_token' => 'existing-token',
'timeout' => 30,
'retry_attempts' => 3,
]);
// 动态配置
$client->setConfig([
'debug' => true,
'timeout' => 60,
]);
$scopes = ['report_service', 'ad_query', 'account_manage'];
$redirectUri = 'http://your-domain.com/callback';
$authUrl = $client->generateAuthUrl($scopes, $redirectUri, 'custom_state');
echo "请访问: {$authUrl}";
// 从回调获取auth_code后
$tokenData = $client->authenticate($authCode);
echo "Access Token: " . $tokenData['access_token'];
echo "用户ID: " . $tokenData['user_id'];
echo "广告主ID: " . $tokenData['advertiser_id'];
// SDK会自动保存refresh_token
$client->authenticate($authCode);
// Token过期时自动刷新
$newTokenData = $client->refresh();
echo "新Token: " . $newTokenData['access_token'];
$balanceData = $client->finance()->queryBalance(
$userId, // 代理商主账号ID
['vseller1', 'vseller2'] // 子账号ID列表(最多100个)
);
// 格式化显示
$formattedBalances = $client->finance()->formatBalanceInfo($balanceData);
foreach ($formattedBalances as $balance) {
echo "账号: " . $balance['virtual_seller_id'];
echo "余额: ¥" . $balance['total_available_balance'];
echo "状态: " . $balance['account_status_text'];
echo "可转账: " . ($balance['can_transfer'] ? '是' : '否');
}
// 获取汇总统计
$summary = $client->finance()->getBalanceSummary($balanceData);
echo "总账户数: " . $summary['total_accounts'];
echo "活跃账户: " . $summary['active_accounts'];
echo "总余额: ¥" . $summary['total_balance'];
// 按钱包类型统计
$cashBalance = $client->finance()->getBalanceByWalletType(
$balanceData,
FinanceApi::WALLET_TYPE_CASH
);
$accountInfo = $client->account()->getAccountInfo();
echo "账户名称: " . $accountInfo['advertiser_name'];
echo "账户ID: " . $accountInfo['advertiser_id'];
// 获取预算信息
$budget = $client->account()->getBudget();
// 更新预算
$client->account()->updateBudget([
'daily_budget' => 10000.00,
'total_budget' => 300000.00,
]);
$dailyReport = $client->report()->getDailyReport([
'start_date' => '2024-01-01',
'end_date' => '2024-01-31',
'advertiser_id' => $advertiserId,
]);
$accountReport = $client->report()->getAccountReport([
'start_date' => '2024-01-01',
'end_date' => '2024-01-31',
'group_by' => 'date',
]);
$adReport = $client->report()->getAdReport([
'start_date' => '2024-01-01',
'end_date' => '2024-01-31',
'group_by' => 'ad_group',
'advertiser_id' => $advertiserId,
]);
// 基础配置
$client = Client::create($appId, $secret)
->setTimeout(60) // 设置超时
->enableDebug() // 启用调试
->setHeaders([ // 设置请求头
'X-Client-Version' => '1.0.0',
]);
// 获取配置
echo "App ID: " . $client->getAppId();
echo "有Token: " . ($client->hasValidAccessToken() ? '是' : '否');
echo "调试模式: " . ($client->isDebugEnabled() ? '开启' : '关闭');
$config = [
'app_id' => 123,
'secret' => 'your-secret',
// 网络配置
'timeout' => 30,
'retry_attempts' => 3,
'retry_delay' => 1000,
// 功能开关
'debug' => false,
'cache_enabled' => true,
];
$client = Client::fromConfig($config);
// 动态修改配置
$client->setConfig([
'debug' => true,
'timeout' => 60,
]);
use likry\juguangSdk\Exception\JuguangSDKException;
try {
$result = $client->finance()->queryBalance($userId, $vsellerIds);
} catch (JuguangSDKException $e) {
// 基本信息
echo "错误: " . $e->getMessage();
echo "代码: " . $e->getErrorCode();
// 错误类型判断
if ($e->isAuthError()) {
echo "认证错误,请检查Token";
} elseif ($e->isNetworkError()) {
echo "网络错误,请检查连接";
} elseif ($e->isRetryable()) {
echo "可重试错误,建议稍后重试";
}
// 格式化错误信息
echo $e->getFormattedMessage();
}
// 如果你已有一个TokenManager实例
$tokenManager = TokenManager::create($appId, $secret, $accessToken);
// 转换为Client实例
$client = Client::fromTokenManager($tokenManager);
// 批量查询多个账户余额
$vsellerIds = ['id1', 'id2', 'id3', 'id4', 'id5'];
$balance = $client->finance()->queryBalance($userId, $vsellerIds);
// 批量获取报表
$reportParams = [
'start_date' => '2024-01-01',
'end_date' => '2024-01-31',
'advertiser_ids' => [$adId1, $adId2, $adId3],
];
$reports = $client->report()->getAccountReport($reportParams);
use likry\juguangSdk\Client;
class JuguangService
{
private $client;
public function __construct()
{
// 初始化客户端
$this->client = Client::fromConfig([
'app_id' => getenv('JUGUANG_APP_ID'),
'secret' => getenv('JUGUANG_SECRET'),
'timeout' => 30,
'retry_attempts' => 3,
]);
}
public function authorizeAndGetBalance(string $authCode, string $userId, array $vsellerIds)
{
try {
// 1. 认证
$tokenData = $this->client->authenticate($authCode);
echo "认证成功,用户ID: " . $tokenData['user_id'];
// 2. 查询余额
$balanceData = $this->client->finance()->queryBalance($userId, $vsellerIds);
// 3. 格式化输出
$summary = $this->client->finance()->getBalanceSummary($balanceData);
return [
'success' => true,
'token_info' => $tokenData,
'balance_summary' => $summary,
];
} catch (JuguangSDKException $e) {
return [
'success' => false,
'error' => $e->getFormattedMessage(),
'error_code' => $e->getErrorCode(),
'retryable' => $e->isRetryable(),
];
}
}
public function getDailyReports(string $startDate, string $endDate, int $advertiserId)
{
try {
return $this->client->report()->getDailyReport([
'start_date' => $startDate,
'end_date' => $endDate,
'advertiser_id' => $advertiserId,
]);
} catch (JuguangSDKException $e) {
throw new Exception("获取报表失败: " . $e->getMessage());
}
}
}
// 使用示例
$service = new JuguangService();
$result = $service->authorizeAndGetBalance($authCode, $userId, $vsellerIds);
bash
# 运行示例
php example.php
# 或者直接测试
composer test