You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

2 Días
15 Hrs
3 Min
16 Seg

Procesador de Pagos con Stripe en Python

3/27
Resources

Building a payment processor is a common challenge in the software development industry, and in this course we will do it by applying SOLID principles and design patterns. The initial code will be basic and we will refactor it to conform to best practices as we go along.

How does the initial code work?

The code starts with a simple class that has a single method called processTransaction. This method receives two parameters: customerData and paymentData. Within this method, three basic validations are performed:

  • Verification that the customer has a name.
  • Verification that the customer has contact information.
  • Verification that the customer has a valid payment source.

How is payment processing handled?

Payment processing is handled through integration with Stripe. We use Stripe's API key, which is stored in environment variables, and create a charge based on the amount and data provided. The method handles any errors with a try-except block, sending a notification if the payment fails.

How are the results notified?

The code includes mechanisms to notify the customer by email or text message. However, since there is no SMTP server configured, annotated examples are used to illustrate what sending emails would look like. In the case of text messages, a mock that simulates an SMS gateway is used.

How is the transaction information recorded?

Finally, the method saves the transaction details in a transactions.log file. This file contains information such as the name of the customer, the amount collected and the final status of the payment. These records are useful for future reference and auditing.

What modifications can be made to the processor?

The code is flexible, and we can modify the customer and payment information to test different scenarios. For example, we can change the customer name, the amount to be charged, and the payment method, including using card tokens instead of card numbers. Stripe provides several tokens and test numbers that can be used to simulate transactions under different conditions.

What role do environment variables play?

An essential part of the code is the configuration of environment variables, which are handled by the Python .env module. This module loads the Stripe API key from the .env file, which ensures that the key is protected and accessible only during program execution.

Contributions 16

Questions 4

Sort by:

Want to see more contributions, questions and answers from the community?

