catalogue(); // ['status' => 200, 'data' => [...], 'rate_limit' => [...], ...] * $o = $cbc->checkout('course:kubernetes-bootcamp', 'A-1001', 'A-1001-try1'); * foreach ($cbc->allOrders(['status' => 'paid']) as $order) { ... } * CbcByteConnect::verifyWebhook($rawBody, $_SERVER, getenv('CBC_WEBHOOK_SECRET')); * // 1.1.0: read-only data feeds (scopes jobs, credentials, events, blog) * foreach ($cbc->allJobs(['category' => 'cloud-devops']) as $job) { echo $job['title'], ' ', $job['url'], PHP_EOL; } * $c = $cbc->credential('CBC-AIENG-2026-0001', 'K7Q2')['data']['credential']; * $events = $cbc->events(['mode' => 'online'])['data']['events']; * foreach ($cbc->allBlogPosts(['tag' => 'kubernetes']) as $post) { ... } * // 1.2.0: bulk seats (only while bulk seats are on for your account) * $o = $cbc->checkoutSeats('course:kubernetes-bootcamp', 25, 'ACME-BATCH-7')['data']['order']; * $cbc->assignSeats($o['id'], ['asha@college.example', 'ravi@college.example']); // after the order is paid * * Every call is signed: X-CBC-Key, X-CBC-Timestamp, X-CBC-Nonce and X-CBC-Signature = hex HMAC-SHA256(secret, * METHOD \n PATH_AND_QUERY \n TIMESTAMP \n NONCE \n sha256_hex(BODY)). Keep the secret on your server only. * Needs the curl extension. Licence: free to use and change for your ByteConnect integration. */ declare(strict_types=1); final class CbcByteConnectError extends RuntimeException { /** @param array $response */ public function __construct(string $message, public readonly int $status = 0, public readonly string $errorCode = '', public readonly array $response = []) { parent::__construct($message, $status); } } final class CbcByteConnect { public const VERSION = '1.2.0'; public function __construct( private string $keyId, private string $secret, private string $baseUrl = 'https://www.careerbytecode.in', private int $timeout = 20, private bool $throwOnError = true ) { if (!preg_match('/^cbc_(test|live)_[a-z2-7]{12}$/', $keyId)) { throw new InvalidArgumentException('The key id looks like cbc_test_xxxxxxxxxxxx or cbc_live_xxxxxxxxxxxx.'); } if ($secret === '') { throw new InvalidArgumentException('The key secret is empty (read it from an environment variable).'); } $this->baseUrl = rtrim($baseUrl, '/'); } /** The string the signature is made over (exposed for tests and debugging). */ public static function stringToSign(string $method, string $pathAndQuery, string $ts, string $nonce, string $body): string { return strtoupper($method) . "\n" . $pathAndQuery . "\n" . $ts . "\n" . $nonce . "\n" . hash('sha256', $body); } /** The four X-CBC headers for one request. */ public function signHeaders(string $method, string $pathAndQuery, string $body = '', ?int $ts = null, ?string $nonce = null): array { $ts = (string)($ts ?? time()); $nonce = $nonce ?? bin2hex(random_bytes(12)); return [ 'X-CBC-Key' => $this->keyId, 'X-CBC-Timestamp' => $ts, 'X-CBC-Nonce' => $nonce, 'X-CBC-Signature' => hash_hmac('sha256', self::stringToSign($method, $pathAndQuery, $ts, $nonce, $body), $this->secret), ]; } /** * One signed call. $path is after /api/v1/ (for example 'orders'); $query is sent exactly as signed. * Returns ['status', 'ok', 'data', 'error', 'request_id', 'rate_limit' => [limit, remaining, reset], 'headers']. */ public function request(string $method, string $path, array $query = [], ?array $json = null, array $extraHeaders = []): array { $pq = '/api/v1/' . ltrim($path, '/') . ($query ? '?' . http_build_query($query, '', '&', PHP_QUERY_RFC3986) : ''); $body = $json === null ? '' : (string)json_encode($json, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); $hdr = ['Accept: application/json', 'User-Agent: CbcByteConnect-PHP/' . self::VERSION]; if ($body !== '') { $hdr[] = 'Content-Type: application/json'; } foreach ($this->signHeaders($method, $pq, $body) + $extraHeaders as $k => $v) { $hdr[] = $k . ': ' . $v; } $headers = []; $ch = curl_init($this->baseUrl . $pq); curl_setopt_array($ch, [ CURLOPT_CUSTOMREQUEST => strtoupper($method), CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => $hdr, CURLOPT_TIMEOUT => $this->timeout, CURLOPT_CONNECTTIMEOUT => 10, CURLOPT_FOLLOWLOCATION => false, CURLOPT_HEADERFUNCTION => static function ($c, string $line) use (&$headers): int { $p = strpos($line, ':'); if ($p !== false) { $headers[strtolower(trim(substr($line, 0, $p)))] = trim(substr($line, $p + 1)); } return strlen($line); }, ]); if ($body !== '') { curl_setopt($ch, CURLOPT_POSTFIELDS, $body); } $raw = curl_exec($ch); $status = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE); $cerr = curl_error($ch); curl_close($ch); if ($raw === false) { throw new CbcByteConnectError('Network error: ' . $cerr); } $j = json_decode((string)$raw, true); if (!is_array($j)) { $j = ['ok' => false, 'error' => ['code' => 'bad_response', 'message' => 'The answer was not JSON (HTTP ' . $status . ').']]; } $out = [ 'status' => $status, 'ok' => !empty($j['ok']), 'data' => $j['data'] ?? null, 'error' => $j['error'] ?? null, 'request_id' => (string)($j['request_id'] ?? ($headers['x-request-id'] ?? '')), 'rate_limit' => ['limit' => isset($headers['x-ratelimit-limit']) ? (int)$headers['x-ratelimit-limit'] : null, 'remaining' => isset($headers['x-ratelimit-remaining']) ? (int)$headers['x-ratelimit-remaining'] : null, 'reset' => isset($headers['x-ratelimit-reset']) ? (int)$headers['x-ratelimit-reset'] : null], 'deprecation' => $headers['deprecation'] ?? null, 'sunset' => $headers['sunset'] ?? null, 'headers' => $headers, ]; if (!$out['ok'] && $this->throwOnError) { $code = (string)($out['error']['code'] ?? 'error'); throw new CbcByteConnectError($code . ': ' . (string)($out['error']['message'] ?? '') . ' (request ' . $out['request_id'] . ')', $status, $code, $out); } return $out; } public function ping(): array { return $this->request('GET', 'ping'); } /** $type = course | exam | byteclass | byteplay | bytelabs; $sample = test keys: the sandbox sample catalogue. */ public function catalogue(string $type = '', bool $sample = false): array { $q = []; if ($type !== '') { $q['type'] = $type; } if ($sample) { $q['sample'] = '1'; } return $this->request('GET', 'catalogue', $q); } /** Make an order. Send the same $idempotencyKey when you retry, to get the same order back. */ public function checkout(string $item, string $partnerRef = '', string $idempotencyKey = ''): array { return $this->request('POST', 'checkout', [], ['item' => $item, 'partner_ref' => $partnerRef], $idempotencyKey !== '' ? ['X-CBC-Idempotency-Key' => $idempotencyKey] : []); } /** One page: $params = status, limit (1-200), since (unix seconds), cursor (next_cursor of the previous page). */ public function orders(array $params = []): array { return $this->request('GET', 'orders', array_filter($params, static fn($v) => $v !== null && $v !== '')); } public function order(string $id): array { return $this->request('GET', 'orders/' . rawurlencode($id)); } /** Every order matching $params, page by page (follows next_cursor). */ public function allOrders(array $params = []): Generator { $params['limit'] = $params['limit'] ?? 200; unset($params['cursor']); do { $r = $this->orders($params); foreach ((array)($r['data']['orders'] ?? []) as $o) { yield $o; } $next = $r['data']['next_cursor'] ?? null; $params['cursor'] = $next; } while (!empty($r['data']['has_more']) && is_string($next) && $next !== ''); } public function ipCheck(): array { return $this->request('GET', 'ip-check'); } /* ---- 1.2.0: bulk seats (only while bulk seats are on for your account) ---- */ /** A bulk seat order: $quantity seats of one item (the buyer pays once on the seat checkout behind checkout_url). */ public function checkoutSeats(string $item, int $quantity, string $partnerRef = '', string $idempotencyKey = ''): array { return $this->request('POST', 'checkout', [], ['item' => $item, 'quantity' => $quantity, 'partner_ref' => $partnerRef], $idempotencyKey !== '' ? ['X-CBC-Idempotency-Key' => $idempotencyKey] : []); } /** The seats of a bulk seat order and who has them. */ public function seats(string $orderId): array { return $this->request('GET', 'orders/' . rawurlencode($orderId) . '/seats'); } /** Give seats of a PAID bulk seat order to learners by email (each email once per order). */ public function assignSeats(string $orderId, array $emails): array { return $this->request('POST', 'orders/' . rawurlencode($orderId) . '/seats', [], ['emails' => array_values(array_map('strval', $emails))]); } /* ---- 1.1.0: read-only data feeds (each needs its scope on the key) ---- */ /** Every item of a paged data feed: follows next_cursor. */ private function pages(string $path, string $key, array $params): Generator { $params = array_filter($params, static fn($v) => $v !== null && $v !== ''); $params['limit'] = $params['limit'] ?? 100; unset($params['cursor']); do { $r = $this->request('GET', $path, $params); foreach ((array)($r['data'][$key] ?? []) as $it) { yield $it; } $next = $r['data']['next_cursor'] ?? null; $params['cursor'] = $next; } while (!empty($r['data']['has_more']) && is_string($next) && $next !== ''); } /** Open jobs, one page: $params = category, city, mode (onsite|remote|hybrid), type, since, limit, cursor. Link to each job's url as it is. */ public function jobs(array $params = []): array { return $this->request('GET', 'jobs', array_filter($params, static fn($v) => $v !== null && $v !== '')); } /** Every open job matching $params, page by page. */ public function allJobs(array $params = []): Generator { return $this->pages('jobs', 'jobs', $params); } /** One open job (404 unknown_job once it is closed, filled or expired). */ public function job(int $id): array { return $this->request('GET', 'jobs/' . $id); } /** Check a certificate by its id; $code = the 4-character verification code the holder gave you (shows the full name). */ public function credential(string $id, string $code = ''): array { return $this->request('GET', 'credentials/' . rawurlencode(strtoupper(trim($id))), $code !== '' ? ['code' => $code] : []); } /** Public upcoming events, one page: $params = mode (online|in_person|hybrid), series, limit, cursor. */ public function events(array $params = []): array { return $this->request('GET', 'events', array_filter($params, static fn($v) => $v !== null && $v !== '')); } public function allEvents(array $params = []): Generator { return $this->pages('events', 'events', $params); } /** ByteBlog posts, one page: $params = tag, author (handle), since, limit, cursor. */ public function blogPosts(array $params = []): array { return $this->request('GET', 'blog/posts', array_filter($params, static fn($v) => $v !== null && $v !== '')); } public function allBlogPosts(array $params = []): Generator { return $this->pages('blog/posts', 'posts', $params); } /** * Check an order notification: $headers = $_SERVER (HTTP_X_CBC_*) or an array of header name => value. * True when X-CBC-Signature or X-CBC-Signature-New matches and the timestamp is within $tolerance seconds. */ public static function verifyWebhook(string $rawBody, array $headers, string $webhookSecret, int $tolerance = 300, ?int $now = null): bool { $get = static function (string $name) use ($headers): string { $server = 'HTTP_' . strtoupper(str_replace('-', '_', $name)); if (isset($headers[$server])) { return (string)$headers[$server]; } foreach ($headers as $k => $v) { if (strcasecmp((string)$k, $name) === 0) { return is_array($v) ? (string)reset($v) : (string)$v; } } return ''; }; $ts = $get('X-CBC-Timestamp'); if ($webhookSecret === '' || !ctype_digit($ts) || abs(($now ?? time()) - (int)$ts) > $tolerance) { return false; } $want = hash_hmac('sha256', $ts . '.' . $rawBody, $webhookSecret); foreach (['X-CBC-Signature', 'X-CBC-Signature-New'] as $h) { $got = strtolower($get($h)); if ($got !== '' && hash_equals($want, $got)) { return true; } } return false; } }