signdeal — 싸인딜 Python SDK (0.3.0)
자기 서비스에서 싸인딜 전자계약을 보내고, 체결되면 웹훅을 받아 체결본 PDF를 저장하는 Python SDK입니다.
Node SDK(@signdeal/sdk 0.5.0)와 같은 표면을 snake_case로 옮겼습니다.
- Python 3.9 이상 · 실행 의존성 0(표준 라이브러리
urllib·hmac·hashlib·json만) · 타입 힌트(py.typed) - 동기 클라이언트만 있습니다(비동기 클라이언트는 아직 없음).
- MIT 라이선스 · 0.x 판(minor 마다 바뀔 수 있으니 올리기 전에 변경 내용을 확인하세요)
설치
pip install signdeal
# 또는
uv add signdeal
충전 → 키 → 발송 → 차감
연동사는 자기 싸인딜 계정에서 발송권을 충전하고(무료 건수 포함), 그 계정에서 만든 API 키를 서버에 넣습니다.
계약을 1건 보낼 때마다 그 계정의 발송권이 받는 사람 수만큼 줄어듭니다. 화면에서 보낼 때와 요금과 차감이 같습니다.
남은 건수는 client.usage()["send_remaining"]로 봅니다. 0인데 보내면 InsufficientCreditsError(HTTP 402)가 납니다.
시험 키(sk_test_)는 실제 발송과 과금이 없습니다. 하루 100건까지이고, 체결본에 「SANDBOX · 법적 효력 없음」이 찍힙니다.
5분 시작하기
키는 싸인딜 API·연동(/app/mcp)에서 만듭니다. 평문 키는 한 번만 보이니 바로 서버 환경 변수에 넣으세요.
export SIGNDEAL_API_KEY=sk_test_... # 코드·저장소에 키를 적지 마세요
# export SIGNDEAL_BASE_URL=... # 기본값은 https://api.signdeal.kr
base_url(또는 SIGNDEAL_BASE_URL)은 https여야 합니다. http는 localhost·127.0.0.1·::1(로컬 시험)에서만 되고, 그 밖의 http 주소는 생성자가 SignDealError(code insecure_base_url)를 던집니다.
from signdeal import SignDeal, InsufficientCreditsError, SignDealError
client = SignDeal() # SIGNDEAL_API_KEY · SIGNDEAL_BASE_URL 을 읽습니다
usage = client.usage()
print("시험 키" if client.is_test_key else f"남은 발송권 {usage['send_remaining']}건")
template = next((t for t in client.templates.list()["data"] if t["api_sendable"]), None) # fields[].key 가 values 의 키
if template is None:
raise SystemExit("API로 보낼 수 있는 양식이 없습니다 — 싸인딜 화면에서 양식을 먼저 만드세요")
# template["fields"] 에서 required 가 True 인 칸(key · label)은 values 에 모두 채워야 합니다
try:
sent = client.send(
template=template["template_id"],
to={"name": "홍길동", "phone": "010-0000-0000"},
values={}, # 양식의 필수 칸을 채우세요 — {fields[].key: 값} (templates.list 의 칸 목록 참고)
ref="order-1234", # 우리 쪽 주문 번호 — 웹훅에 그대로 돌아오고, 같은 ref 로 다시 보내도 1건만 발송
)
print(sent["contract_id"], sent["status"])
except InsufficientCreditsError:
... # 402 — 싸인딜 계정에서 충전 필요
except SignDealError as e:
print(e.status, e.code, e.request_id) # 문의할 때는 request_id 를 알려 주세요
client.send({...})처럼 dict 하나로 넘겨도 됩니다(키워드와 섞으면 키워드가 이깁니다).
받는 사람은 문자·알림톡의 서명 링크에서 본인확인 후 서명합니다. 연동사 서버가 대신 서명하는 API는 없고, 체결은 웹훅 contract.completed로 압니다.
웹훅 받기 → 체결본 저장
import os
from signdeal import SignDeal, verify_webhook, WebhookVerificationError
client = SignDeal()
os.makedirs("signed", exist_ok=True) # 체결본을 저장할 폴더
client.webhooks.create(url="https://example.com/webhooks/signdeal", secret=os.environ["SIGNDEAL_WEBHOOK_SECRET"], name="내 서비스")
# Flask — 서명은 「받은 원문 바이트」로 확인합니다(request.get_json() 말고 request.get_data()).
@app.post("/webhooks/signdeal")
def signdeal_webhook():
try:
event = verify_webhook(request.get_data(), request.headers, os.environ["SIGNDEAL_WEBHOOK_SECRET"])
except WebhookVerificationError as e:
return {"ok": False, "error": e.reason}, 400
if event["event"] == "contract.completed":
pdf = client.contracts.download_final_pdf(event["contract"]["id"])
open(f"signed/{event['contract']['id']}.pdf", "wb").write(pdf)
return {"ok": True}
Django는 verify_webhook(request.body, request.headers, secret)입니다. 프레임워크 없이 쓰려면 wsgi_webhook(secret, on_event)가 WSGI 앱을 만들어 줍니다(Node의 expressWebhook 짝).
끝까지 도는 예시는 examples/send_and_receive.py입니다(serve → register → send).
내 PDF 보내기 · 재촉 · 취소
from pathlib import Path
res = client.send_pdf(
title="용역 계약", pdf=Path("contract.pdf"),
recipients=[{"name": "홍길동", "phone": "010-0000-0000", "role": "r1"}],
roles=[{"id": "r1", "label": "받는 분", "side": "recipient"}],
fields=[{"type": "signature", "role": "r1", "page": 1, "x": 0.55, "y": 0.85, "w": 0.3, "h": 0.06}], # 좌표는 쪽 크기에 대한 0~1 비율
before_confirm=lambda preview: preview["would_send"], # False 면 확정하지 않음
)
client.contracts.remind(res["contract_id"]) # 차감 0 · 서명자당 24시간 1번(넘으면 RateLimitError)
client.contracts.void(res["contract_id"], reason="중복 발송") # 이미 취소됐으면 ConflictError(409)
서명 링크 직접 받기(delivery="none")
알림톡·문자를 보내지 않고, 응답 signers[]의 sign_url을 내 서비스에서 직접 전달합니다(본인인증 조직 · 시험 키만).
send와 send_pdf 모두 delivery="none"을 그대로 넘깁니다.
res = client.send(template="tpl_1", to={"name": "홍길동", "phone": "01000000000"}, delivery="none")
link = res["signers"][0]["sign_url"] # 비밀 링크 — 로그·분석 도구에 남기지 마세요
new = client.contracts.reissue_sign_urls(res["contract_id"]) # 새 링크 발급 · 이전 링크는 바로 무효 · 자동 재시도 없음
- 같은 요청이 자동 재시도로 이미 처리됐다면 응답에 링크가 없습니다. 이때
SignDealError(code="sign_urls_not_returned")가 납니다.send를 다시 부르지 말고contracts.reissue_sign_urls(contract_id)로 새 링크를 받으세요. - 응답을 로그에 남길 때는
signdeal.redact_sign_urls(응답)으로sign_url과/sign/<토큰>을 가립니다.
서명 뒤 돌아오기(복귀 값)
from signdeal import verify_return, ReturnVerificationError
def check_nonce(nonce: str, exp: int) -> bool:
# 「없을 때만 넣기」를 한 번에(확인과 저장을 나누면 동시 요청 둘이 다 통과합니다).
# 처음 본 nonce 면 exp(유닉스 초)까지 저장하고 True, 이미 본 nonce 면 False → reason "replayed"
return redis.set(f"signdeal:nonce:{nonce}", 1, nx=True, exat=exp) is True
payload = verify_return(request.args["signdeal_result"], os.environ["SIGNDEAL_RETURN_SECRET"], check_nonce=check_nonce)
# 이 값만 믿고 결제·권한 부여를 하지 말고, 웹훅 또는 client.contracts.get(payload["contract_id"]) 로 확인하세요.
기능
| 메서드 | 서버 경로 | 비고 |
|---|---|---|
send(**params) |
POST /api/send |
202 {contract_id, tracking_id, status, billing, …} · 멱등 키 자동 |
preview_send(**params) |
POST /api/send preview:true |
발송·차감 없음 |
usage() |
GET /api/usage |
send_remaining · requires_purchase · 시험 키면 sandbox |
contracts.get(id) |
GET /api/contracts/{id} |
서명자 상태 포함 |
contracts.list(limit=, offset=, status=, client_ref=) |
GET /api/contracts |
next_offset이 None이면 마지막 쪽 |
contracts.list_all(**filters) |
위와 같음 | 다음 쪽을 자동으로 넘기는 제너레이터 |
contracts.download_audit_certificate(id) |
GET …/audit |
감사추적 인증서 bytes. 체결 전이면 NotFoundError |
contracts.download_final_pdf(id) |
GET …/pdf?strict_final=1 |
체결본 bytes. 체결 전이면 NotFoundError |
contracts.download_base_pdf(id) |
GET …/pdf?kind=base |
서명 전 원본 |
contracts.remind(id, signer_ids=) |
POST /api/contracts/{id}:remind |
차감 0 · 자동 재시도 없음 |
contracts.reissue_sign_urls(id, signer_ids=) |
POST /api/contracts/{id}:reissue_sign_urls |
delivery="none" 계약 전용 · 새 링크 · 자동 재시도 없음 |
contracts.void(id, reason=, notify=) |
POST /api/contracts/{id}:void |
발송 취소 · 자동 재시도 없음 (Node contracts.void와 짝) |
templates.list(scope=, offset=, include_revision=) |
GET /api/templates |
api_sendable인 양식을 send에 |
documents.upload(pdf, file_name=) |
POST /api/documents |
bytes·파일 객체·Path · 같은 PDF는 reused:True |
send_pdf(**params, before_confirm=) |
올리기 → …:send_document ×2 |
미리보기와 확정에 같은 멱등 키 |
preview_pdf(**params) |
…:send_document dry_run |
미리보기만 |
embed.get_settings() / update_settings(allowed_origins=) / rotate_return_secret() |
/api/integrations/embed |
복귀 주소 허용 출처 · 복귀 비밀값 · update_settings·rotate_return_secret 자동 재시도 없음(비밀값은 첫 응답 1번뿐) |
webhooks.create/list/delete |
/api/integrations/webhooks |
create에 events·filter·name · create 자동 재시도 없음(두 번 돌면 첫 연동이 교체될 수 있음) |
webhooks.rotate_secret(id, overlap_seconds=) |
POST …/{id}/rotate-secret |
새 비밀값은 이 응답 1번뿐 · 자동 재시도 없음 |
webhooks.list_deliveries(id, limit=, cursor=) |
GET …/{id}/deliveries |
{data, next_cursor} |
webhooks.resend_delivery(id, delivery_id) |
POST …/deliveries/{did}/resend |
1건당 5번 · 자동 재시도 없음 |
verify_webhook · construct_event · verify_signature · wsgi_webhook |
— | 웹훅 서명 v1·v2 |
verify_return |
— | 복귀 값 검증(+ check_nonce 콜백) |
모든 메서드는 headers={...}로 요청 헤더를 덧붙일 수 있습니다. idempotency_key="..."는 send·preview_send·send_pdf·preview_pdf·documents.upload·contracts.remind만 받습니다. webhooks.create처럼 **fields를 받는 호출에 넣으면 요청 본문 칸이 되니 쓰지 마세요.
오류
API 오류는 모두 SignDealError(또는 그 하위)입니다. 속성: status(네트워크 오류는 0) · code(서버 error.code · network_error · timeout) · request_id · type · field · retryable · body.
| 클래스 | 언제 |
|---|---|
InsufficientCreditsError |
402 발송권 부족(payment_method_required). 충전하면 풀림. org_unverified(402)는 일반 SignDealError |
RateLimitError |
429. retry_after(초 · 본문 → Retry-After 헤더 순, 없으면 None) · next_allowed_at(재촉만). SDK는 429를 다시 보내지 않음 |
AuthenticationError / PermissionDeniedError / NotFoundError |
401 / 403 / 404 |
ValidationError / ConflictError / ServerError |
400·422 / 409 / 5xx |
WebhookVerificationError · ReturnVerificationError |
검증 실패 · .reason으로 이유 |
재시도와 멱등
- 리다이렉트(3xx)는 따라가지 않습니다.
SignDealError(code="redirect_not_followed")가 나고 다시 보내지 않습니다. - 네트워크 오류 · 시간 초과 · 5xx만, 같은 결과가 보장되는 호출만 다시 보냅니다(기본 2번 · 0.5초 → 1초 → 2초 · 최대 8초 · ±20%).
대상:
GET·PUT·DELETE, 그리고 서버가Idempotency-Key를 지키는send·preview_send·send_pdf·preview_pdf, 내용 주소인documents.upload. send계열은Idempotency-Key를 자동으로 붙이고 재시도에도 같은 키를 씁니다. 끊겨서 다시 보내도 1건만 발송·차감됩니다.- 재촉 · 취소 · 서명 링크 재발급 · 웹훅 등록 · 비밀값 교체 · 재전송은 다시 보내지 않습니다(같은 일을 두 번 하게 됩니다).
SignDeal(api_key, base_url=, timeout=30, max_retries=2, retry_base=0.5, headers=, transport=, logger=)로 바꿀 수 있습니다.- 모든 요청에
User-Agent: signdeal-python/0.3.0과X-SignDeal-Api-Version: v1이 붙습니다.
디버그 로그
logging.getLogger("signdeal")를 DEBUG로 켜면 요청·응답 한 줄씩(방법 · 경로 · 시도 횟수 · 상태 · request_id · 걸린 시간)이 찍힙니다.
본문은 찍지 않고, API 키 · Bearer 값 · 웹훅/복귀 비밀값 · 서명 주소의 토큰 · signdeal_result 값은 ***로 가립니다(signdeal.redact). 응답 dict는 signdeal.redact_sign_urls로 가립니다.
웹훅
- 서명 헤더는 두 개가 함께 옵니다. 비교는
hmac.compare_digest로 합니다.- 옛 헤더
X-SignDeal-Signature: sha256=<HMAC-SHA256(secret, 원문) hex> - 새 헤더
X-SignDeal-Signature-V2: t=<유닉스 초>,v2=<HMAC-SHA256(secret, "t.원문") hex>— 시각이 들어가 있어, 이 헤더가 오면 허용 시각 범위 밖의 오래된 재전송을 거릅니다. 옛 헤더(v1)만 오면 시각 검사가 없으니require_v2=True를 주면 V2 없는 요청을 거절합니다(기본False· 호환 유지).
- 옛 헤더
- 헤더 묶음(dict · Flask/Django
request.headers등)을 주면 V2가 있으면 V2로(시각 허용 기본 300초 ·tolerance_seconds=· 넘으면timestamp_out_of_range), 없으면 옛 헤더로 확인합니다. 옛 헤더 값 문자열만 주면 옛 방식으로만 확인합니다. - 비밀값 교체 겹침 동안에는
secret=[새, 옛]을 주세요. - 이벤트 9종:
contract.sent·completed·declined·voided·signer_signed·viewed·expired·credits.low·integration.test. 모르는 이벤트 이름이 와도 던지지 않습니다. - 재시도·재전송은 같은
event_id로 옵니다.event_id로 중복 처리를 막으세요(시각 검사를 써도 계속 권장합니다). now=는 유닉스 초(또는datetime)입니다 — Node는 밀리초.
라이선스
MIT — 저장소의 LICENSE(패키지에 함께 들어갑니다).
Metadata
Release files for signdeal 0.3.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| signdeal-0.3.0.tar.gz | 53.2 kB | Without provenance | Details for signdeal-0.3.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| signdeal-0.3.0-py3-none-any.whl | Python 3 | none | any | Details for signdeal-0.3.0-py3-none-any.whl |
Total release size: 87.2 kB
Release files / signdeal-0.3.0.tar.gz
| Download URL | signdeal-0.3.0.tar.gz |
|---|---|
| Size | 53.2 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
6b308772a7bec1f192e8d32e04a6d93929dd1bbc7645a8050139aee284c34ba0
|
|
BLAKE2b-256 checksum How to use checksums |
fec24905a9e037b1a7cddc04c7fe68c9a677dcee3da906da4f0c371eaf274046
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.11.12 {"installer":{"name":"uv","version":"0.11.12","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
|
Release files / signdeal-0.3.0-py3-none-any.whl
| Download URL | signdeal-0.3.0-py3-none-any.whl |
|---|---|
| Size | 34.0 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
1a3f15cfe660aa2938ba1f3a2e0da65c63193ef2fbec82881429fc32c9c8cdd2
|
|
BLAKE2b-256 checksum How to use checksums |
3b0b7b4cd2ad3f7886e043bc91520f2df7bb4e39da7fbdfb8082a772332221fb
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.11.12 {"installer":{"name":"uv","version":"0.11.12","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
|
Security for signdeal 0.3.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.