Commits (3)
# app_stripe
# Barcode Scanner
| Nom | Prénom |
|---------|--------|
| Doe | Jane |
| Doe | John |
Le TP est à réaliser par groupe de 2.
## Getting started
## Compétences évaluées
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
| Compétence | Aptitude | Description | Acquis | Remarque |
|------------|----------|----------------------------------------------------------------------------------------------------|--------|----------|
| D1 | C2 | Maîtriser la gestion des variables d’environnement d’une application | | |
| D2 | C1 | Maîtriser la création d’interfaces graphiques à l’aide de React Native | | |
| | C1 | Maîtriser l’API Stripe Javascript | | |
| | C3 | Maîtriser l’architecture logicielle d’un projet (services, composants, types, interfaces, classes) | | |
| | C3 | Maîtriser l’écriture de code asynchrone | | |
| | C3 | Savoir rédiger une documentaion | | |
| D4 | C1 | Maîtriser git | | |
| | C4 | Savoir respecter l’énoncé et l’échéance | | |
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
## Technologies requises
## Add your files
Vous allez avoir besoin des technologies suivantes :
- [Android Studio](https://developer.android.com/studio "Android Studio")
- [Docker](https://www.docker.com "Docker") Desktop ou CLI
- [NodeJS LTS](https://nodejs.org/fr "NodeJS")
- Un compte [Stripe](https://stripe.com/fr "Stripe")
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
## Travail à réaliser
```
cd existing_repo
git remote add origin https://www-apps.univ-lehavre.fr/forge/dj222837/app_stripe.git
git branch -M main
git push -uf origin main
```
## Integrate with your tools
- [ ] [Set up project integrations](https://www-apps.univ-lehavre.fr/forge/dj222837/app_stripe/-/settings/integrations)
## Collaborate with your team
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Automatically merge when pipeline succeeds](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
## Test and Deploy
Use the built-in continuous integration in GitLab.
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
Vous devez réaliser une application d'achat d'objets en tout genre à l'aide de Stripe.
***
Elle doit comprendre les pages/fonctionnalités suivantes :
# Editing this README
- Scan de codes-barres :
- Accès au panier ;
- Si l'appareil photo n'est pas disponible, il faut pouvoir ajouter les articles manuellement ;
- Une vérification via l'API est nécessaire afin de savoir si l'article existe.
- Un panier :
- Contient l'ensemble des articles scannés ;
- Accessible depuis la page de scan des articles ;
- Possibilité de retirer du panier un article scanné ;
- Lorsque qu'un article est ajouté plusieurs fois, afficher un indicateur précisant le nombre du même article ;
- Possibilité d'augmenter la quantité d'un article déjà scanné ;
- Possibilité de payer les articles sélectionnés à l'aide de Stripe ;
- Sauvergarde du panier pour de futurs achats.
- Un historique des articles payés.
- Un [thème jour/nuit](https://m2.material.io/design/color/dark-theme.html#ui-application).
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template.
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
Le projet est composé des choses suivantes :
- [Server](./server/README.md) : Une API développée avec FastAPI afin d'utiliser Stripe. Vous pouvez implémenter la votre.
- [Client](./client/README.md) : Une application React Native de départ, c'est ici que vous allez développer l'application.
## Name
Choose a self-explaining name for your project.
Il est imposé d'utiliser `Expo.SQLite` pour la persistence des données au niveau du client.
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
***Il est important de configurer le serveur avant le client.***
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Informations
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
Le projet a été créé l'aide de la commande suivante :
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
```shell
npx create-expo-app -t expo-template-blank-typescript
```
## License
For open source projects, say how it is licensed.
Il est possible de lancer l'application dans un émulateur Android et/ou iOS :
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
```shell
npx expo run:android # npx expo run:ios
```
# Learn more https://docs.github.com/en/get-started/getting-started-with-git/ignoring-files
# dependencies
node_modules/
# Expo
.expo/
dist/
web-build/
expo-env.d.ts
# Native
.kotlin/
*.orig.*
*.jks
*.p8
*.p12
*.key
*.mobileprovision
# Metro
.metro-health-check*
# debug
npm-debug.*
yarn-debug.*
yarn-error.*
# macOS
.DS_Store
*.pem
# local env files
.env*.local
# typescript
*.tsbuildinfo
# generated native folders
/ios
/android
import { StripeProvider } from '@stripe/stripe-react-native';
import CheckoutScreen from './CheckoutScreen';
import React from 'react';
export default function App() {
const stripePK = "pk_test_51SKwERQq66qTCnSLfpU75kBYasSolAbCKhA64jLG3r3q3XX4cCuJtv5M69juxlLE4Ptz0yp1fo8tSbxGFVMPecBv00AubYeo2l"
return (
<StripeProvider
publishableKey={stripePK}
merchantIdentifier="lola"
>
<CheckoutScreen />
</StripeProvider>
);
}
import { useStripe } from "@stripe/stripe-react-native";
import React, { useEffect, useState } from "react";
import { Alert, Text, Button, SafeAreaView } from "react-native";
export default function CheckoutScreen() {
const { initPaymentSheet, presentPaymentSheet } = useStripe();
const [loading, setLoading] = useState(false);
const [paymentIntentId, setPaymentIntentId] = useState<string>("");
const apiUrl = "http://172.26.7.103:8000";
const userId = "cus_THVVhujjj328BN";
const items = [
{
"id": 1,
"amount": 2
}
];
const fetchPaymentSheetParams = async () => {
const response = await fetch(`${apiUrl}/payments/`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
"pending_items": items,
"customer_id": userId
})
});
const { paymentIntent, ephemeralKey, customer } = await response.json();
return {
paymentIntent,
ephemeralKey,
customer,
};
};
const initializePaymentSheet = async () => {
const {
paymentIntent,
ephemeralKey,
customer,
} = await fetchPaymentSheetParams();
const { error } = await initPaymentSheet({
merchantDisplayName: "Example, Inc.",
customerId: customer,
customerEphemeralKeySecret: ephemeralKey,
paymentIntentClientSecret: paymentIntent,
allowsDelayedPaymentMethods: false,
});
if (!error) {
setPaymentIntentId(paymentIntent);
setLoading(true);
}
};
const openPaymentSheet = async () => {
const { error } = await presentPaymentSheet();
if (error) {
Alert.alert(`Error code: ${error.code}`, error.message);
} else {
const paymentIntent = `pi_${paymentIntentId.split("_")[1]}`;
const response = await fetch(`${apiUrl}/payments/check/${paymentIntent}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
"customer_id": userId
})
});
if (response.status == 200) Alert.alert('Success', 'Your order is confirmed!');
}
};
useEffect(() => {
initializePaymentSheet();
}, []);
return (
<SafeAreaView>
<Text>Payment</Text>
<Button
disabled={!loading}
title="Checkout"
onPress={openPaymentSheet}
/>
</SafeAreaView>
);
}
\ No newline at end of file
{
"expo": {
"name": "client",
"slug": "client",
"version": "1.0.0",
"orientation": "portrait",
"icon": "./assets/icon.png",
"userInterfaceStyle": "light",
"newArchEnabled": true,
"plugins": [
[
"@stripe/stripe-react-native",
{
"merchantIdentifier": "lola",
"enableGooglePay": false
}
]
],
"splash": {
"image": "./assets/splash-icon.png",
"resizeMode": "contain",
"backgroundColor": "#ffffff"
},
"ios": {
"supportsTablet": true
},
"android": {
"adaptiveIcon": {
"foregroundImage": "./assets/adaptive-icon.png",
"backgroundColor": "#ffffff"
},
"edgeToEdgeEnabled": true,
"predictiveBackGestureEnabled": false,
"package": "com.anonymous.client"
},
"web": {
"favicon": "./assets/favicon.png"
}
}
}
import { registerRootComponent } from 'expo';
import App from './App';
// registerRootComponent calls AppRegistry.registerComponent('main', () => App);
// It also ensures that whether you load the app in Expo Go or in a native build,
// the environment is set up appropriately
registerRootComponent(App);
Ce diff est replié.
{
"name": "client",
"version": "1.0.0",
"main": "index.ts",
"scripts": {
"start": "expo start",
"android": "expo run:android",
"ios": "expo run:ios",
"web": "expo start --web"
},
"dependencies": {
"@stripe/stripe-react-native": "0.50.3",
"expo": "~54.0.18",
"expo-status-bar": "~3.0.8",
"react": "19.1.0",
"react-native": "0.81.5",
"stripe": "^19.1.0"
},
"devDependencies": {
"@types/react": "~19.1.0",
"typescript": "~5.9.2"
},
"private": true
}
{
"extends": "expo/tsconfig.base",
"compilerOptions": {
"jsx": "react",
"strict": true
}
}
\ No newline at end of file
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/#use-with-ide
.pdm.toml
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
.idea/
dev.db
\ No newline at end of file
FROM python:3.11
WORKDIR /build
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1
COPY pyproject.toml poetry.lock ./
RUN apt-get update -y && \
apt-get install libpq-dev gcc -y
RUN pip install poetry
# force global installation
RUN poetry config virtualenvs.create false --local
RUN poetry install --no-root
COPY . .
CMD uvicorn src.main:app --proxy-headers --host 0.0.0.0 --reload --port $FASTAPI_PORT
\ No newline at end of file
# Server
Un backend développé à l'aide du framework Python, FastAPI.
## Structure de l'API
| Routeur | Chemin | Méthode | Description |
|----------|---------------------|---------|--------------------------------------------------------------------|
| Customer | / | GET | Renvoie la liste des utilisateurs |
| | / | POST | Ajoute d'un utilisateur |
| | /{customer_id} | GET | Renvoie les informations d'un utilisateur |
| Items | / | GET | Renvoie la liste des objets |
| | / | POST | Ajoute un objet |
| | / | DELETE | Supprime un objet |
| | /{item_id} | GET | Renvoie les informations d'un objet |
| Payment | / | GET | Renvoie la liste des paiements |
| | / | POST | Créée un paiement |
| | /{customer_id} | GET | Renvoie les paiements liés à un utilisateur |
| | /check/{payment_id} | POST | Valide le paiement si réalisé et renvoie la liste des objets payés |
## Configuration de l'API
Ajouter les variables d'environnement en vous aidant du fichier `.env.example` dans un fichier nommé `.env`.
La clé publique ainsi que la privée sont disponibles depuis le dashboard de Stripe.
Lancement du serveur :
```shell
docker compose up --build
```
Une fois lancé, accedez à la documentation de l'API à cette adresse : `http://localhost:{FASTAPI_PORT}/docs`.
Pour arrêter et supprimer le serveur :
```shell
docker compose down
```
## Avant d'utiliser le client
Pour que l'exemple du client puisse fonctionner correctement, il faut exécuter les commandes suivantes.
- Ajouter un `item` **banane** :
```curl
curl -X 'POST' \
'http://localhost:8000/items/' \
-H 'accept: application/json' \
-H 'Content-Type: application/json' \
-d '{
"name": "banane",
"price": 199
}'
```
La réponse attendue est :
```json
{
"name": "banane",
"price": 199,
"id": 1
}
```
- Ainsi qu'un `customer`. L'identifiant unique généré du `customer` correspond à l'identifiant Stripe du client :
```curl
curl -X 'POST' \
'http://localhost:8000/customers/' \
-H 'accept: application/json' \
-H 'Content-Type: application/json' \
-d '{
"email": "example@example.xyz"
}'
```
La réponse attendue est :
```json
{
"id": "cus_OmpJZapHkM2keT",
"email": "example@example.xyz"
}
```
version: '3'
services:
barcode-scanner-server:
build:
dockerfile: Dockerfile
env_file: .env
ports:
- ${FASTAPI_PORT}:${FASTAPI_PORT}
volumes:
- ./:/build
Ce diff est replié.
[tool.poetry]
name = "server"
version = "0.1.0"
description = ""
authors = ["Maxence Lambard <maxence.lambard@univ-lehavre.fr>"]
readme = "README.md"
[tool.poetry.dependencies]
python = "^3.10"
fastapi = "^0.87.0"
uvicorn = {extras = ["standard"], version = "^0.19.0"}
pydantic = "^1.10.2"
stripe = "^5.0.0"
sqlalchemy = "^1.4.44"
[tool.poetry.group.dev.dependencies]
autopep8 = "^2.0.0"
[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"
import os
from typing import Any
import stripe
from fastapi import FastAPI, Request, Response
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from . import customers, items, payments
from .database import Base, SessionLocal, engine
from .exceptions import (ConditionException, NotFoundException,
condition_exception_handler,
not_found_exception_handler)
sk_stripe: str = os.environ.get("STRIPE_SK")
stripe.api_key = sk_stripe
def create_app() -> FastAPI:
Base.metadata.create_all(bind=engine)
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.add_exception_handler(NotFoundException, not_found_exception_handler)
app.add_exception_handler(ConditionException, condition_exception_handler)
@app.middleware("http")
async def db_session_middleware(request: Request, call_next: Any):
response = Response("Internal server error", status_code=500)
try:
request.state.db = SessionLocal()
response = await call_next(request)
finally:
request.state.db.close()
return response
app.include_router(customers.routes.customers_router)
app.include_router(items.routes.item_router)
app.include_router(payments.routes.payments_router)
return app