Тестовые ключи Stripe API Django - PullRequest
0 голосов
/ 23 февраля 2019

Мне было интересно, знает ли кто-нибудь, что, черт возьми, не так с моим кодом / импортом ключей API в моем проекте.

import os
try:
    from secret import *
except:print("Error: make a local version of private_settings.py from the template")
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)


BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True




# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sites',
    'users',
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'allauth.socialaccount.providers.google',
    'stripe',
    'phonenumber_field',
    'multiselectfield',
    'crispy_forms',

    #My Apps
    'Spaces',
    'submitaspace',
    'product',
    'carts',
    'memberships',
]

CRISPY_TEMPLATE_PACK = 'bootstrap4'

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'Space.urls'

TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates')
STATIC_DIR = os.path.join(BASE_DIR, 'static')

STATIC_ROOT = os.path.join(BASE_DIR,'static_root')
STATICFILES_DIRS = [STATIC_DIR, ]

MEDIA_DIR = os.path.join(BASE_DIR, 'media')
MEDIA_ROOT = MEDIA_DIR
MEDIA_URL = '/media/'
#print(STATIC_ROOT)


#print(STATIC_DIR)
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [TEMPLATE_DIR,],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'django.template.context_processors.media'
            ],
        },
    },
]

STATIC_URL = '/static/'
MEDIA_ROOT = MEDIA_DIR #where to look for files
MEDIA_URL = '/media/' #where to serve files from on url

WSGI_APPLICATION = 'Space.wsgi.application'

if DEBUG:
    STRIPE_PUBLISHABLE_KEY = 'pk_test_MYPUBLISHABLEKEY'
    STRIPE_SECRET_KEY = 'sk_test_MYSECRETKEY'
else:
    STRIPE_PUBLISHABLE_KEY = 'pk_test_MYPUBLISHABLEKEY'
    STRIPE_SECRET_KEY = 'sk_test_MYTESTKEY'


# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

AUTHENTICATION_BACKENDS = (

    'django.contrib.auth.backends.ModelBackend',

    'allauth.account.auth_backends.AuthenticationBackend',

)
AUTH_USER_MODEL = 'users.CustomUser'
SITE_ID = 1

CSRF_COOKIE_SECURE = False

LOGIN_REDIRECT_URL = 'home'
# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

LOGIN_REDIRECT_URL = 'index'
LOGOUT_REDIRECT_URL = 'index'
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/

ОК, так что, как вы можете видеть здесь, я добавил свои ключи вправильный порядок, импортированная полоса в моем списке приложений.

Проверено оба ключа 1000000000 раз.

И я все еще получаю следующую ошибку:

