Created
October 31, 2011 19:19
-
-
Save screeley/1328564 to your computer and use it in GitHub Desktop.
A simple script to update Chargify subscriptions to the most recent version.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
A simple script to update Chargify subscriptions to the most recent version. | |
""" | |
import base64 | |
import requests | |
import json | |
API_KEY = 'Chargify API Key' | |
HOST = 'https://<Chargify Host Name>.chargify.com' | |
headers = { | |
"Authorization": "Basic %s" % base64.encodestring('%s:%s' % (API_KEY, 'x'))[:-1], | |
"User-Agent": "Migrate-to-Latest-Version", | |
"Content-Type": "application/json" | |
} | |
def update_plan(id, handle): | |
print 'Updating %s to %s' % (id, handle) | |
d = { | |
"subscription":{ | |
'product_handle' : handle | |
} | |
} | |
data = json.dumps(d) | |
url = '%s/subscriptions/%s.json' % (HOST, id) | |
r = requests.put(url, data=data, headers=headers) | |
if r.error: | |
print 'Error: %s ID: %s HANDLE: %s' % (r.error, id, handle) | |
def update(pages=10): | |
for p in range(1, pages+1): | |
r = requests.get('%s/subscriptions.json?per_page=200&page=%s' % (HOST, p), headers=headers) | |
data = json.loads(r.content) | |
# No more subs: | |
if not data: | |
break | |
# We only update the plans that were not canceled. | |
subs = [s['subscription'] for s in data if s['subscription']['canceled_at'] is None] | |
for s in subs: | |
handle = s['product']['handle'] | |
id = s['id'] | |
#update to testing account. | |
update_plan(id, 'testing') | |
#update back to the right plan | |
update_plan(id, handle) | |
#Spot checking and testing. | |
def update_one(id): | |
sub = get_id(id) | |
handle = sub['product']['handle'] | |
#update to testing account. | |
update_plan(id, 'testing') | |
#update back to the right plan | |
update_plan(id, handle) | |
#Utils that help | |
def get_id(id): | |
url = '%s/subscriptions/%s.json' % (HOST, id) | |
r = requests.get(url, headers=headers) | |
return json.loads(r.content)['subscription'] | |
def get_all(pages=10): | |
subs = [] | |
for p in range(1, pages+1): | |
r = requests.get('%s/subscriptions.json?per_page=200&page=%s' % (HOST, p), headers=headers) | |
data = json.loads(r.content) | |
# No more subs: | |
if not data: | |
break | |
subs.extend([s['subscription'] for s in data]) | |
return subs | |
if __name__ == '__main__': | |
update() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Managed to stumble across this exactly when I needed it. Thanks!