Stripe and Pythonanywhere

Show me da money!
Getting money is great, isn't it?

Seeing the cash flowing in is just awesome.

but...

If it ain't got no way to get in, that just kinda sucks.

Wouldn't it be awesome if thee was a way to get a free payment processor that only took money after you were paid, rather than needing any up front?

That's what we're looking for here...

What we want:


  • Python anywhere to serve Stripe CC entry 
  • then take to thank you page
    • where processes
    • and then says thank you.


To do this:


  • Need python anywhere account
  • Need stripe account


Ignore this stuff all the way until pink again

Python anywhere
web tab - clear all web apps, files tab empty out mysite folder of everything
https://stackoverflow.com/questions/31504190/django-pinax-couldnt-extract-file
https://www.pythonanywhere.com/forums/topic/2718/#id_post_15582

Says follow instructions here...
https://github.com/pinax/pinax-project-account
It says can be done!
Lets try it...

add new web app
robstestinglab.pythonanywhere.com
Django, python 3.6, mysite

go to https://robstestinglab.pythonanywhere.com/ gives...
----------------------
It worked!
Congratulations on your first Django-powered page.

Next, start your first app by running python manage.py startapp [app_label].
You're seeing this message because you have DEBUG = True in your Django settings file and you haven't configured any URLs. Get to work!
----------------------
NOTICE! HAS HTTPS! YAY



xxx/mysite/manage.py
-------------------------------
#!/usr/bin/env python3.6

import os

import sys


if __name__ == "__main__":

    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")

    try:

        from django.core.management import execute_from_command_line

    except ImportError:

        # The above import may fail for some other reason. Ensure that the

        # issue is really that Django is missing to avoid masking other

        # exceptions on Python 2.

        try:

            import django

        except ImportError:

            raise ImportError(

                "Couldn't import Django. Are you sure it's installed and "

                "available on your PYTHONPATH environment variable? Did you "

                "forget to activate a virtual environment?"

            )

        raise

    execute_from_command_line(sys.argv)
-------------------------------------


Went to https://github.com/pinax/pinax-project-account
Redirected me to...
https://github.com/pinax/pinax-starter-projects/tree/account

https://stackoverflow.com/questions/31504190/django-pinax-couldnt-extract-file
django-admin.py startproject --template=https://github.com/pinax/pinax-project-account/zipball/master


Actually this looks good
http://blog.pinaxproject.com/2016/01/27/recap-january-pinax-hangout/
pinax does stripe for django


Empty out the apps on web tab and delete the Myapp folder on the files tab
go to consoles tab, start a new console: other: bash
type in:
--------------------------
mkvirtualenv snot
pip install django
wget https://github.com/pinax/pinax-project-account/zipball/master
mv master master.zip
django-admin.py startproject --template=./master.zip
----------------------------

In brief, the differences are:

Our default versions of Django are a little out of date. In order to use the nice, shiny new Django 1.7, you'll need to use a virtualenv.

manage.py runserver and localhost:8000 won't work on PythonAnywhere, because our console servers aren't accessible from the outside world.

Instead, go to the Web tab and start a new web app using manual configuration. Click through to the link to edit your wsgi file and uncomment the section for Django. From then on, your Django site will be live at your-username.pythonanywhere.com.

You'll need to hit the Reload button to reload your web app, whenever you want to see the effects of code changes on your site.

That's ultra-brief overview. For detailed instructions, check out the Following the Django Tutorial on PythonAnywhere wiki page.

To close this helper, just click the x to the top right.

 Close this tutorial
---------------------------------
https://pinax-stripe.readthedocs.io/en/latest/user-guide/getting-started/
http://blog.pinaxproject.com/2016/01/27/recap-january-pinax-hangout/
ttps://www.pythonanywhere.com/user/robstestinglab02/consoles/5651876/


mkvirtualenv snot
pip install django
pip install pinax-cli
cd snot
pip install -r requirements.txt
python manage.py migrate
python manage.py loaddata sites

go to settings.py, lines 143 and 144 and put in the test keys

Getting the web page URLs to work...