$ python manage.py createsuperuser
Error: make a local version of private_settings.py from the template
Username: marko
Email address: myemail@gmail.com
Password:
Password (again):
Traceback (most recent call last):
  File "manage.py", line 15, in <module>
    execute_from_command_line(sys.argv)
  File "C:\Users\marko\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line
    utility.execute()
  File "C:\Users\marko\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 365, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Users\marko\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 288, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:\Users\marko\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 59, in execute
    return super().execute(*args, **options)
  File "C:\Users\marko\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 335, in execute
    output = self.handle(*args, **options)
  File "C:\Users\marko\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 179, in handle
    self.UserModel._default_manager.db_manager(database).create_superuser(**user_data)
  File "C:\Users\marko\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\auth\models.py", line 161, in create_superuser
    return self._create_user(username, email, password, **extra_fields)
  File "C:\Users\marko\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\auth\models.py", line 144, in _create_user
    user.save(using=self._db)
  File "C:\Users\marko\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\auth\base_user.py", line 73, in save
    super().save(*args, **kwargs)
  File "C:\Users\marko\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\base.py", line 729, in save
    force_update=force_update, update_fields=update_fields)
  File "C:\Users\marko\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\base.py", line 769, in save_base
    update_fields=update_fields, raw=raw, using=using,
  File "C:\Users\marko\AppData\Local\Programs\Python\Python37\lib\site-packages\django\dispatch\dispatcher.py", line 178, in send
    for receiver in self._live_receivers(sender)
  File "C:\Users\marko\AppData\Local\Programs\Python\Python37\lib\site-packages\django\dispatch\dispatcher.py", line 178, in <listcomp>
    for receiver in self._live_receivers(sender)
  File "C:\Users\marko\Documents\GitHub\SideSpacer\memberships\models.py", line 45, in post_save_usermembership_create
    new_customer_id = stripe.Customer.create(email=instance.email)
  File "C:\Users\marko\AppData\Local\Programs\Python\Python37\lib\site-packages\stripe\api_resources\abstract\createable_api_resource.py", line 22, in create
    response, api_key = requestor.request("post", url, params, headers)
  File "C:\Users\marko\AppData\Local\Programs\Python\Python37\lib\site-packages\stripe\api_requestor.py", line 121, in request
    resp = self.interpret_response(rbody, rcode, rheaders)
  File "C:\Users\marko\AppData\Local\Programs\Python\Python37\lib\site-packages\stripe\api_requestor.py", line 372, in interpret_response
    self.handle_error_response(rbody, rcode, resp.data, rheaders)
  File "C:\Users\marko\AppData\Local\Programs\Python\Python37\lib\site-packages\stripe\api_requestor.py", line 151, in handle_error_response
    raise err
stripe.error.PermissionError: 
Request req_IQMW2TtdvifmFW: This API call cannot be made with a publishable API key. Please use a secret API key. You can find a list of your API keys at https://dashboard.stripe.com/account/apikeys.

Моймодели:

  from django.conf import settings
from django.db import models
from django.db.models.signals import post_save

import stripe 

stripe.api_key = settings.STRIPE_SECRET_KEY



MEMBERSHIP_CHOICES = (
    ('Monthly', 'monthly'),
    ('3 - Month Subscription', 'threemonths'),
    ('Annual', 'annual'),
)

class Membership(models.Model):
    slug = models.SlugField()
    membership_type = models.CharField(choices=MEMBERSHIP_CHOICES,
                                        default='Monthly', max_length=30)
    price = models.IntegerField(default=0.00)
    stripe_plan_id = models.CharField(max_length=40)

    def __str__(self):
        return self.membership_type




class UserMembership(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    stripe_customer_id = models.CharField(max_length=40)
    membership = models.ForeignKey(Membership, on_delete=models.SET_NULL, null=True)

    def __str__(self):
        return self.user.username

def post_save_usermembership_create(sender, instance, created, *args, **kwargs):
    if created:
        UserMembership.objects.get_or_create(user=instance)

    user_membership, created = UserMembership.objects.get_or_create(user=instance)

    if user_membership.stripe_customer_id is None or user_membership.stripe_customer_id == '':
        new_customer_id = stripe.Customer.create(email=instance.email)
        user_membership.stripe_customer_id = new_customer_id['id']
        user_membership.save()

post_save.connect(post_save_usermembership_create, sender=settings.AUTH_USER_MODEL)





class Subscription(models.Model):
    user_membership = models.ForeignKey(UserMembership, on_delete=models.CASCADE)
    stripe_customer_id = models.CharField(max_length=40)
    active = models.BooleanField(default=True)

    def __str__(self):
        return self.user_membership.user.username

И да, я недавно установил полосу через пипс.Что касается приборной панели Stripe - я получаю статус ошибки 403

{
  "error": {
    "code": "secret_key_required",
    "doc_url": "https://stripe.com/docs/error-codes/secret-key-required",
    "message": "This API call cannot be made with a publishable API key. Please use a secret API key. You can find a list of your API keys at https://dashboard.stripe.com/account/apikeys.",
    "type": "invalid_request_error"
  }
}
...