"""CareerByteCode ByteConnect API client for Python 3.8+ (single file, standard library only). Version 1.2.0. Guide: https://www.careerbytecode.in/byteconnect/docs/#sdks from cbc_byteconnect import CbcByteConnect cbc = CbcByteConnect('cbc_test_xxxxxxxxxxxx', os.environ['CBC_SECRET']) r = cbc.catalogue() # {'status', 'ok', 'data', 'error', 'request_id', 'rate_limit': {...}} o = cbc.checkout('course:kubernetes-bootcamp', 'A-1001', 'A-1001-try1') for order in cbc.all_orders(status='paid'): ... CbcByteConnect.verify_webhook(raw_body_bytes, request.headers, os.environ['CBC_WEBHOOK_SECRET']) # 1.1.0: read-only data feeds (scopes jobs, credentials, events, blog) for job in cbc.all_jobs(category='cloud-devops'): print(job['title'], job['url']) cert = cbc.credential('CBC-AIENG-2026-0001', 'K7Q2')['data']['credential'] events = cbc.events(mode='online')['data']['events'] for post in cbc.all_blog_posts(tag='kubernetes'): ... # 1.2.0: bulk seats (only while bulk seats are on for your account) so = cbc.checkout_seats('course:kubernetes-bootcamp', 25, 'ACME-BATCH-7')['data']['order'] cbc.assign_seats(so['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. """ import hashlib import hmac import json import os import re import time import urllib.error import urllib.parse import urllib.request VERSION = '1.2.0' class CbcByteConnectError(Exception): def __init__(self, message, status=0, code='', response=None): super().__init__(message) self.status = status self.code = code self.response = response class CbcByteConnect: VERSION = VERSION def __init__(self, key_id, secret, base_url='https://www.careerbytecode.in', timeout=20, throw_on_error=True): if not re.match(r'^cbc_(test|live)_[a-z2-7]{12}$', str(key_id)): raise ValueError('The key id looks like cbc_test_xxxxxxxxxxxx or cbc_live_xxxxxxxxxxxx.') if not secret: raise ValueError('The key secret is empty (read it from an environment variable).') self.key_id = key_id self.secret = secret self.base_url = str(base_url).rstrip('/') self.timeout = timeout self.throw_on_error = throw_on_error @staticmethod def string_to_sign(method, path_and_query, ts, nonce, body): body_b = body if isinstance(body, bytes) else (body or '').encode('utf-8') return '\n'.join([str(method).upper(), path_and_query, str(ts), nonce, hashlib.sha256(body_b).hexdigest()]) def sign_headers(self, method, path_and_query, body='', ts=None, nonce=None): ts = str(ts or int(time.time())) nonce = nonce or os.urandom(12).hex() sts = self.string_to_sign(method, path_and_query, ts, nonce, body) sig = hmac.new(self.secret.encode('utf-8'), sts.encode('utf-8'), hashlib.sha256).hexdigest() return {'X-CBC-Key': self.key_id, 'X-CBC-Timestamp': ts, 'X-CBC-Nonce': nonce, 'X-CBC-Signature': sig} def request(self, method, path, query=None, json_body=None, extra_headers=None): q = {k: v for k, v in (query or {}).items() if v is not None and v != ''} qs = urllib.parse.urlencode(q, quote_via=urllib.parse.quote, safe='') pq = '/api/v1/' + str(path).lstrip('/') + ('?' + qs if qs else '') body = '' if json_body is None else json.dumps(json_body, separators=(',', ':'), ensure_ascii=False) headers = {'Accept': 'application/json', 'User-Agent': 'CbcByteConnect-Python/' + VERSION} if body: headers['Content-Type'] = 'application/json' headers.update(self.sign_headers(method, pq, body)) headers.update(extra_headers or {}) req = urllib.request.Request(self.base_url + pq, data=body.encode('utf-8') if body else None, method=str(method).upper(), headers=headers) try: with urllib.request.urlopen(req, timeout=self.timeout) as r: status, raw, hdr = r.status, r.read(), r.headers except urllib.error.HTTPError as e: status, raw, hdr = e.code, e.read(), e.headers except urllib.error.URLError as e: raise CbcByteConnectError('Network error: %s' % e.reason, 0, 'network') try: j = json.loads(raw.decode('utf-8')) except ValueError: j = {'ok': False, 'error': {'code': 'bad_response', 'message': 'The answer was not JSON (HTTP %d).' % status}} def num(h): v = hdr.get(h) return int(v) if v is not None and str(v).isdigit() else None out = { 'status': status, 'ok': bool(j.get('ok')), 'data': j.get('data'), 'error': j.get('error'), 'request_id': j.get('request_id') or hdr.get('X-Request-Id') or '', 'rate_limit': {'limit': num('X-RateLimit-Limit'), 'remaining': num('X-RateLimit-Remaining'), 'reset': num('X-RateLimit-Reset')}, 'deprecation': hdr.get('Deprecation'), 'sunset': hdr.get('Sunset'), 'headers': dict(hdr.items()), } if not out['ok'] and self.throw_on_error: code = (out['error'] or {}).get('code', 'error') raise CbcByteConnectError('%s: %s (request %s)' % (code, (out['error'] or {}).get('message', ''), out['request_id']), status, code, out) return out def ping(self): return self.request('GET', 'ping') def catalogue(self, type='', sample=False): q = {} if type: q['type'] = type if sample: q['sample'] = '1' return self.request('GET', 'catalogue', q) def checkout(self, item, partner_ref='', idempotency_key=''): extra = {'X-CBC-Idempotency-Key': idempotency_key} if idempotency_key else {} return self.request('POST', 'checkout', {}, {'item': item, 'partner_ref': partner_ref}, extra) def orders(self, status=None, limit=None, since=None, cursor=None): """One page. since = unix seconds; cursor = next_cursor of the previous page.""" return self.request('GET', 'orders', {'status': status, 'limit': limit, 'since': since, 'cursor': cursor}) def order(self, order_id): return self.request('GET', 'orders/' + urllib.parse.quote(str(order_id), safe='')) def all_orders(self, status=None, since=None, limit=200): """Every order matching the filters, page by page (follows next_cursor).""" cursor = None while True: r = self.orders(status=status, limit=limit, since=since, cursor=cursor) data = r.get('data') or {} for o in data.get('orders') or []: yield o cursor = data.get('next_cursor') if not data.get('has_more') or not cursor: return def ip_check(self): return self.request('GET', 'ip-check') # ---- 1.2.0: bulk seats (only while bulk seats are on for your account) ---- def checkout_seats(self, item, quantity, partner_ref='', idempotency_key=''): """A bulk seat order: quantity seats of one item (the buyer pays once on the seat checkout behind checkout_url).""" extra = {'X-CBC-Idempotency-Key': idempotency_key} if idempotency_key else {} return self.request('POST', 'checkout', {}, {'item': item, 'quantity': int(quantity), 'partner_ref': partner_ref}, extra) def seats(self, order_id): """The seats of a bulk seat order and who has them.""" return self.request('GET', 'orders/' + urllib.parse.quote(str(order_id), safe='') + '/seats') def assign_seats(self, order_id, emails): """Give seats of a PAID bulk seat order to learners by email (each email once per order).""" return self.request('POST', 'orders/' + urllib.parse.quote(str(order_id), safe='') + '/seats', {}, {'emails': [str(e) for e in emails]}) # ---- 1.1.0: read-only data feeds (each needs its scope on the key) ---- def _pages(self, path, key, params): # Every item of a paged data feed (follows next_cursor). q = {k: v for k, v in params.items() if v is not None and v != ''} q.setdefault('limit', 100) q.pop('cursor', None) while True: r = self.request('GET', path, q) data = r.get('data') or {} for it in data.get(key) or []: yield it nxt = data.get('next_cursor') if not data.get('has_more') or not nxt: return q['cursor'] = nxt def jobs(self, **params): # Open jobs, one page: category, city, mode, type, since, limit, cursor. Link to each job's url as it is. return self.request('GET', 'jobs', params) def all_jobs(self, **params): return self._pages('jobs', 'jobs', params) def job(self, job_id): # One open job (404 unknown_job once it is closed, filled or expired). return self.request('GET', 'jobs/' + urllib.parse.quote(str(job_id), safe='')) def credential(self, cred_id, code=''): # Check a certificate by its id; code = the 4-character verification code the holder gave you. return self.request('GET', 'credentials/' + urllib.parse.quote(str(cred_id).strip().upper(), safe=''), {'code': code} if code else {}) def events(self, **params): # Public upcoming events, one page: mode (online, in_person, hybrid), series, limit, cursor. return self.request('GET', 'events', params) def all_events(self, **params): return self._pages('events', 'events', params) def blog_posts(self, **params): # ByteBlog posts, one page: tag, author (handle), since, limit, cursor. return self.request('GET', 'blog/posts', params) def all_blog_posts(self, **params): return self._pages('blog/posts', 'posts', params) @staticmethod def verify_webhook(raw_body, headers, webhook_secret, tolerance=300, now=None): """True when X-CBC-Signature or X-CBC-Signature-New matches and the timestamp is fresh. raw_body = exact bytes.""" def get(name): if hasattr(headers, 'get'): v = headers.get(name) if v is None: for k in list(getattr(headers, 'keys', lambda: [])()): if str(k).lower() == name.lower(): v = headers[k] break return '' if v is None else str(v) return '' ts = get('X-CBC-Timestamp') if not webhook_secret or not ts.isdigit() or abs((now or int(time.time())) - int(ts)) > tolerance: return False raw = raw_body if isinstance(raw_body, bytes) else str(raw_body).encode('utf-8') want = hmac.new(webhook_secret.encode('utf-8'), ts.encode('utf-8') + b'.' + raw, hashlib.sha256).hexdigest() for h in ('X-CBC-Signature', 'X-CBC-Signature-New'): got = get(h).lower() if got and hmac.compare_digest(want, got): return True return False