no. Just go here.
https://docs.djangoproject.com/en/1.11/intro/tutorial01/

  • install django

cd to outer mysite by going cd then dir, working way to /home/robstestinglab02/mysite

  • python manage.py runserver

 this verifys working. Ignore about unapllied migrations

  • python manage.py runserver 8080

 changes port while on work computer cos 8000 is used by other stuff
To create app named fred
ensure in outer mysite folder

  • python manage.py startapp fred

fred is folder. Project is stuff for singel website, can have multiple apps in it.
open file fred/views.py and put this in

from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the polls index.")
------------------
So now got "webpage", need to point to it with URL
In fred, create file urls.py - do thru Pythonanywhere GUI
----------------
from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
]
--------------------------
In mysite, edit file urls.py so
--------------------------
from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
    url(r'^fred/', include('fred.urls')),
    url(r'^admin/', admin.site.urls),
]
---------------------------
go to pythonanywhere dashboard web tab, reload

Now go to https://robstestinglab02.pythonanywhere.com/fred/
Yay! It works!
It says
Hello, world. You're at the polls index.
ctrl U, source code is the same.

Note: it seems it can work in either https OR http.
I think this still means it can work as stripe, later.

https://stripe.com/docs/charges


GoDjango Tutorial

https://godjango.com/57-starting-with-stripejs/

OK, starting all over again.
Gonna use the public key and secret key from https://stripe.com/docs/checkout/tutorial and https://stripe.com/docs/charges which are...
pk_test_6pRNASCoBOKtIshFeQd4XMUh
and
sk_test_BQokikJOvBiI2HlWgH4olfQ2

Go to Terminal

Pythonanywhere, console tab, bash

  • pip install stripe

says requirements already satisfied.

  • ls -lha

Didn't need to do tha, but lists contents of robtestinglab02 folder (not sure what -lha does)
So going to have folders

  • store
    • forms.py
    • views.py
    • urls.py
    • subscribe.html
    • thank_you.html

not sure about the thank you bit yet.
Yup. Think it does.
But something about settings.STRIPE_PUBLIC_KEY. Lets look at settings.


Getting Websites with URLS working...

A good but over-detailed tutorial...
https://docs.djangoproject.com/en/1.11/intro/tutorial01/

Setting up project

Get pythonanywhere account
Tab:Web add a new app, django, mysite
Tab: Console, other:bash
-starts terminal
cd to outer mysite by going cd then dir, working way to /home/robstestinglab02/mysite

  • python manage.py runserver

 this verifys working. Ignore about unapllied migrations

  • python manage.py runserver 8080

changes port while on work computer cos 8000 is used by other stuff
To create app named fred
ensure in outer mysite folder

  • python manage.py startapp fred

fred is folder. Project is stuff for singel website, can have multiple apps in it.

Making web pages

open file fred/views.py and put this in

from django.http import HttpResponse

def index(request):
    output="Hello, world, you're at Fred Index"
    return HttpResponse(output)

def burp(request):
    output="Hello, world, you're at Fred Burp"
    return HttpResponse(output)

def socks(request):
    output="Hello, world, you're at Fred Socks"
    return HttpResponse(output)


Getting URLs to point to webpages

In mysite, edit file urls.py so

from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
    url(r'^fred/', include('fred.urls')),
    url(r'^admin/', admin.site.urls),
]

So now got "webpage", need to point to it with URL
In fred, create file urls.py - do thru Pythonanywhere GUI

from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'burp/$', views.burp, name='burp'),
    url(r'socks/$', views.socks, name='socks'),
]

Testing

go to pythonanywhere dashboard web tab, reload

Now go to https://robstestinglab02.pythonanywhere.com/fred/
Now go to https://robstestinglab02.pythonanywhere.com/fred/burp
Now go to https://robstestinglab02.pythonanywhere.com/fred/socks
Yay! It works!

Stripe Checkout

Go get checkout page form from https://stripe.com/docs/checkout/tutorial