**¡Alert!** 1. Creen el entorno virtual `python3 -m venv .venv`, es importante para que sea más eficiente si trabajamos en windows tener WSL2 Instalado. 2. Instalar las dependencias `pip install stripe` `pip install python-dotenv` que pide el archivo initial\_code.py 3. Descargar el archivo initial\_code.py que se tiene en la sección de recursos o archivos de clases
Al hacer un curso es muy molesto copiar y pegar código sin contexto. ¿Qué es stripe? ¿Por qué lo usamos? ¿Para qué lo usamos? ¿Cómo funciona?
Heyy Chicos... tal vez el Proffe fue muy rapido y omitio algunas cossas que por lo cual del curso El considera por defecto ya conocidos.\n esto es por hacwrse antes :\n 1. Descarga el formato comprimido .zip y extraeelor en algun lugar de tu /home directory. 2. Ir al directorio donde se descomprimio el archivo.: cd ~/Documents/path\_to\_Code \n 3. Crear un Ambiente Virtual : Python -m venv "VirtualEnv\_Name" . 4. Activar el Ambiente Virtual : sources myEnv/bin/activate . 5. Instalar Stripe and dotEnv : pip install stripe \npip install python-dotenv \n. 6. Crear Cuenta en <u>Stripe : </u>[**<u>https://docs.stripe.com/api/secret\_management</u>**](https://docs.stripe.com/api/secret_management)
Otro tema: El profesor dice que hay un paso a paso de como crear la cuenta en stripe pero no lo vi por ningun lado. Solo proveen el enlace a la documentación del API y ahí está el getting start. No se si tengan una cuenta solo para el uso del curso, así no tendríamos que crear cuentas personales.
podrían dejar en la sección de recursos, solo el codigo inicial, para hacer mas rapida la carga del codigo, lo otro o lo suben por cada clase o lo dejan para el final, pero me costó encontrar el codigo inicial, a pesar del nombre :D
Dejo por aquí mi aporte. Cuando ya tenga el proyecto y la cuenta de stripe creada (No necesitan agregar datos como empresa, simplemente se van luego de confirmar la cuenta al correo al dashboard) para obtener la clave secreta se van a: \- Sección Desarrolladores (sección izquierda) \- API Keys \- La que usaran será la clave secreta (uso de backend) Luego de tener la clave secreta dentro de la raíz del proyecto en vs code crean un archivo .env, allí crean la variable de entorno: STRIPE\_API\_KEY= Allí ponen la clave secreta y guardan.
Buenas a todos/as! Les dejo mi repo a todos y todas donde podrán encontrar como plus a lo que vimos con el instructor: 1. Una implementación completa para utilizar un gmail y enviar el email de verdad 2. Una implementación completa de twilio para enviar SMS de verdad frente a cada pago Espero les sea de utilidad. Se agredece feedback. Link: <https://github.com/Mgobeaalcoba/design_patterns_in_python>
trate de seguir todas las clases en este repo, se me hizo muy dificil... dividi en branchs y fui dejando teoria en los readme, en cada iteracion al menos fui probando que funcione. <https://github.com/guduchango/python-design-patterns-and-solid-principle>
Nota mental-> \>>> No empezar a escribir hasta que se termine el video! \- o si no... \- trabajaras por 1 hora lo que explican en 5 segundos a la midad del video. Nunca había trabajado con `stripe` ni con `.env` así que dure un buen rato tratando de "adivinar" su significado y utilidad. Luego pense que podia seguir con la clase y me dí cuenta que estaba a 10 segundo de tener la respuesta a todas mis duda T\_T
¡Hola! Para que no te pierdas en esta clase, te dejo un tutorial de cómo correr el proyecto: 1\. Descarga el .zip de los recursos de clase y crea una carpeta en donde instanciar el proyecto. 2\. Crea tu entorno virtual, en mi caso mi S.O es wsl2, es decir un Linux dentro de Windows y yo lo creo con estos comandos, asegúrate de tener los comandos para tu S.O: ```bash python3 -m venv env \# activa tu entorno con el siguiente comando: source env/bin/activate ``` 3\. Descarga las librerías: ```bash pip install stripe python-dotenv ``` 4\. Crea tu cuenta en Stripe: dirígete al siguiente link y crea una cuenta. Yo vivo en Colombia pero le puse México. 5\. Obtén tu API key: dirígete al siguiente link para obtener tu API key. Debes elegir tu llave secreta y copiarla. 6\. En la raíz de tu directorio/carpeta, crea un archivo y ponle de nombre .env. Allí debes pegar la API key secreta que copiaste del paso anterior. 7\. Ejecuta el proyecto :D
Hola. Les pido ayuda porque no he podido crear un pago. He hecho lo siguiente: 1\. Ya creé mi cuenta en stripe 2\. Solo la registré, porque pide muchos datos de empresas y otras cosas que no puedo proporcionar. 3\. Me fuí al link <https://dashboard.stripe.com/test/apikeys> y obtuve un API\_KEY "pk\_test\_51QNK...". Este es el que uso. 4\. No procesa el pago generando el siguiente error: Request req\_I3xZ3f5PAxNcNb: 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.> Nota: Alguien me respondió que no había necesidad de realizar todos los pasos, para poder probar en modo testing, ya que la información que estoy proporcionando no es real, comenzando por el pais que Colombia no estaba en la lista y me tocó usar USA. Luego pide información de empresa, y también número de celular. Me parece que deberían ser mas rápidos con este soporte o garantizar todos los pasos para poder realizar este curso sin bloqueos. No se si me pueda comunicar con alguien de soporte que me ayude a despegar en este curso.
Si desean trabajar con uv, y se descargan todo el código, estos son los pasos para instalar todas las dependencias: ````js ``` # Instalación de uv curl -LsSf https://astral.sh/uv/install.sh | sh # Creación del ambiente virtual uv venv # Activación del ambiente virtual source .venv/bin/activate # Instalación de dependencias uv pip install -r pyproject.toml --extra dev ``` ````
Ya vine con experiencia en usar stripe en otros lenguajes, pero creo que este video no está claro para los que van iniciando, hace falta más claridad en la explicación de las tecnologías a usar
Como crear e instalar en Python el venv (entorno virtual) Abre la terminal Dirigete al directorio del proyecto pon los siguientes comandos Dirígete al directorio de tu proyecto. ``` cd ruta/a/tu/proyecto ``` Crea el entorno virtual: ``` python -m venv nombre\_del\_entorno ``` Activar el entorno virtual: en Windows ``` nombre\_del\_entorno\Scripts\activate ``` En MAcOs o en Linux ``` source nombre\_del\_entorno/bin/activate ``` Una vez activado, verás el nombre del entorno virtual en tu terminal. Desde aquí, puedes instalar paquetes sin afectar a tu instalación global de Python.
Recuerden ir al apartado `Developers` al crear su usuario, ahi podran acceder a la `PK` y la `SK`
Tengo problemas para instalar dotenv en mi ambiente virtual. ¿Alguien sabe cómo solucionarlo? `Collecting dotenv` ` Using cached dotenv-0.0.5.tar.gz (2.4 kB)` ` Preparing metadata (setup.py) ... error` ` error: subprocess-exited-with-error` ` × python setup.py egg_info did not run successfully.` ` │ exit code: 1` ` ╰─> [69 lines of output]` ` C:\Users\ntban\OneDrive\Platzi\solid_python\myenv\Lib\site-packages\setuptools\__init__.py:94: _DeprecatedInstaller: setuptools.installer and fetch_build_eggs are deprecated.` ` !!` ` ********************************************************************************` ` Requirements should be satisfied by a PEP 517 installer.` `` If you are using pip, you can try `pip install --use-pep517`.`` ` ********************************************************************************` ` !!` ` dist.fetch_build_eggs(dist.setup_requires)` ` error: subprocess-exited-with-error` ` python setup.py egg_info did not run successfully.` ` exit code: 1` ` [1 lines of output]` `` ERROR: Can not execute `setup.py` since setuptools is not available in the build environment.`` ` [end of output]` ` note: This error originates from a subprocess, and is likely not a problem with pip.` ` error: metadata-generation-failed` ` Encountered error while generating package metadata.` ` See above for output.` ` note: This is an issue with the package mentioned above, not pip.` ` hint: See above for details.` ` Traceback (most recent call last):` ` File "C:\Users\ntban\OneDrive\Platzi\solid_python\myenv\Lib\site-packages\setuptools\installer.py", line 102, in _fetch_build_egg_no_warn` ` subprocess.check_call(cmd)` ` File "C:\Users\ntban\AppData\Local\Programs\Python\Python312\Lib\subprocess.py", line 413, in check_call` ` raise CalledProcessError(retcode, cmd)` ` subprocess.CalledProcessError: Command '['C:\\Users\\ntban\\OneDrive\\Platzi\\solid_python\\myenv\\Scripts\\python.exe', '-m', 'pip', '--disable-pip-version-check', 'wheel', '--no-deps', '-w', 'C:\\Users\\ntban\\AppData\\Local\\Temp\\tmpeqni7cx2', '--quiet', 'distribute']' returned non-zero exit status 1.` ` The above exception was the direct cause of the following exception:` ` Traceback (most recent call last):` ` File "<string>", line 2, in <module>` ` File "<pip-setuptools-caller>", line 34, in <module>` ` File "C:\Users\ntban\AppData\Local\Temp\pip-install-poycc_fj\dotenv_b628c5c201b4440ca338c9100f1a0406\setup.py", line 13, in <module>` ` setup(name='dotenv',` ` File "C:\Users\ntban\OneDrive\Platzi\solid_python\myenv\Lib\site-packages\setuptools\__init__.py", line 116, in setup` ` _install_setup_requires(attrs)` ` File "C:\Users\ntban\OneDrive\Platzi\solid_python\myenv\Lib\site-packages\setuptools\__init__.py", line 89, in _install_setup_requires` ` _fetch_build_eggs(dist)` ` File "C:\Users\ntban\OneDrive\Platzi\solid_python\myenv\Lib\site-packages\setuptools\__init__.py", line 94, in _fetch_build_eggs` ` dist.fetch_build_eggs(dist.setup_requires)` ` File "C:\Users\ntban\OneDrive\Platzi\solid_python\myenv\Lib\site-packages\setuptools\dist.py", line 656, in fetch_build_eggs` ` return _fetch_build_eggs(self, requires)` ` ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^` ` File "C:\Users\ntban\OneDrive\Platzi\solid_python\myenv\Lib\site-packages\setuptools\installer.py", line 39, in _fetch_build_eggs` ` resolved_dists = pkg_resources.working_set.resolve(` ` ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^` ` File "C:\Users\ntban\OneDrive\Platzi\solid_python\myenv\Lib\site-packages\pkg_resources\__init__.py", line 897, in resolve` ` dist = self._resolve_dist(` ` ^^^^^^^^^^^^^^^^^^^` ` File "C:\Users\ntban\OneDrive\Platzi\solid_python\myenv\Lib\site-packages\pkg_resources\__init__.py", line 933, in _resolve_dist` ` dist = best[req.key] = env.best_match(` ` ^^^^^^^^^^^^^^^` ` File "C:\Users\ntban\OneDrive\Platzi\solid_python\myenv\Lib\site-packages\pkg_resources\__init__.py", line 1271, in best_match` ` return self.obtain(req, installer)` ` ^^^^^^^^^^^^^^^^^^^^^^^^^^^` ` File "C:\Users\ntban\OneDrive\Platzi\solid_python\myenv\Lib\site-packages\pkg_resources\__init__.py", line 1307, in obtain` ` return installer(requirement) if installer else None` ` ^^^^^^^^^^^^^^^^^^^^^^` ` File "C:\Users\ntban\OneDrive\Platzi\solid_python\myenv\Lib\site-packages\setuptools\installer.py", line 104, in _fetch_build_egg_no_warn` ` raise DistutilsError(str(e)) from e` ` distutils.errors.DistutilsError: Command '['C:\\Users\\ntban\\OneDrive\\Platzi\\solid_python\\myenv\\Scripts\\python.exe', '-m', 'pip', '--disable-pip-version-check', 'wheel', '--no-deps', '-w', 'C:\\Users\\ntban\\AppData\\Local\\Temp\\tmpeqni7cx2', '--quiet', 'distribute']' returned non-zero exit status 1.` ` [end of output]` ` note: This error originates from a subprocess, and is likely not a problem with pip.` `error: metadata-generation-failed` `× Encountered error while generating package metadata.` `╰─> See above for output.` `note: This is an issue with the package mentioned above, not pip.` `hint: See above for details.`