socialcli 0.3.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of socialcli might be problematic. Click here for more details.
- socialcli-0.3.0.dist-info/METADATA +168 -0
- socialcli-0.3.0.dist-info/RECORD +224 -0
- socialcli-0.3.0.dist-info/WHEEL +4 -0
- socialcli-0.3.0.dist-info/entry_points.txt +3 -0
- socialcli-0.3.0.dist-info/licenses/LICENSE +21 -0
- socialctl/__init__.py +0 -0
- socialctl/__main__.py +6 -0
- socialctl/adapters/__init__.py +6 -0
- socialctl/adapters/base.py +68 -0
- socialctl/adapters/errores.py +56 -0
- socialctl/adapters/facebook.py +180 -0
- socialctl/adapters/instagram.py +442 -0
- socialctl/adapters/tiktok.py +535 -0
- socialctl/adapters/youtube.py +331 -0
- socialctl/agent_errors.py +176 -0
- socialctl/agent_guide.py +23 -0
- socialctl/approval_cli.py +27 -0
- socialctl/auth.py +139 -0
- socialctl/authflow.py +344 -0
- socialctl/brands.py +194 -0
- socialctl/capabilities.py +57 -0
- socialctl/capabilities.yml +5945 -0
- socialctl/cli.py +1766 -0
- socialctl/connection_service/__init__.py +0 -0
- socialctl/connection_service/__main__.py +33 -0
- socialctl/connection_service/app.py +496 -0
- socialctl/connection_service/assets/PLATFORM-LOGOS-LICENSE.txt +50 -0
- socialctl/connection_service/assets/connection.css +75 -0
- socialctl/connection_service/assets/facebook.webp +0 -0
- socialctl/connection_service/assets/instagram.svg +194 -0
- socialctl/connection_service/assets/socialcli-logo.png +0 -0
- socialctl/connection_service/assets/tiktok.png +0 -0
- socialctl/connection_service/assets/youtube.svg +1 -0
- socialctl/connection_service/landing.py +146 -0
- socialctl/connection_service/legacy.py +48 -0
- socialctl/connection_service/peer.py +13 -0
- socialctl/connection_service/providers.py +324 -0
- socialctl/connection_service/settings.py +76 -0
- socialctl/connection_service/store.py +124 -0
- socialctl/connections/__init__.py +0 -0
- socialctl/connections/account_cli.py +438 -0
- socialctl/connections/cli.py +379 -0
- socialctl/connections/client.py +126 -0
- socialctl/connections/credential_cli.py +224 -0
- socialctl/connections/credential_store.py +49 -0
- socialctl/connections/file_store.py +193 -0
- socialctl/connections/keychain.py +78 -0
- socialctl/connections/meta_user.py +81 -0
- socialctl/connections/rotation_cli.py +116 -0
- socialctl/connections/saas_client.py +91 -0
- socialctl/connections/temporary_media.py +62 -0
- socialctl/delivery_options.py +70 -0
- socialctl/engagement.py +200 -0
- socialctl/engagement_cli.py +50 -0
- socialctl/executor.py +135 -0
- socialctl/formatter.py +291 -0
- socialctl/hosted_media.py +152 -0
- socialctl/identity.py +200 -0
- socialctl/inbox.py +298 -0
- socialctl/inbox_cli.py +46 -0
- socialctl/inventory.py +155 -0
- socialctl/inventory_cli.py +171 -0
- socialctl/inventory_sources.py +101 -0
- socialctl/management/__init__.py +1 -0
- socialctl/management/batch_cli.py +115 -0
- socialctl/management/batches.py +325 -0
- socialctl/management/changes.py +485 -0
- socialctl/management/cli.py +227 -0
- socialctl/management/comments_cli.py +352 -0
- socialctl/management/community_batch_cli.py +63 -0
- socialctl/management/community_batches.py +294 -0
- socialctl/management/community_changes.py +370 -0
- socialctl/management/community_cli.py +142 -0
- socialctl/management/community_schema.py +119 -0
- socialctl/management/facebook_groups.py +1118 -0
- socialctl/management/groups_cli.py +274 -0
- socialctl/management/inbox_readers.py +87 -0
- socialctl/management/meta_changes.py +197 -0
- socialctl/management/meta_cli.py +342 -0
- socialctl/management/meta_client.py +631 -0
- socialctl/management/meta_comment_inbox.py +565 -0
- socialctl/management/meta_comments.py +587 -0
- socialctl/management/meta_errors.py +59 -0
- socialctl/management/meta_pagination.py +52 -0
- socialctl/management/meta_schema.py +128 -0
- socialctl/management/meta_webhooks.py +147 -0
- socialctl/management/metadata_parts.py +144 -0
- socialctl/management/owned_assets.py +85 -0
- socialctl/management/owned_changes.py +470 -0
- socialctl/management/owned_cli.py +128 -0
- socialctl/management/owned_reorder.py +62 -0
- socialctl/management/owned_schema.py +368 -0
- socialctl/management/reply_context.py +24 -0
- socialctl/management/reply_evidence.py +80 -0
- socialctl/management/resource_changes.py +407 -0
- socialctl/management/resource_cli.py +136 -0
- socialctl/management/snippet_readback.py +26 -0
- socialctl/management/stories.py +713 -0
- socialctl/management/stories_cli.py +172 -0
- socialctl/management/youtube.py +323 -0
- socialctl/management/youtube_community.py +326 -0
- socialctl/management/youtube_metadata.py +122 -0
- socialctl/management/youtube_owned.py +259 -0
- socialctl/management/youtube_resources.py +305 -0
- socialctl/media.py +269 -0
- socialctl/media_cli.py +183 -0
- socialctl/media_ingress.py +211 -0
- socialctl/media_preflight.py +114 -0
- socialctl/media_registry.py +301 -0
- socialctl/media_requirements.py +52 -0
- socialctl/metricas/__init__.py +6 -0
- socialctl/metricas/almacen.py +133 -0
- socialctl/metricas/analytics_changes.py +295 -0
- socialctl/metricas/analytics_cli.py +191 -0
- socialctl/metricas/analytics_client.py +304 -0
- socialctl/metricas/analytics_ingest.py +260 -0
- socialctl/metricas/analytics_schema.py +174 -0
- socialctl/metricas/base.py +147 -0
- socialctl/metricas/facebook.py +418 -0
- socialctl/metricas/insights.py +227 -0
- socialctl/metricas/instagram.py +133 -0
- socialctl/metricas/modelos.py +87 -0
- socialctl/metricas/piezas.py +134 -0
- socialctl/metricas/reach.py +94 -0
- socialctl/metricas/reporting_client.py +112 -0
- socialctl/metricas/resumen.py +251 -0
- socialctl/metricas/slugs.py +89 -0
- socialctl/metricas/tiktok.py +185 -0
- socialctl/metricas/youtube.py +403 -0
- socialctl/migration_cli.py +60 -0
- socialctl/migration_files.py +68 -0
- socialctl/models.py +150 -0
- socialctl/native_schedule/__init__.py +13 -0
- socialctl/native_schedule/api_delivery.py +15 -0
- socialctl/native_schedule/api_reconcile.py +40 -0
- socialctl/native_schedule/approval.py +160 -0
- socialctl/native_schedule/cadence.py +73 -0
- socialctl/native_schedule/cli.py +510 -0
- socialctl/native_schedule/dispatcher.py +120 -0
- socialctl/native_schedule/facebook.py +112 -0
- socialctl/native_schedule/facebook_reels.py +140 -0
- socialctl/native_schedule/first_comment.py +181 -0
- socialctl/native_schedule/handoff.py +193 -0
- socialctl/native_schedule/instagram_delivery.py +224 -0
- socialctl/native_schedule/instagram_runtime.py +66 -0
- socialctl/native_schedule/inventory.py +70 -0
- socialctl/native_schedule/migration.py +310 -0
- socialctl/native_schedule/models.py +103 -0
- socialctl/native_schedule/reconcile.py +83 -0
- socialctl/native_schedule/remote_data.py +177 -0
- socialctl/native_schedule/report.py +151 -0
- socialctl/native_schedule/store.py +560 -0
- socialctl/native_schedule/verification.py +32 -0
- socialctl/native_schedule/youtube.py +339 -0
- socialctl/operation_output.py +87 -0
- socialctl/plantillas/accounts.yml +33 -0
- socialctl/plantillas/brand.md +95 -0
- socialctl/plantillas/estrategia.md +64 -0
- socialctl/postfile.py +240 -0
- socialctl/preflight.py +73 -0
- socialctl/publication_policy.py +34 -0
- socialctl/publication_status.py +75 -0
- socialctl/publication_steps.py +398 -0
- socialctl/publish_output.py +96 -0
- socialctl/publisher.py +445 -0
- socialctl/queue_migration.py +302 -0
- socialctl/read_budget.py +224 -0
- socialctl/read_reports.py +91 -0
- socialctl/rutas.py +103 -0
- socialctl/saas/__init__.py +1 -0
- socialctl/saas/access.py +75 -0
- socialctl/saas/auth.py +213 -0
- socialctl/saas/backup.py +124 -0
- socialctl/saas/billing.py +327 -0
- socialctl/saas/billing_enrollment.py +1237 -0
- socialctl/saas/billing_enrollment_schema.py +519 -0
- socialctl/saas/billing_inventory.py +775 -0
- socialctl/saas/billing_reconcile.py +127 -0
- socialctl/saas/billing_routes.py +27 -0
- socialctl/saas/budget.py +66 -0
- socialctl/saas/connections.py +374 -0
- socialctl/saas/consent.py +52 -0
- socialctl/saas/lifecycle.py +341 -0
- socialctl/saas/mail.py +89 -0
- socialctl/saas/maintenance.py +68 -0
- socialctl/saas/meta_user.py +298 -0
- socialctl/saas/meta_webhooks.py +358 -0
- socialctl/saas/migration.py +107 -0
- socialctl/saas/models.py +8 -0
- socialctl/saas/operations.py +102 -0
- socialctl/saas/pages.py +126 -0
- socialctl/saas/pairing.py +158 -0
- socialctl/saas/permissions.py +57 -0
- socialctl/saas/reminders.py +128 -0
- socialctl/saas/renewal.py +74 -0
- socialctl/saas/restore_guard.py +229 -0
- socialctl/saas/revocation.py +97 -0
- socialctl/saas/rotation.py +114 -0
- socialctl/saas/routes.py +221 -0
- socialctl/saas/settings.py +34 -0
- socialctl/saas/store.py +106 -0
- socialctl/saas/temporary_media.py +245 -0
- socialctl/saas/webhooks.py +76 -0
- socialctl/schedule_remote.py +262 -0
- socialctl/schedule_sqlite.py +44 -0
- socialctl/scheduler.py +581 -0
- socialctl/scheduler_launchd.py +319 -0
- socialctl/scheduler_systemd.py +167 -0
- socialctl/source_links.py +119 -0
- socialctl/ui/__init__.py +1 -0
- socialctl/ui/assets/agent-manual.md +850 -0
- socialctl/ui/assets/agents.md +27 -0
- socialctl/ui/assets/components.css +20 -0
- socialctl/ui/assets/connection-layout.css +53 -0
- socialctl/ui/assets/otp.template.html +10 -0
- socialctl/ui/assets/tokens.css +1 -0
- socialctl/ui/assets/trial.template.html +11 -0
- socialctl/ui/assets/web-layout.css +38 -0
- socialctl/ui/email/otp.html +10 -0
- socialctl/ui/email/trial.html +11 -0
- socialctl/upload_consent.py +13 -0
- socialctl/workspace.py +8 -0
- socialctl/youtube_data.py +471 -0
- socialctl/youtube_data_service.py +225 -0
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
"""Mode-validated Stripe billing with durable checkout intents and short local locks."""
|
|
2
|
+
from contextlib import contextmanager
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
|
+
import os
|
|
5
|
+
import re
|
|
6
|
+
import secrets
|
|
7
|
+
from urllib.parse import urlsplit
|
|
8
|
+
import httpx
|
|
9
|
+
from fastapi import HTTPException
|
|
10
|
+
from socialctl.saas.access import AccessControl
|
|
11
|
+
from socialctl.saas.budget import BudgetExpired
|
|
12
|
+
|
|
13
|
+
API_VERSION = '2025-09-30.clover'
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class AnchorRejected(Exception):
|
|
17
|
+
"""Stripe rejected the anchor before starting Checkout execution."""
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass(frozen=True)
|
|
22
|
+
class BillingSettings:
|
|
23
|
+
secret_key: str = field(repr=False)
|
|
24
|
+
webhook_secret: str = field(repr=False)
|
|
25
|
+
price_id: str
|
|
26
|
+
account_id: str
|
|
27
|
+
portal_configuration: str
|
|
28
|
+
mode: str = 'test'
|
|
29
|
+
|
|
30
|
+
def __post_init__(self):
|
|
31
|
+
if self.mode not in {'test','live'} or not self.secret_key.startswith('sk_'+self.mode+'_'):
|
|
32
|
+
raise ValueError('Stripe mode and secret key must match')
|
|
33
|
+
for value, prefix in [(self.webhook_secret,'whsec_'),(self.price_id,'price_'),
|
|
34
|
+
(self.account_id,'acct_'),(self.portal_configuration,'bpc_')]:
|
|
35
|
+
if not re.fullmatch(re.escape(prefix)+r'[A-Za-z0-9_]+',value):
|
|
36
|
+
raise ValueError('Incomplete Stripe configuration')
|
|
37
|
+
|
|
38
|
+
@property
|
|
39
|
+
def expected_livemode(self):
|
|
40
|
+
return self.mode == 'live'
|
|
41
|
+
|
|
42
|
+
@classmethod
|
|
43
|
+
def from_environment(cls):
|
|
44
|
+
mode=os.environ.get('SOCIALCLI_BILLING_MODE','')
|
|
45
|
+
if not mode:
|
|
46
|
+
return None
|
|
47
|
+
return cls(secret_key=os.environ.get('STRIPE_SECRET_KEY',''),
|
|
48
|
+
webhook_secret=os.environ.get('STRIPE_WEBHOOK_SECRET',''),
|
|
49
|
+
price_id=os.environ.get('STRIPE_PRICE_ID',''),
|
|
50
|
+
account_id=os.environ.get('STRIPE_ACCOUNT_ID',''),
|
|
51
|
+
portal_configuration=os.environ.get('STRIPE_PORTAL_CONFIGURATION',''),mode=mode)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def unavailable():
|
|
55
|
+
return HTTPException(503,'Billing is temporarily unavailable. Please try again; do not start another purchase.')
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def stripe_id(value,prefix):
|
|
59
|
+
if not isinstance(value,str) or not re.fullmatch(re.escape(prefix)+r'[A-Za-z0-9_]+',value):
|
|
60
|
+
raise unavailable()
|
|
61
|
+
return value
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def fixed_price(price,expected,*,active=False,expected_livemode=False):
|
|
65
|
+
recurring=price.get('recurring') or {}
|
|
66
|
+
return (price.get('id')==expected and price.get('livemode') is expected_livemode
|
|
67
|
+
and price.get('type')=='recurring' and price.get('currency')=='usd'
|
|
68
|
+
and price.get('unit_amount')==1000 and recurring.get('interval')=='month'
|
|
69
|
+
and recurring.get('interval_count')==1 and recurring.get('usage_type')=='licensed'
|
|
70
|
+
and not recurring.get('trial_period_days') and not price.get('transform_quantity')
|
|
71
|
+
and (not active or price.get('active') is True))
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class BillingService:
|
|
75
|
+
def __init__(self,metadata,settings,client,clock,origin):
|
|
76
|
+
self.metadata,self.vault,self.settings=metadata,metadata.vault,settings
|
|
77
|
+
self.client,self.clock,self.origin=client,clock,origin
|
|
78
|
+
self.access=AccessControl(metadata)
|
|
79
|
+
self.budget=None
|
|
80
|
+
self.bind_environment()
|
|
81
|
+
|
|
82
|
+
def bind_environment(self):
|
|
83
|
+
"""Never reinterpret persisted sandbox access by changing configuration."""
|
|
84
|
+
expected={'account_id':self.settings.account_id,'mode':self.settings.mode}
|
|
85
|
+
error='The billing environment differs from persisted state; keep commercial access closed and use the reviewed cutover procedure.'
|
|
86
|
+
with self.vault.transaction() as db:
|
|
87
|
+
bound=self.vault.get(db,'saas-billing-environment','active')
|
|
88
|
+
if bound:
|
|
89
|
+
if bound['payload']!=expected:
|
|
90
|
+
raise ValueError(error)
|
|
91
|
+
return
|
|
92
|
+
# No unbound billing history proves which account created customer
|
|
93
|
+
# pointers or uncertain intents, even if all recorded events agree.
|
|
94
|
+
# Legacy enrollment requires a separately reviewed offline procedure.
|
|
95
|
+
legacy=(db.execute('SELECT 1 FROM saas_billing LIMIT 1').fetchone()
|
|
96
|
+
or db.execute('SELECT 1 FROM saas_billing_events LIMIT 1').fetchone()
|
|
97
|
+
or db.execute("SELECT 1 FROM saas_entitlements WHERE paid_until>0 OR subscription_status<>'' LIMIT 1").fetchone()
|
|
98
|
+
or db.execute("SELECT 1 FROM records WHERE kind IN ('saas-checkout-intent','saas-stripe-event') LIMIT 1").fetchone())
|
|
99
|
+
if legacy:
|
|
100
|
+
raise ValueError(error)
|
|
101
|
+
self.vault.put(db,'saas-billing-environment','active',expected,expires=253402300799)
|
|
102
|
+
|
|
103
|
+
def api(self,method,path,data=None,key=None):
|
|
104
|
+
headers={'Authorization':'Bearer '+self.settings.secret_key,'Stripe-Version':API_VERSION}
|
|
105
|
+
if key:headers['Idempotency-Key']=key
|
|
106
|
+
try:
|
|
107
|
+
with self.client.stream(method,'https://api.stripe.com/v1'+path,headers=headers,
|
|
108
|
+
params=data if method=='GET' else None,data=data if method!='GET' else None,
|
|
109
|
+
timeout=self.budget.timeout(20) if self.budget else 20,follow_redirects=False) as response:
|
|
110
|
+
content=bytearray()
|
|
111
|
+
for chunk in response.iter_bytes():
|
|
112
|
+
if self.budget and self.budget.expired():raise BudgetExpired()
|
|
113
|
+
content.extend(chunk)
|
|
114
|
+
if len(content)>2*1024*1024:raise unavailable()
|
|
115
|
+
import json
|
|
116
|
+
value=json.loads(content)
|
|
117
|
+
if response.status_code!=200:
|
|
118
|
+
error=value.get('error',{}) if isinstance(value,dict) else {}
|
|
119
|
+
if (response.status_code==400 and method=='POST' and path=='/checkout/sessions'
|
|
120
|
+
and error.get('type')=='invalid_request_error'
|
|
121
|
+
and error.get('param')=='subscription_data[billing_cycle_anchor]'):
|
|
122
|
+
raise AnchorRejected()
|
|
123
|
+
raise unavailable()
|
|
124
|
+
if not isinstance(value,dict):raise unavailable()
|
|
125
|
+
return value
|
|
126
|
+
except (httpx.HTTPError,ValueError,TypeError,BudgetExpired):
|
|
127
|
+
raise unavailable() from None
|
|
128
|
+
|
|
129
|
+
def verify_configuration(self):
|
|
130
|
+
if self.api('GET','/account').get('id')!=self.settings.account_id:
|
|
131
|
+
raise unavailable()
|
|
132
|
+
if not fixed_price(self.api('GET','/prices/'+self.settings.price_id),self.settings.price_id,active=True,expected_livemode=self.settings.expected_livemode):
|
|
133
|
+
raise unavailable()
|
|
134
|
+
|
|
135
|
+
def owned(self,obj,user_id):
|
|
136
|
+
return obj.get('livemode') is self.settings.expected_livemode and obj.get('metadata',{}).get('app')=='socialcli' and obj.get('metadata',{}).get('user_id')==user_id
|
|
137
|
+
|
|
138
|
+
@contextmanager
|
|
139
|
+
def lease(self,user_id,*,checkout=False):
|
|
140
|
+
token=secrets.token_urlsafe(24)
|
|
141
|
+
with self.vault.transaction() as db:
|
|
142
|
+
user=self.metadata.user(db,user_id)
|
|
143
|
+
if user is None or user['deleting']:
|
|
144
|
+
raise HTTPException(403,'This account is unavailable.')
|
|
145
|
+
if checkout and self.access.decision(db,user_id,self.clock()).reason not in {'trial','trial_expired'}:
|
|
146
|
+
raise HTTPException(409,'Connect your first social account to start your trial, or manage your existing subscription.')
|
|
147
|
+
db.execute('INSERT OR IGNORE INTO saas_billing(user_id,customer_key,customer_started) VALUES(?,?,?)',
|
|
148
|
+
(user_id,secrets.token_hex(20),0))
|
|
149
|
+
row=db.execute('SELECT * FROM saas_billing WHERE user_id=?',(user_id,)).fetchone()
|
|
150
|
+
if row['lease_until']>self.clock():
|
|
151
|
+
raise HTTPException(409,'Your billing request is already being processed. Please try again shortly.')
|
|
152
|
+
db.execute('UPDATE saas_billing SET lease=?,lease_until=? WHERE user_id=?',(token,self.clock()+180,user_id))
|
|
153
|
+
row=dict(row)
|
|
154
|
+
try:
|
|
155
|
+
yield row,token
|
|
156
|
+
finally:
|
|
157
|
+
with self.vault.transaction() as db:
|
|
158
|
+
db.execute('UPDATE saas_billing SET lease=NULL,lease_until=0 WHERE user_id=? AND lease=?',(user_id,token))
|
|
159
|
+
|
|
160
|
+
def save(self,user_id,token,**values):
|
|
161
|
+
allowed={'customer_id','subscription_id','checkout_id','attempt','attempt_started','sync_due','cancel_at_period_end','review','customer_started'}
|
|
162
|
+
if not values or not values.keys()<=allowed:raise ValueError('Invalid billing update')
|
|
163
|
+
with self.vault.transaction() as db:
|
|
164
|
+
user=self.metadata.user(db,user_id)
|
|
165
|
+
if user is None or user['deleting']:raise HTTPException(403,'This account is unavailable.')
|
|
166
|
+
count=db.execute('UPDATE saas_billing SET '+','.join(k+'=?' for k in values)+' WHERE user_id=? AND lease=? AND lease_until>?',
|
|
167
|
+
(*values.values(),user_id,token,self.clock())).rowcount
|
|
168
|
+
if count!=1:raise HTTPException(409,'Billing is still being checked. Please try again.')
|
|
169
|
+
|
|
170
|
+
def customer(self,user_id,row,token,*,create=False):
|
|
171
|
+
customer_id=row['customer_id']
|
|
172
|
+
if customer_id:
|
|
173
|
+
customer=self.api('GET','/customers/'+stripe_id(customer_id,'cus_'))
|
|
174
|
+
elif create:
|
|
175
|
+
# Stripe may prune idempotency after 24h. Never retry an unresolved
|
|
176
|
+
# customer creation beyond that window and risk a second customer.
|
|
177
|
+
if row['customer_started'] and self.clock()-row['customer_started']>=23*3600:
|
|
178
|
+
raise HTTPException(409,'An earlier billing request needs review before another purchase.')
|
|
179
|
+
if not row['customer_started']:
|
|
180
|
+
self.save(user_id,token,customer_started=self.clock())
|
|
181
|
+
row['customer_started']=self.clock()
|
|
182
|
+
customer=self.api('POST','/customers',{'metadata[app]':'socialcli','metadata[user_id]':user_id},'socialcli-customer-'+row['customer_key'])
|
|
183
|
+
customer_id=stripe_id(customer.get('id'),'cus_')
|
|
184
|
+
if not self.owned(customer,user_id):raise unavailable()
|
|
185
|
+
self.save(user_id,token,customer_id=customer_id)
|
|
186
|
+
row['customer_id']=customer_id
|
|
187
|
+
else:
|
|
188
|
+
raise HTTPException(409,'There is no billing account yet.')
|
|
189
|
+
if not self.owned(customer,user_id):raise unavailable()
|
|
190
|
+
return customer_id
|
|
191
|
+
|
|
192
|
+
def listing(self,path,params):
|
|
193
|
+
result=[]
|
|
194
|
+
for _ in range(10):
|
|
195
|
+
response=self.api('GET',path,{**params,'limit':100})
|
|
196
|
+
data=response.get('data')
|
|
197
|
+
if not isinstance(data,list):raise unavailable()
|
|
198
|
+
result.extend(data)
|
|
199
|
+
if response.get('has_more') is False:return result
|
|
200
|
+
if not data or not data[-1].get('id'):raise unavailable()
|
|
201
|
+
params={**params,'starting_after':data[-1]['id']}
|
|
202
|
+
raise unavailable()
|
|
203
|
+
|
|
204
|
+
def redirect_url(self,value,host):
|
|
205
|
+
url=urlsplit(value or '')
|
|
206
|
+
if url.scheme!='https' or url.hostname!=host or url.username or url.password or url.port not in (None,443):
|
|
207
|
+
raise unavailable()
|
|
208
|
+
return value
|
|
209
|
+
|
|
210
|
+
def checkout(self,user_id):
|
|
211
|
+
with self.lease(user_id,checkout=True) as (row,token):
|
|
212
|
+
self.verify_configuration()
|
|
213
|
+
customer=self.customer(user_id,row,token,create=True)
|
|
214
|
+
subscriptions=self.listing('/subscriptions',{'customer':customer,'status':'all'})
|
|
215
|
+
if any(s.get('status') not in {'canceled','incomplete_expired'} for s in subscriptions):
|
|
216
|
+
raise HTTPException(409,'You already have a subscription. Use Manage billing to update your payment or cancel.')
|
|
217
|
+
from socialctl.saas.billing_reconcile import paid_until
|
|
218
|
+
canceled=[s for s in subscriptions if s.get('status')=='canceled']
|
|
219
|
+
invoices=self.listing('/invoices',{'customer':customer,'status':'paid'}) if canceled else []
|
|
220
|
+
if any(paid_until(self,customer,s,invoices)>self.clock() for s in canceled):
|
|
221
|
+
raise HTTPException(409,'Your paid access has not ended. You can subscribe again after it ends.')
|
|
222
|
+
sessions=self.listing('/checkout/sessions',{'customer':customer})
|
|
223
|
+
opened=[s for s in sessions if s.get('mode')=='subscription' and s.get('status')=='open']
|
|
224
|
+
if len(opened)>1:raise HTTPException(409,'Multiple payment requests need review. Please use Manage billing.')
|
|
225
|
+
if opened:
|
|
226
|
+
session=opened[0]
|
|
227
|
+
if not self.owned(session,user_id) or session.get('customer')!=customer:raise unavailable()
|
|
228
|
+
items=self.listing('/checkout/sessions/'+stripe_id(session.get('id'),'cs_')+'/line_items',{})
|
|
229
|
+
if len(items)!=1 or items[0].get('quantity')!=1 or not fixed_price(items[0].get('price',{}),self.settings.price_id,expected_livemode=self.settings.expected_livemode):raise unavailable()
|
|
230
|
+
self.save(user_id,token,checkout_id=stripe_id(session.get('id'),'cs_'))
|
|
231
|
+
return self.redirect_url(session.get('url'),'checkout.stripe.com')
|
|
232
|
+
previous=next((s for s in sessions if s.get('metadata',{}).get('attempt')==row['attempt']),None)
|
|
233
|
+
if previous and previous.get('status')=='complete' and not subscriptions:
|
|
234
|
+
raise HTTPException(409,'Your previous purchase is being checked. Please use Manage billing.')
|
|
235
|
+
attempt=row['attempt']
|
|
236
|
+
if not attempt or previous and previous.get('status') in {'expired','complete'}:
|
|
237
|
+
attempt=secrets.token_hex(20)
|
|
238
|
+
self.save(user_id,token,attempt=attempt,attempt_started=self.clock(),checkout_id=None)
|
|
239
|
+
elif self.clock()-row['attempt_started']>=23*3600:
|
|
240
|
+
raise HTTPException(409,'An earlier payment request needs review before another purchase.')
|
|
241
|
+
# Persist the complete time-sensitive choice before the HTTP request.
|
|
242
|
+
# Retrying an uncertain request must retain exactly the same parameters.
|
|
243
|
+
with self.vault.transaction() as db:
|
|
244
|
+
intent=self.vault.get(db,'saas-checkout-intent',attempt)
|
|
245
|
+
if intent:
|
|
246
|
+
deferred=intent['payload']['deferred']
|
|
247
|
+
else:
|
|
248
|
+
entitlement=db.execute('SELECT trial_end FROM saas_entitlements WHERE user_id=?',(user_id,)).fetchone()
|
|
249
|
+
deadline=int(entitlement['trial_end']) if entitlement and entitlement['trial_end'] else 0
|
|
250
|
+
deferred=({'subscription_data[billing_cycle_anchor]':deadline,
|
|
251
|
+
'subscription_data[proration_behavior]':'none',
|
|
252
|
+
'payment_method_collection':'always'} if deadline>self.clock() else {})
|
|
253
|
+
self.vault.put(db,'saas-checkout-intent',attempt,{'user_id':user_id,'deferred':deferred},expires=self.clock()+30*86400)
|
|
254
|
+
try:
|
|
255
|
+
session=self.api('POST','/checkout/sessions',{
|
|
256
|
+
**deferred,
|
|
257
|
+
'mode':'subscription','customer':customer,'line_items[0][price]':self.settings.price_id,
|
|
258
|
+
'line_items[0][quantity]':1,'success_url':self.origin+'/account/?payment=processing',
|
|
259
|
+
'cancel_url':self.origin+'/account/?payment=canceled','client_reference_id':user_id,
|
|
260
|
+
'metadata[app]':'socialcli','metadata[user_id]':user_id,'metadata[attempt]':attempt,
|
|
261
|
+
'subscription_data[metadata][app]':'socialcli','subscription_data[metadata][user_id]':user_id,
|
|
262
|
+
'payment_method_types[0]':'card','allow_promotion_codes':'false',
|
|
263
|
+
'branding_settings[display_name]':'SocialCli','branding_settings[background_color]':'#f5f7fb',
|
|
264
|
+
'branding_settings[button_color]':'#1464ec','branding_settings[font_family]':'default',
|
|
265
|
+
},'socialcli-checkout-'+attempt)
|
|
266
|
+
except AnchorRejected:
|
|
267
|
+
if deferred.get('subscription_data[billing_cycle_anchor]',float('inf'))<=self.clock():
|
|
268
|
+
# Only a definitive pre-execution validation failure releases
|
|
269
|
+
# this intent. Timeouts and ambiguous failures keep the same key.
|
|
270
|
+
self.save(user_id,token,attempt=None,attempt_started=None,checkout_id=None)
|
|
271
|
+
raise HTTPException(409,'Your trial ended while Checkout was opening. Open Subscribe again to review your first payment.') from None
|
|
272
|
+
raise unavailable() from None
|
|
273
|
+
if not self.owned(session,user_id) or session.get('customer')!=customer or session.get('mode')!='subscription':raise unavailable()
|
|
274
|
+
self.save(user_id,token,checkout_id=stripe_id(session.get('id'),'cs_'))
|
|
275
|
+
return self.redirect_url(session.get('url'),'checkout.stripe.com')
|
|
276
|
+
|
|
277
|
+
def portal(self,user_id):
|
|
278
|
+
with self.lease(user_id) as (row,token):
|
|
279
|
+
if self.api('GET','/account').get('id')!=self.settings.account_id:raise unavailable()
|
|
280
|
+
customer=self.customer(user_id,row,token)
|
|
281
|
+
session=self.api('POST','/billing_portal/sessions',{'customer':customer,
|
|
282
|
+
'configuration':self.settings.portal_configuration,'return_url':self.origin+'/account/'},
|
|
283
|
+
'socialcli-portal-'+token)
|
|
284
|
+
return self.redirect_url(session.get('url'),'billing.stripe.com')
|
|
285
|
+
|
|
286
|
+
def reconcile(self,user_id):
|
|
287
|
+
from socialctl.saas.billing_reconcile import reconcile
|
|
288
|
+
return reconcile(self,user_id)
|
|
289
|
+
|
|
290
|
+
def delete_account_billing(self,user_id,row):
|
|
291
|
+
"""No new charges: wait for in-flight Checkout, expire sessions, cancel subscriptions."""
|
|
292
|
+
if row['lease_until']>self.clock():raise HTTPException(409,'Billing cleanup is waiting for an earlier request.')
|
|
293
|
+
if self.api('GET','/account').get('id')!=self.settings.account_id:raise unavailable()
|
|
294
|
+
customer=row['customer_id']
|
|
295
|
+
if not customer:
|
|
296
|
+
if not row['customer_started']:return
|
|
297
|
+
if self.clock()-row['customer_started']>=23*3600:raise unavailable()
|
|
298
|
+
result=self.api('POST','/customers',{'metadata[app]':'socialcli','metadata[user_id]':user_id},'socialcli-customer-'+row['customer_key'])
|
|
299
|
+
if not self.owned(result,user_id):raise unavailable()
|
|
300
|
+
customer=stripe_id(result.get('id'),'cus_')
|
|
301
|
+
with self.vault.transaction() as db:
|
|
302
|
+
db.execute('UPDATE saas_billing SET customer_id=? WHERE user_id=?',(customer,user_id))
|
|
303
|
+
owner=self.api('GET','/customers/'+stripe_id(customer,'cus_'))
|
|
304
|
+
if owner.get('deleted') is True and owner.get('id')==customer:return
|
|
305
|
+
if not self.owned(owner,user_id):raise unavailable()
|
|
306
|
+
sessions=self.listing('/checkout/sessions',{'customer':customer})
|
|
307
|
+
if any(not self.owned(s,user_id) or s.get('customer')!=customer for s in sessions):raise unavailable()
|
|
308
|
+
# Close hosted payment pages before taking the subscription snapshot.
|
|
309
|
+
# A page completing concurrently either appears in the later read or
|
|
310
|
+
# makes expiration fail, leaving the durable job pending for another pass.
|
|
311
|
+
for session in sessions:
|
|
312
|
+
if session.get('status')=='open':
|
|
313
|
+
self.api('POST','/checkout/sessions/'+stripe_id(session.get('id'),'cs_')+'/expire',{},'socialcli-delete-session-'+session['id'])
|
|
314
|
+
subscriptions=self.listing('/subscriptions',{'customer':customer,'status':'all'})
|
|
315
|
+
if any(not self.owned(s,user_id) or s.get('customer')!=customer for s in subscriptions):raise unavailable()
|
|
316
|
+
subscription_ids={s['id'] for s in subscriptions}
|
|
317
|
+
for session in sessions:
|
|
318
|
+
if session.get('mode')=='subscription' and session.get('status')=='complete' and session.get('subscription') not in subscription_ids:
|
|
319
|
+
raise unavailable()
|
|
320
|
+
for sub in subscriptions:
|
|
321
|
+
if sub.get('status') not in {'canceled','incomplete_expired'}:
|
|
322
|
+
self.api('DELETE','/subscriptions/'+stripe_id(sub.get('id'),'sub_'))
|
|
323
|
+
# Delete the dedicated, owner-verified Stripe customer as a final fence:
|
|
324
|
+
# Stripe prevents subsequent subscriptions and cancels any concurrent one.
|
|
325
|
+
# Historical invoice records remain with Stripe. A repeat GET reports deleted.
|
|
326
|
+
deleted=self.api('DELETE','/customers/'+stripe_id(customer,'cus_'))
|
|
327
|
+
if deleted.get('id')!=customer or deleted.get('deleted') is not True:raise unavailable()
|