ie
<form action="/your-server-side-code" method="POST">
  <script
    src="https://checkout.stripe.com/checkout.js" class="stripe-button"
    data-key="pk_test_6pRNASCoBOKtIshFeQd4XMUh"
    data-amount="999"
    data-name="Stripe.com"
    data-description="Widget"
    data-image="https://stripe.com/img/documentation/checkout/marketplace.png"
    data-locale="auto"
    data-zip-code="true">
  </script>
</form>

Note - this just straight from page, these test codes are NOT correct.
https://stripe.com/docs/checkout/tutorial
https://ultimatedjango.com/learn-django/lessons/create-stripe-processing-code/

Trying out Update fred/views.py
just pasted it in and modified outside single quotes to double quotes
notice the form action address has fred in it,
Also added {% csrf_token %}
and changed request.form to request.POST


from django.http import HttpResponse
from django.views.generic import TemplateView
from django.shortcuts import render
import stripe

def index(request):
    output="Hello, world, you're at Fred Index"
    return HttpResponse(output)

def burp(request):
    output="""
this bit is from the views bit
"""
    return render(request, 'burp.html')

def socks(request):
    stripe.api_key = "sk_test_BQokikJOvBiI2HlWgH4olfQ2"
    token = request.POST['stripeToken']
    charge = stripe.Charge.create(
        amount=1000,
        currency="usd",
        description="Example charge",
        source=token,
    )
    output={"""
<h2>This is from the views.py</h2>
"""}
    return render(request, 'socks.html')


Note - will need to change the pk_test_ later cos that one just straight from website.

YAY, this works, lets enter data and then sends to socks.

But now says CSRF verification forbidden.

  • Look at https://docs.djangoproject.com/en/dev/ref/csrf/
  • so put {% csrf_token %} after the post
  • also settings in mysite/mysite/settings.py still has the middleware fine so don't change that.
  • Must have render of view, so lets fire that one off...
  • go to https://docs.djangoproject.com/en/1.11/intro/tutorial03/
  • ctrl-f and find first "render"
  • says create a fred/templates/socks.html
  • and had changed request.form to request.POST
  • Looks like it's working...
  • let's try it with the test data from MY stripe account...
  • So I'll log in, go to the element instruction page and the checkout page, they'll produce my test and my live keys. Going to only use the test ones, swap 'em into the pages I've given here, and see what comes up on the dashboard.
  • But won't put those numbers up here cos vulnerability stuff. (Sorry guys!)

<h2>Hello, world, you're at Fred Socks</h2>


  • note in the view has curly brackets around output cos turns it to dictionary,
  • and also the template and html is listed in the return render
  • Create fred/templates/burp.html
<form action="/fred/socks/" method="POST">{% csrf_token %}
  <script
    src="https://checkout.stripe.com/checkout.js" class="stripe-button"
    data-key="pk_test_6pRNASCoBOKtIshFeQd4XMUh"
    data-amount="999"
    data-name="Stripe.com"
    data-description="Widget"
    data-image="https://stripe.com/img/documentation/checkout/marketplace.png"
    data-locale="auto"
    data-zip-code="true">
  </script>
</form>

  • the urls.py is updated
from django.conf.urls import url

from . import views
#from .views import burp, socks
urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^burp/$', views.burp, name='burp'),
    url(r'^socks/$', views.socks, name='socks'),
]

in mysite/mysite/settings change
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [ ],

to
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [r'mysite/fred/templates/'],

Don't actually need the stripe api bit yet.
Look into this tomorrow.

WOOP WOOP! IT WORKS!!! OH YEAH OH YEAH OH YEAH!

happy dance happy dance happy dance!
test data is picked up by stripe dashboard!

So to work on...
  • error handling
    • if unsuccessful gives code and reason why not working
    • if successful sends to page with a ? on the end so can then pick up in mautic hidden form
  • using elements instead of Checkout
    • cos can make fit page better and looks more like real checkout
    • but that should be a 3 second job
  • have can submit different amounts rather than just $10
    • is currently hardcoded into both the Checkout page and the charge view/thank you page. 
  • Tidy up these instructions





No comments:

Post a Comment