Exemplo n.º 1
0
 def create(self, validated_data, store):
     shopify.ShopifyResource.clear_session()
     with shopify.Session.temp(store.url, store.token):
         test_charge = cfg.DEBUG
         plan = validated_data['plan']
         if len(plan.split(" ")) == 1:
             plan = plan + " Second"
         # check if the store is from our DEVELOPMENT_STORES
         if (store.url in cfg.DEVELOPMENT_STORES):
             # fake billing
             test_charge = True
         if plan.split(" ")[1] == "Free":
             store.activate_plan(plan)
             return store.free_trial_left()
         else:
             recur_charge = shopify.RecurringApplicationCharge({
                 "name":
                 plan,
                 "price":
                 RecurringCharge.billing_amount(plan),
                 "return_url":
                 cfg.SHOPIFY_CONFIG['CHARGES_RETURN_URL'],
                 "trial_days":
                 0,
                 "test":
                 test_charge
             })
             recur_charge.save()
             RecurringCharge.objects.create(
                 shopify_id=recur_charge.attributes['id'],
                 status=recur_charge.attributes['status'],
                 plan=plan,
                 store=store)
             return (recur_charge.attributes['confirmation_url'])
 def test_activate_charge(self):
     # Just check that calling activate doesn't raise an exception.
     self.fake("recurring_application_charges/35463/activate",
               method='POST',
               headers={
                   'Content-length': '0',
                   'Content-type': 'application/json'
               },
               body=" ")
     charge = shopify.RecurringApplicationCharge({'id': 35463})
     charge.activate()
 def test_activate_charge(self):
     # Just check that calling activate doesn't raise an exception.
     self.fake(
         "recurring_application_charges/35463/activate",
         method="POST",
         headers={
             "Content-length": "0",
             "Content-type": "application/json"
         },
         body=" ",
     )
     charge = shopify.RecurringApplicationCharge({"id": 35463})
     charge.activate()
Exemplo n.º 4
0
 def get(self, request, *args, **kwargs):
     activate_shopify_session(request)
     shop_obj = Shop.objects.get(name=request.session.get('shop_name'))
     charge_id = request.GET.get('charge_id')
     payment_data = shopify.RecurringApplicationCharge.get(charge_id)
     status = payment_data['status']
     if status == 'accepted':
         charge = shopify.RecurringApplicationCharge(payment_data)
         charge.activate()
         plan_pricing = PlanPricing.objects.get(price=payment_data['price'])
         shop_obj.plan = plan_pricing.plan.id
         shop_obj.payment_token = charge.id
         shop_obj.payment_date = datetime.today()
         expire_date = datetime.today() + timedelta(days=10)
         shop_obj.expire_date = expire_date
         shop_obj.save()
     context = {}
     context["shop"] = shop_obj.name
     context["api_key"] = settings.SHOPIFY_API_KEY
     return render(request, self.template_name, context)
Exemplo n.º 5
0
def finalize(request):
    print '==> finalize()'
    shop_url = request.GET['shop']

    # This block checks if it is the second redirect.
    # Basically, EASDK install process automatically redirects to finalize() when it is done, so it effectively runs this function twice
    # which on the second run triggers the Exception bellow as the session expires.
    # To avoid this, we will check again if the store exists in our DB if it does, don't run this code just redirect to the dashboard

    try:
        print 'trying to no re-install'
        print 'shop_url %s' % (shop_url)
        ShopDeatzInst = ShopDeatz.objects.get(shop_url=str(shop_url))
        # redirect to dashboard
        return dashboard.views.index(request)

    except ObjectDoesNotExist:
        print 'Not found installing'
        # Then continue to installation code
        pass

    # Create a Shopify Session for Merchant Shop using shop_url and access_token (0auth token)
    try:
        shopify_session = shopify.Session(shop_url)

        # This is where the shopify 0auth token is captured
        # request_token uses the 'hmac' arguement passed along in the GET to request a 0auth token
        auth_token = shopify_session.request_token(request.GET)

        request.session['shopify'] = {
            "shop_url": shop_url,
            "access_token": auth_token,
        }
    except Exception:
        messages.error(request, "Could not log in to Shopify store.")
        # In case the authentication did not work, send the merchant back to the manual Login Form
        return redirect(reverse(login))

    # Activate your shopify sessions so ou can make API calls
    shopify.ShopifyResource.activate_session(shopify_session)

    # Creates an object that contains all the shop info eqvalent to GET endpoint /admin/shop.json
    shop_info = shopify.Shop.current()

    # Create an instance of ShopDeatz Model and save shop_url and access_token for future use to when issuing commands on behalf of the store.
    ShopDeatzInst = ShopDeatz()
    ShopDeatzInst.shop_url = shop_url
    ShopDeatzInst.auth_token = auth_token
    ShopDeatzInst.download_key = ''.join(
        random.choice(string.ascii_uppercase + string.digits)
        for _ in range(139))
    ShopDeatzInst.shop_name = shop_info.name
    ShopDeatzInst.save()

    messages.info(request, "Logged in to shopify store.")

    # redirect(_return_addres(request)) will send you back to the webapps root '/' url where the login
    response = redirect(_return_address(request))

    request.session.pop('return_to', None)

    # Now render the merchants embeddedi post install page (the finished.html template with <head>Emmbeded APP SDK JS</head>)
    # The template itself contains a JS redirect so it will render the template redirect to Shopify dashboard, and display rendered template
    # encapsulated in an iframe in ther shopify backend

    # You must pass 2 arguements to the EASDK JS, your app's api_key and the FULL path to the store that is installing the app.
    full_shop_url = 'https://' + shop_url
    context = {
        'SHOPIFY_API_KEY': settings.SHOPIFY_API_KEY,
        'shop_url': full_shop_url
    }

    print '\n'
    print 'STARTING APPLICATION CHARGE PROCESS'

    ##################################################
    # Create the application charge
    ##################################################
    # Create recurring charge
    # if the user accepts the charge,
    # if user declines the charge, his shop will be removed from the DB
    # He will then be redirected by the createRecurringCharge() function to the redirection url a.k.a dashboard home (cdn1.gdprinsider.ovh)
    # At this point shop behaviour will be normal, if the shop still exists in the DB (accepted the charge) then they will have access to dash
    # if the shop has been removed from DB (declined the charge) then they will be redirected to the shopify install webpage

    charge = shopify.RecurringApplicationCharge()
    charge.name = settings.APP_NAME
    charge.price = settings.APP_PRICE
    charge.test = settings.APP_TESTFLAG
    charge.return_url = settings.APP_RETURNURL
    # Check if shop has already installed app preivously in Install Tracker, if it has then do not offer Trial period
    try:
        ShopInstallTracker = InstallTracker.objects.get(shop_url=shop_url)
        pass
    # Otherwise offer 2 days of trial
    except ObjectDoesNotExist:
        charge.trial_days = settings.APP_TRIALDAYS

    charge.save()

    print 'charge_id'
    print charge.__dict__
    ShopDeatzInst.charge_id = charge.id
    ShopDeatzInst.save()

    # redirect the user to the confirmation_url given in the charge.save() response where they will be prompted to accept or decline the charge
    # Once the user accepts / declines he will then be automatically redirected to charge.return_url (https://cdn1.gdprinsider.ovh/activatecharge)
    # where we have a view (activateRecurringCharge) listening for charges to activate
    return redirect(charge.confirmation_url)