نمونههای آمادهٔ اتصال
زبان خودتان را انتخاب کنید
هر سه نمونه دقیقاً همان دو درخواست را میفرستند. شناسهٔ شخص از نشست معتبر سرور LMS گرفته میشود.
Node.js
ابتدا کلاینت را با baseUrl و apiKey بسازید. این ماژول در سرور LMS اجرا میشود و وابستگی خارجی ندارد.
۱. ثبت کلاس
const { class_url } = await client.createClass(classData);
// Save class_url with this class in the LMS.۲. دریافت لینک ورود و هدایت شخص
// After LMS authentication and class membership authorization:
const { entry_url } = await client.getEntryLink(classId, authenticatedUser.externalId);
response.writeHead(303, {
Location: entry_url,
'Cache-Control': 'no-store',
'Referrer-Policy': 'no-referrer',
});
response.end();نمایش فایل کامل کلاینت Node.js
// Node.js 22+; use this module in the LMS SERVER. No packages required.
export function artanClassClient({ baseUrl, apiKey }) {
const origin = new URL(baseUrl);
if (origin.protocol !== 'https:') throw new Error('ArtanClass requires HTTPS');
async function post(path, body, timeout = 30000) {
const response = await fetch(new URL(path, origin), {
method: 'POST', redirect: 'error',
headers: { Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json', Accept: 'application/json' },
body: JSON.stringify(body), signal: AbortSignal.timeout(timeout),
});
const data = await response.json();
if (!response.ok) {
const error = new Error((data.errors || ['ArtanClass request failed']).join(' '));
error.status = response.status; error.code = data.code;
error.retryAfter = response.headers.get('Retry-After');
throw error;
}
return data;
}
return {
createClass: (classData) => post('/api/v1/lms/classes', classData, 180000),
getEntryLink: (classId, externalUserId) => post(`/api/v1/lms/classes/${encodeURIComponent(classId)}/launch`, {
external_user_id: externalUserId,
}),
};
}
// 1. Create a classroom with its teacher and FULL student list:
// import { readFile } from 'node:fs/promises';
// const client = artanClassClient({
// baseUrl: process.env.ARTANCLASS_BASE_URL,
// apiKey: process.env.ARTANCLASS_API_KEY,
// });
// const classData = JSON.parse(await readFile('./class.json', 'utf8'));
// const { class_url } = await client.createClass(classData);
// Store class_url with the LMS class.
//
// 2. In the LMS entry handler, FIRST authenticate and check class membership.
// Take these IDs from YOUR database/session, never directly from a browser form.
// const { entry_url } = await client.getEntryLink(lmsClass.externalId, authenticatedUser.externalId);
// response.writeHead(303, {
// Location: entry_url,
// 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer',
// });
// response.end();
// Same code for teachers and students. Role is determined by the saved roster.
// Handle API errors before redirecting; do not log keys, national IDs or entry_url.Go
فایل کلاینت را در backend خودتان قرار دهید و Client را با BaseURL و APIKey مقداردهی کنید. فقط کتابخانهٔ استاندارد لازم است.
۱. ثبت کلاس
classroom, err := client.CreateClass(ctx, classData)
if err != nil { /* handle error, then return */ }
// Save classroom.ClassURL with this class in the LMS.۲. دریافت لینک ورود و هدایت شخص
// After LMS authentication and class membership authorization:
entry, err := client.EntryLink(r.Context(), classID, authenticatedUser.ExternalID)
if err != nil { /* handle error, then return */ }
w.Header().Set("Cache-Control", "no-store")
w.Header().Set("Referrer-Policy", "no-referrer")
http.Redirect(w, r, entry.EntryURL, http.StatusSeeOther)نمایش فایل کامل کلاینت Go
// Copy into your Go LMS backend. Standard library only.
package artanclass
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
)
type Client struct { BaseURL, APIKey string }
type Person struct {
ExternalUserID string `json:"external_user_id"`
Name string `json:"name"`
NationalID string `json:"national_id"` // Preserve leading zeroes.
}
type ClassRequest struct {
ExternalClassID string `json:"external_class_id"`
Name string `json:"name"`
Teacher Person `json:"teacher"`
Students []Person `json:"students"`
}
type ClassResponse struct { ClassURL string `json:"class_url"` }
type EntryResponse struct { EntryURL string `json:"entry_url"` }
type APIError struct {
Status int
Code string `json:"code"`
Errors []string `json:"errors"`
RetryAfter string
}
func (e *APIError) Error() string {
return fmt.Sprintf("ArtanClass %d (%s): %s", e.Status, e.Code, strings.Join(e.Errors, "; "))
}
func (c Client) post(ctx context.Context, path string, body, result any, timeout time.Duration) error {
base, err := url.Parse(c.BaseURL)
if err != nil || base.Scheme != "https" || base.Host == "" { return fmt.Errorf("invalid ArtanClass HTTPS base URL") }
data, err := json.Marshal(body)
if err != nil { return err }
req, err := http.NewRequestWithContext(ctx, http.MethodPost, base.ResolveReference(&url.URL{Path: path}).String(), bytes.NewReader(data))
if err != nil { return err }
req.Header.Set("Authorization", "Bearer "+c.APIKey)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
client := &http.Client{Timeout: timeout, CheckRedirect: func(_ *http.Request, _ []*http.Request) error { return http.ErrUseLastResponse }}
resp, err := client.Do(req)
if err != nil { return err }
defer resp.Body.Close()
decoder := json.NewDecoder(io.LimitReader(resp.Body, 2<<20))
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
apiErr := &APIError{Status: resp.StatusCode, RetryAfter: resp.Header.Get("Retry-After")}
if err := decoder.Decode(apiErr); err != nil { return fmt.Errorf("ArtanClass HTTP %d", resp.StatusCode) }
return apiErr
}
return decoder.Decode(result)
}
func (c Client) CreateClass(ctx context.Context, body ClassRequest) (ClassResponse, error) {
var result ClassResponse
if body.Students == nil { body.Students = []Person{} }
err := c.post(ctx, "/api/v1/lms/classes", body, &result, 180*time.Second)
return result, err
}
func (c Client) EntryLink(ctx context.Context, classID, externalUserID string) (EntryResponse, error) {
var result EntryResponse
if classID == "" || len(classID) > 128 { return result, fmt.Errorf("invalid LMS class id") }
for _, ch := range classID {
if !(ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' || ch >= '0' && ch <= '9' || ch == '_' || ch == '-') { return result, fmt.Errorf("invalid LMS class id") }
}
err := c.post(ctx, "/api/v1/lms/classes/"+classID+"/launch", map[string]string{"external_user_id": externalUserID}, &result, 30*time.Second)
return result, err
}
// 1. result, err := client.CreateClass(ctx, classData) // See class.json.
// Handle err, then store result.ClassURL with the LMS class.
//
// 2. In your authenticated LMS entry handler, authorize class membership FIRST.
// result, err := client.EntryLink(r.Context(), lmsClass.ExternalID, authenticatedUser.ExternalID)
// if err != nil { /* show a retry message, then return */ }
// w.Header().Set("Cache-Control", "no-store")
// w.Header().Set("Referrer-Policy", "no-referrer")
// http.Redirect(w, r, result.EntryURL, http.StatusSeeOther)
// Same code for teachers and students; do not log keys, national IDs or EntryURL.cURL
متغیرهای اتصال را تنظیم کنید و class.json و launch.json را از همین صفحه دریافت کنید.
۱. ثبت کلاس
curl --request POST "$ARTANCLASS_BASE_URL/api/v1/lms/classes" \
--header "Authorization: Bearer $ARTANCLASS_API_KEY" \
--header 'Content-Type: application/json' \
--data-binary @class.json۲. دریافت لینک ورود و هدایت شخص
curl --request POST "$ARTANCLASS_BASE_URL/api/v1/lms/classes/math-701/launch" \
--header "Authorization: Bearer $ARTANCLASS_API_KEY" \
--header 'Content-Type: application/json' \
--data-binary @launch.jsonنمایش فایل کامل کلاینت cURL
#!/usr/bin/env sh
set -eu
: "${ARTANCLASS_BASE_URL:?Set the ArtanClass HTTPS origin}"
: "${ARTANCLASS_API_KEY:?Set the server-side API key}"
# Run from this examples directory. Requests below create/sync real data.
# 1. Register the class, teacher and FULL student list. Returns only class_url.
curl --fail-with-body --max-time 180 --request POST "$ARTANCLASS_BASE_URL/api/v1/lms/classes" \
--header "Authorization: Bearer $ARTANCLASS_API_KEY" \
--header 'Content-Type: application/json' --data-binary @class.json
printf '\n'
# 2. Get a personal entry link. launch.json contains only external_user_id.
# For a student, replace teacher-42 with student-101 in launch.json.
curl --fail-with-body --max-time 30 --request POST "$ARTANCLASS_BASE_URL/api/v1/lms/classes/math-701/launch" \
--header "Authorization: Bearer $ARTANCLASS_API_KEY" \
--header 'Content-Type: application/json' --data-binary @launch.json
printf '\n'
# entry_url is private, single-use and expires after 120 seconds.
# In your LMS handler redirect ONLY the authenticated person's browser to it.ورود دانشآموز هم همین کد است.
شناسهٔ شخص را از سرور LMS بردارید. معلم و دانشآموز پارامتر متفاوتی ندارند؛ خطای API را پیش از هدایت مرورگر مدیریت کنید.