def post(self, request, obj_name=None, user_id=None, **kwargs): if obj_name == 'preapproval' and 'checkout_id' in request.POST: # as described in https://www.wepay.com/developer/reference/ipn # checkouts created automatically will receive IPNs to preapproval's # callback_uri obj_name = 'checkout' model = get_wepay_model(obj_name) obj_id_name = "%s_id" % obj_name user = None try: obj_id = request.POST[obj_id_name] except KeyError: return HttpResponse( "Missing object_id in POST: %s" % obj_id_name, status=501) try: obj = model.objects.get(pk=obj_id) except model.DoesNotExist: if obj_name == 'user': raise Http404("User object with user_id: '%s' not found." % obj_id) obj = model(pk=obj_id) if not user_id is None: user = get_object_or_404(get_wepay_model('user'), pk=user_id) obj.access_token = user.access_token try: api_call = getattr(obj, "api_%s" % obj_name) api_call() except WePayError, e: if e.code == 1011 and not user is None: # acess_token has been revoked user.access_token = None user.save() else: return HttpResponse( "WePay error on update. %s" % e, status=500)
def handle(self, *args, **kwargs): obj_name = kwargs.get('obj_name') ids = kwargs.get('ids', '') model = get_wepay_model(obj_name) if model is None: print "Unrecognized object name: %s " % obj_name exit() pks = [int(x) for x in ids.split(',') if x] if hasattr(model.objects, 'accessible'): objects = model.objects.accessible() else: objects = model.objects.all() if pks: objects.filter(pk__in=pks) for obj in objects: method = getattr(obj, "api_%s" % obj_name) try: method() print "Updated object with id: %s" % obj.pk except WePayError, e: if e.code == 1011: if obj_name == 'user': obj.access_token = None obj.save() print "access token revoked for the object with id: %s" % obj.pk else: print "problem updating object with id: %s" % obj.pk print e
def retrieve_objects(self, obj_name, parent, parent_name, **kwargs): start = 0 limit = 5 api_find = getattr(parent, "api_%s_find" % obj_name) responses = api_find( start=start, limit=limit, timeout=3*60, **kwargs)[1] model = get_wepay_model(obj_name) objects = [] while responses: for response in responses: if model.objects.filter(pk=response[model._meta.pk.attname]).exists(): action = "Updated" else: action = "Retrieved" try: obj = model.objects.create_from_response( True, response, **{parent_name: parent}) except BaseException: print(response) # useful for debugging raise objects.append(obj) print("%s: %s" % (action ,obj)) start+= limit try: responses = api_find( start=start, limit=limit, timeout=3*60, **kwargs)[1] except (WePayHTTPError, WePayConnectionError) as e: print("Error: %s" % e) self.retrieve_errors.append({ 'call': "api_%s_find" % obj_name, 'params': "start=%s, limit=%s" % (start, limit), 'error': e }) return objects
def handle(self, objects='', **kwargs): update_errors = [] if objects: objects = [o.strip() for o in objects.split(',') if o] unknown_objects = set(objects) - set(self.supported_objects) assert not unknown_objects, "Unknown objects: %s" % ','.join(unknown_objects) else: objects = self.supported_objects models = [] for obj_name in objects: try: models.append((obj_name, get_wepay_model(obj_name))) except LookupError: pass for obj_name, model in models: obj = None for obj in model.objects.accessible(): try: api_modify = getattr(obj, "api_%s_modify" % obj_name) print("Modified: %s" % api_modify(callback_uri=obj.get_callback_uri())[0]) except (WePayHTTPError, WePayConnectionError) as e: print("Error: %s" % e) update_errors.append({ 'call': "api_%s_modify" % obj_name, 'object': obj, 'params': "callback_uri=%s" % obj.get_callback_uri(), 'error': e }) if update_errors: print("THERE WERE ERRORS:") print(update_errors)
def wepay(request): app = get_wepay_model('app').objects.get_current() base_url = "https://wepay.com" if app.production else "https://stage.wepay.com" return { 'WEPAY_APP': app, 'WEPAY_LOGIN_URL': "%s/login" % base_url, 'WEPAY_TOS_URL': "%s/legal/terms-of-service" % base_url, 'WEPAY_PRIVACY_URL': "%s/legal/privacy-policy" % base_url }
def get_account(self, account_id): account = get_object_or_404(get_wepay_model('account'), account_id=account_id) if not self.has_permission(account): raise PermissionDenied if self.refresh: # best attempt to update all of account's info batch_id = 'account-%s-refresh' % account_id redirect_uri = self.get_redirect_uri() account.api_account(batch_mode=True, batch_id=batch_id, commit=False, batch_reference_id='%s-info' % batch_id) account.api_account_get_update_uri(batch_mode=True, batch_id=batch_id, batch_reference_id='%s-uri' % batch_id, redirect_uri=redirect_uri) account.api_account_get_reserve_details(batch_mode=True, batch_id=batch_id, batch_reference_id='%s-reserve' % batch_id) app = get_wepay_model('app').objects.get_current() try: app.api_batch_create(batch_id, timeout=20) except WePayHTTPError: pass return account
def post(self, request, user_id=None, **kwargs): model = None obj_id = None for obj_name in self.supported_objects: obj_id_name = "%s_id" % obj_name if obj_id_name in request.POST: obj_id = request.POST[obj_id_name] model = get_wepay_model(obj_name) break if model is None: if obj_id is None: return HttpResponse( "Missing object_id in POST.", status=400) return HttpResponse( "Object '%s' is not supported by this application." % obj_name, status=501) user = None try: obj = model.objects.get(pk=obj_id) except model.DoesNotExist: if obj_name == 'user': # ipn received for user that wasn't created locally, cannot recreate # due to lack of info, which is not the case for the rest of the objects raise Http404("User object with user_id: '%s' not found." % obj_id) obj = model(pk=obj_id) if user_id is not None: # retrieve access_token from the user object, so we can perform a lookup call user = get_object_or_404(get_wepay_model('user'), pk=user_id) obj.access_token = user.access_token try: api_call = getattr(obj, "api_%s" % obj_name) api_call() except WePayHTTPError as exc: if exc.error_code == 1011 and user is not None: # acess_token has been revoked, reflect it in db user.access_token = None user.save() else: return HttpResponse( "WePay error on update. %s" % exc, status=exc.status_code) ipn_processed.send(sender=model, instance=obj) return HttpResponse("Successfull %s update." % obj_name)
class Meta: model = get_wepay_model('app') fields = ( 'client_id', 'client_secret', 'access_token', 'account', 'user', 'name', 'primary_color', 'secondary_color', 'background_color', 'button_color', #'gaq_domains' )
def clean(self): # update/create associated account account_id = self.data.get('account', None) if account_id: Account = get_wepay_model('account') try: account_id = int(account_id) except ValueError, exc: raise forms.ValidationError(str(exc)) try: try: account = Account.objects.get(pk=account_id) account.api_account() except Account.DoesNotExist: account, response = self.instance.api.account( account_id=account_id, callback=curry(Account.objects.create_from_response, None)) self.cleaned_data['account'] = account except WePayError, exc: raise forms.ValidationError(str(exc))
def handle(self, objects='', **kwargs): update_errors = [] if objects: objects = [o.strip() for o in objects.split(',') if o] unknown_objects = set(objects) - set(self.supported_objects) assert not unknown_objects, "Unknown objects: %s" % ','.join( unknown_objects) else: objects = self.supported_objects models = [] for obj_name in objects: try: models.append((obj_name, get_wepay_model(obj_name))) except LookupError: pass for obj_name, model in models: obj = None for obj in model.objects.accessible(): try: api_modify = getattr(obj, "api_%s_modify" % obj_name) print("Modified: %s" % api_modify(callback_uri=obj.get_callback_uri())[0]) except (WePayHTTPError, WePayConnectionError) as e: print("Error: %s" % e) update_errors.append({ 'call': "api_%s_modify" % obj_name, 'object': obj, 'params': "callback_uri=%s" % obj.get_callback_uri(), 'error': e }) if update_errors: print("THERE WERE ERRORS:") print(update_errors)
import copy from django.conf import settings from django.template.base import Node, token_kwargs, TemplateSyntaxError from django.template.defaulttags import register from django.utils import six from djwepay.api import get_wepay_model, DEFAULT_SCOPE APP = get_wepay_model('app').objects.get_current() #TODO: remove jquery dependency from the tag. class AuthorizeNode(Node): template = """ <script src="%(browser_js)s" type="text/javascript"></script> <script type="text/javascript"> function oauth2_authorize(){ if(document.documentMode && document.documentMode >= 10){ return false; // disable for gte IE10 } WePay.set_endpoint("%(endpoint)s"); var button = document.getElementById("%(elem_id)s"); $(button).click(function(event){event.preventDefault; return false;}); WePay.OAuth2.button_init(button, { "client_id": "%(client_id)d", "scope": %(scope)r, "user_name": "%(user_name)s", "user_email": "%(user_email)s", "redirect_uri": "%(redirect_uri)s",
import copy from django.template.base import Node, token_kwargs, TemplateSyntaxError from django.template.defaulttags import register from django.utils import six from djwepay.api import get_wepay_model, DEFAULT_SCOPE APP = get_wepay_model('app').objects.get_current() class AuthorizeNode(Node): template = '<script src="%(browser_js)s" ' \ 'type="text/javascript"></script><script type="text/javascript">' \ 'function oauth2_authorize(){'\ 'WePay.set_endpoint("%(endpoint)s"); ' \ 'WePay.OAuth2.button_init(document.getElementById("%(elem_id)s"), {' \ '"client_id": "%(client_id)d",' \ '"scope": %(scope)r,' \ '"user_name": "%(user_name)s",' \ '"user_email": "%(user_email)s",' \ '"redirect_uri": "%(redirect_uri)s",' \ '"top": %(top)d,' \ '"left": %(left)d,' \ '"state": "%(state)s",' \ '"callback": %(callback)s });}' \ 'if(window.addEventListener)' \ 'window.addEventListener("load", oauth2_authorize);' \ 'else window.attachEvent("onload", oauth2_authorize);' \ '</script>' \ default_params = {
TEST_CC = { 'user_name': "Test Dude", 'cc_number': "4003830171874018", 'expiration_month': "02", 'expiration_year': "17", 'cvv': "123", } TEST_ADDRESS = { 'address1': "123 Main Stret", 'city': "Albuquerque", 'state': "NM", 'zip': "87108", 'country': "US" } App = get_wepay_model('app') User = get_wepay_model('user') Account = get_wepay_model('account') Checkout = get_wepay_model('checkout') Preapproval = get_wepay_model('preapproval') Withdrawal = get_wepay_model('withdrawal') CreditCard = get_wepay_model('credit_card') @override_settings(WEPAY_APP_ID=TEST_APP_ID) class WePayTestCase(TestCase): #fixtures = ['djwepay_testdata.xml'] @staticmethod def browser_create(): browser = mechanize.Browser()
def handle(self, *args, **kwargs): production = kwargs.get('production', False) client_id = kwargs.get('client_id') client_secret = kwargs.get('client_secret') access_token = kwargs.get('access_token') account_id = kwargs.get('account_id') try: while not client_id: client_id = input("client_id: ") try: client_id = int(client_id) except (TypeError, ValueError): self.stderr.write( "\n'client_id' has to be an integer not: %s" % client_id) client_id = None while not client_secret: client_secret = input("client_secret: ") if not client_secret: self.stderr.write("\n'client_secret' is required.") while not access_token: access_token = input("access_token: ") if not access_token: self.stderr.write("\n'access_token' is required.") while not account_id: try: account_id = int(input("account_id: ")) except (TypeError, ValueError): self.stderr.write( "\n'account_id' has to be an integer not: %s" % account_id) account_id = None except KeyboardInterrupt: self.stderr.write("\nOperation cancelled.") sys.exit(1) if (production and access_token.startswith("STAGE_")) or \ (not production and access_token.startswith("PRODUCTION_")): self.stderr.write("\nThere is a conflict: access_token doesn't correspond with " "environment. production=%s and access_token='%s...' " "Flag --production controls the environment."% (production, access_token[:14])) sys.exit(1) WePayBackend = from_string_import(API_BACKEND) api = WePayBackend(production=production, access_token=access_token) App = get_wepay_model('app') app = App(client_id=client_id, client_secret=client_secret) app.access_token = access_token app.api = api app.api_app() self.stdout.write( "Retrieved app with client_id: %s and status: %s" % (app.pk, app.status)) User = get_wepay_model('user') user = User(access_token=access_token) user.api = api user.app = app user.api_user() self.stdout.write("Retrieved user: %s" % user) Account = get_wepay_model('account') account = Account(account_id=int(account_id)) account.user = user account.api = api account.api_account() self.stdout.write("Retrieved account: %s" % account) app.user = user app.account = account app.save() self.stdout.write( "Successfully added new WePay App. If you choose to use it " "please set 'WEPAY_APP_ID=%s' in the settings.py module." % app.pk)
def handle(self, objects='', users='', **kwargs): self.retrieve_errors = [] supported_objects = [] for obj_name in self.supported_objects: try: get_wepay_model(obj_name) supported_objects.append(obj_name) except LookupError: pass if objects: objects = [o.strip() for o in objects.split(',') if o] unsupported_objects = set(objects) - set(supported_objects) assert not unsupported_objects, \ "Unsupported objects: %s" % ','.join(unsupported_objects) else: objects = supported_objects filters = {} if users: user_pks = [pk.strip() for pk in users.split() if pk.strip()] filters = {'user_id__in': user_pks} users = get_wepay_model('user').objects.exclude(access_token=None) if filters: user = users.filter(**filters) for user in users: if 'account' in objects: responses = user.api_account_find()[1] accounts = [] Account = get_wepay_model('account') for response in responses: if Account.objects.filter(pk=response['account_id']).exists(): action = "Updated" else: action = "Retrieved" account = Account.objects.create_from_response( True, response, user=user) print("%s: %s" % (action, account)) if account.state != 'deleted': accounts.append(account) else: accounts = user.accounts.exclude(state='deleted') if 'preapproval' in objects: for account in accounts: self.retrieve_objects('preapproval', account, 'account') if 'checkout' in objects: for account in accounts: self.retrieve_objects('checkout', account, 'account') if 'withdrawal' in objects: for account in accounts: self.retrieve_objects('withdrawal', account, 'account') if 'subscription_plan' in objects: for account in accounts: subscription_plans = self.retrieve_objects( 'subscription_plan', account, 'account') if 'subscription' in objects: for subscription_plan in subscription_plans: self.retrieve_objects( 'subscription', subscription_plan, 'subscription_plan') if 'subscription_charge' in objects: for subscription_plan in subscription_plans: self.retrieve_objects( 'subscription_charge', subscription_plan, 'subscription_plan') app = get_wepay_model('app').objects.get_current() #if 'preapproval' in objects: # self.retrieve_objects('preapproval', app, 'app', account_id=0) if 'credit_card' in objects: self.retrieve_objects('credit_card', app, 'app') if self.retrieve_errors: print("THERE WERE ERRORS:") print(self.retrieve_errors)
def app(self): return get_wepay_model('app').objects.get_current()
__all__ = ['AppAdmin', 'UserAdmin', 'AccountAdmin'] class AppAdmin(admin.ModelAdmin): list_display = ('client_id', 'status', 'production') list_filter = ('status', 'production', 'date_created') readonly_fields = ( 'state', 'status', 'date_created', 'date_modified', 'api_version' ) raw_id_fields = ('account',) search_fields = ('status', 'theme_object', 'gaq_domain') form = AppForm if not is_abstract('app'): admin.site.register(get_wepay_model('app'), AppAdmin) class UserAdmin(admin.ModelAdmin): list_display = ('user_id', 'user_name', 'email', 'state') list_filter = ('state', 'date_created') readonly_fields = ( 'user_id', 'user_name', 'first_name', 'last_name', 'email', 'state', 'access_token', 'expires_in', 'date_created', 'date_modified' ) search_fields = ('user_id', 'user_name', 'email', 'state') if not is_abstract('user'): admin.site.register(get_wepay_model('user'), UserAdmin) class AccountAdmin(admin.ModelAdmin): list_display = (
class Meta: model = get_wepay_model('app')
def handle(self, *args, **kwargs): production = kwargs.get('production', False) client_id = kwargs.get('client_id') client_secret = kwargs.get('client_secret') access_token = kwargs.get('access_token') account_id = kwargs.get('account_id') try: while not client_id: client_id = input("client_id: ") try: client_id = int(client_id) except (TypeError, ValueError): self.stderr.write( "\n'client_id' has to be an integer not: %s" % client_id) client_id = None while not client_secret: client_secret = input("client_secret: ") if not client_secret: self.stderr.write("\n'client_secret' is required.") while not access_token: access_token = input("access_token: ") if not access_token: self.stderr.write("\n'access_token' is required.") while not account_id: try: account_id = int(input("account_id: ")) except (TypeError, ValueError): self.stderr.write( "\n'account_id' has to be an integer not: %s" % account_id) account_id = None except KeyboardInterrupt: self.stderr.write("\nOperation cancelled.") sys.exit(1) if (production and access_token.startswith("STAGE_")) or \ (not production and access_token.startswith("PRODUCTION_")): self.stderr.write("\nThere is a conflict: access_token doesn't correspond with " "environment. production=%s and access_token='%s...' " "Flag --production controls the environment."% (production, access_token[:14])) sys.exit(1) WePayBackend = from_string_import(API_BACKEND) api = WePayBackend(production=production, access_token=access_token) App = get_wepay_model('app') app = App(client_id=client_id, client_secret=client_secret, production=production) app.access_token = access_token app.api = api app.api_app() self.stdout.write( "Retrieved app with client_id: %s and status: %s" % (app.pk, app.status)) User = get_wepay_model('user') user = User(access_token=access_token) user.api = api user.app = app user.api_user() self.stdout.write("Retrieved user: %s" % user) Account = get_wepay_model('account') account = Account(account_id=int(account_id)) account.user = user account.api = api account.api_account() self.stdout.write("Retrieved account: %s" % account) app.user = user app.account = account app.save() self.stdout.write( "Successfully added new WePay App. If you choose to use it " "please set 'WEPAY_APP_ID=%s' in the settings.py module." % app.pk)
class Meta: model = get_wepay_model('account') fields = ('name', 'description')