├── api ├── __init__.py ├── migrations │ └── __init__.py ├── models.py ├── admin.py ├── apps.py ├── schemas.py └── api.py ├── SmsCodeWebhook ├── __init__.py ├── const.py ├── asgi.py ├── wsgi.py ├── urls.py └── settings_example.py ├── requirements.txt ├── start.sh ├── dockerfile ├── manage.py ├── README.md └── .gitignore /api/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /SmsCodeWebhook/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /api/migrations/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | django 2 | django-ninja 3 | django-redis -------------------------------------------------------------------------------- /api/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | # Create your models here. 4 | -------------------------------------------------------------------------------- /api/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | # Register your models here. 4 | -------------------------------------------------------------------------------- /api/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class ApiConfig(AppConfig): 5 | default_auto_field = 'django.db.models.BigAutoField' 6 | name = 'api' 7 | -------------------------------------------------------------------------------- /SmsCodeWebhook/const.py: -------------------------------------------------------------------------------- 1 | # redis的key名 2 | code_key = "code" 3 | # 验证码的redis的ttl 4 | CODE_TIMEOUT = 60 5 | # 轮询等待时间(秒) 6 | WAIT_TIME = 1 7 | # 获取验证码最大等待时间(秒) 8 | MAX_WAIT_TIME = 60 9 | # 匹配验证码正则表达式 10 | sms_code_pattern = r'\b\d{6}\b' -------------------------------------------------------------------------------- /start.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | echo -e "======================1. 启动redis========================\n" 4 | service redis-server start 2>/dev/null 5 | echo -e "redis启动成功...\n" 6 | 7 | echo -e "======================2. 启动SmsCodeWebhook========================\n" 8 | echo -e "SmsCodeWebhook正在接收请求...\n" 9 | python manage.py runserver 0.0.0.0:8000 10 | -------------------------------------------------------------------------------- /api/schemas.py: -------------------------------------------------------------------------------- 1 | from ninja import Schema 2 | from typing import Optional, Dict 3 | 4 | 5 | class GetCodeRequest(Schema): 6 | phone_number: str 7 | 8 | 9 | class SendSmsMsgRequest(Schema): 10 | phone_number: str 11 | sms_msg: str 12 | 13 | 14 | class ResponseSchema(Schema): 15 | err_code: int 16 | message: str 17 | data: Optional[Dict] = None 18 | -------------------------------------------------------------------------------- /SmsCodeWebhook/asgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | ASGI config for SmsCodeWebhook project. 3 | 4 | It exposes the ASGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.asgi import get_asgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'SmsCodeWebhook.settings') 15 | 16 | application = get_asgi_application() 17 | -------------------------------------------------------------------------------- /SmsCodeWebhook/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for SmsCodeWebhook project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'SmsCodeWebhook.settings') 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3.10.14-slim 2 | 3 | # 设置工作目录 4 | WORKDIR /app 5 | 6 | # 复制应用文件 7 | COPY . . 8 | 9 | # 安装依赖 10 | RUN pip install --no-cache-dir -r requirements.txt -i https://mirrors.aliyun.com/pypi/simple/ 11 | 12 | # 安装 Redis 13 | RUN apt-get update && \ 14 | apt-get install -y redis-server && \ 15 | apt-get clean 16 | 17 | 18 | # 时区 19 | RUN apt-get install -y tzdata 20 | ENV TZ=Asia/Shanghai 21 | RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone 22 | 23 | # 定义启动命令,运行 main.py 24 | CMD ["bash", "start.sh"] 25 | 26 | -------------------------------------------------------------------------------- /manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Django's command-line utility for administrative tasks.""" 3 | import os 4 | import sys 5 | 6 | 7 | def main(): 8 | """Run administrative tasks.""" 9 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'SmsCodeWebhook.settings') 10 | try: 11 | from django.core.management import execute_from_command_line 12 | except ImportError as exc: 13 | raise ImportError( 14 | "Couldn't import Django. Are you sure it's installed and " 15 | "available on your PYTHONPATH environment variable? Did you " 16 | "forget to activate a virtual environment?" 17 | ) from exc 18 | execute_from_command_line(sys.argv) 19 | 20 | 21 | if __name__ == '__main__': 22 | main() 23 | -------------------------------------------------------------------------------- /SmsCodeWebhook/urls.py: -------------------------------------------------------------------------------- 1 | """SmsCodeWebhook URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/3.2/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: path('', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.urls import include, path 14 | 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 15 | """ 16 | from django.contrib import admin 17 | from django.urls import path 18 | from api.api import api 19 | 20 | urlpatterns = [ 21 | path('admin/', admin.site.urls), 22 | path('api/', api.urls), 23 | ] 24 | -------------------------------------------------------------------------------- /api/api.py: -------------------------------------------------------------------------------- 1 | from ninja import NinjaAPI 2 | from django.core.cache import cache 3 | import time 4 | from .schemas import SendSmsMsgRequest, GetCodeRequest, ResponseSchema 5 | import re 6 | from SmsCodeWebhook.const import ( 7 | code_key, 8 | CODE_TIMEOUT, 9 | WAIT_TIME, 10 | MAX_WAIT_TIME, 11 | sms_code_pattern 12 | ) 13 | api = NinjaAPI() 14 | 15 | 16 | @api.post("/getCode", response=ResponseSchema) 17 | def get_code(request, request_body: GetCodeRequest): 18 | start_time = time.time() 19 | key = request_body.phone_number 20 | while True: 21 | code = cache.get(key) 22 | 23 | if code: 24 | cache.delete(key) # 删除已使用的验证码 25 | return ResponseSchema(err_code=0, message="Success", data={"code": code}) 26 | 27 | if time.time() - start_time > MAX_WAIT_TIME: 28 | return ResponseSchema(err_code=408, message="获取验证码超时") 29 | 30 | time.sleep(WAIT_TIME) 31 | 32 | 33 | @api.post("/sendSmsMsg", response=ResponseSchema) 34 | def send_sms_msg(request, request_body: SendSmsMsgRequest): 35 | # 获取手机号码 36 | key = request_body.phone_number 37 | # 获取短信内容 38 | sms_msg = request_body.sms_msg 39 | # 这里来解析的短信内容 40 | re_pattern = re.compile(sms_code_pattern) 41 | match = re_pattern.search(sms_msg) 42 | if match: 43 | code = match.group(0) 44 | cache.set(key, code, timeout=CODE_TIMEOUT) 45 | return ResponseSchema(err_code=0, message="Set code successfully.") 46 | return ResponseSchema(err_code=400, message="Set code fail.") -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SmsCodeWebook 2 | 3 | ## 介绍 4 | - 自用验证码的接收webhook, 基于django-ninja, redis 5 | - 提供/api/getCode和/api/sendSmsMsg 2个接口 6 | - 整体步骤如下: 7 | - 业务方手动或自动触发发送短信验证码, 然后调用SmsCodeWebook的/api/getCode, 等待返回验证码; 8 | - 移动端(android等) 使用工具(如SmsForwarder) 监听手机短信 9 | - 当工具监听到验证码短信时, 调用SmsCodeWebook的/api/sendSmsMsg接口发送短信内容; 10 | - SmsCodeWebook接受到短信内容后, 将验证码从短信中匹配出来, 存到redis中; 11 | - SmsCodeWebook从redis取出key, 返回验证码给业务方。 12 | 13 | 14 | ## 使用文档 15 | 16 | ## 1、docker部署(推荐) 17 | 18 | ### 下载镜像 19 | ```shell 20 | docker pull icepage/scw:latest 21 | ``` 22 | 23 | ### 运行 24 | 25 | 使用默认settings.py 26 | ```bash 27 | docker run -p 8000:8000 icepage/scw:latest 28 | ``` 29 | 30 | 自定义settings.py 31 | ```bash 32 | docker run -v /本地路径/settings.py:/app/SmsCodebhook/settings.py -p 8000:8000 icepage/scw:latest 33 | ``` 34 | 35 | ### 测试 36 | 开2个终端测试 37 | 38 | #### 终端1 39 | 调用/api/getCode, 等待验证码 40 | ```shell 41 | curl -X POST 'http://127.0.0.1:8000/api/getCode' -d '{"phone_number": "13500000000"}' 42 | ``` 43 | 44 | #### 终端2 45 | 调用/api/sendSmsMsg,发送验证消息 46 | ```shell 47 | curl -X POST 'http://127.0.0.1:8000/api/sendSmsMsg' -d '{"phone_number": "13500000000", "sms_msg": "【京东】请确认本人操作,切勿泄露给他人。您正在新设备上登录,验证码:475431。京东工作人员不会索取此验证码。"}' 48 | ``` 49 | 50 | #### 重回终端1 51 | 看到验证码返回 52 | 53 | 54 | ## 2、本地部署 55 | ### 安装依赖 56 | ```commandline 57 | pip install -r requirements.txt 58 | ``` 59 | ### 安装redis 60 | 自行安装 61 | 62 | ### 配置settings.py 63 | 复制settings_example.py, 重命名为settings.py 64 | 65 | #### 添加redis配置 66 | 编辑settings.py 67 | ```python 68 | redis_host = '127.0.0.1' 69 | redis_port = '6379' 70 | redis_pass = '123456' 71 | redis_database = '0' 72 | 73 | CACHES = { 74 | 'default': { 75 | 'BACKEND': 'django_redis.cache.RedisCache', 76 | 'LOCATION': f'redis://:{redis_pass}@{redis_host}:{redis_port}/{redis_database}', 77 | 'OPTIONS': { 78 | 'CLIENT_CLASS': 'django_redis.client.DefaultClient', 79 | } 80 | } 81 | } 82 | ``` 83 | 84 | ## 运行服务 85 | ```commandline 86 | python manage.py runserver 87 | ``` 88 | 89 | 90 | ## 接口说明 91 | ### 1. Send SMS Message 92 | 93 | #### Endpoint 94 | `POST /api/sendSmsMsg` 95 | 96 | #### Description 97 | 发送验证码短信原文 98 | 99 | #### Body 100 | ```json 101 | { 102 | "phone_number": "13500000000", 103 | "sms_msg": "请确认本人操作,切勿泄露给他人。您正在新设备上登录,验证码:475431。" 104 | } 105 | ``` 106 | 107 | ##### Content-Type: `application/json` 108 | 109 | ### 2. Get Code 110 | 111 | #### Endpoint 112 | `POST /api/getCode` 113 | 114 | #### Description 115 | 获取验证码 116 | 117 | #### Body 118 | ```json 119 | { 120 | "phone_number": "13500000000" 121 | } 122 | ``` 123 | 124 | ##### Content-Type: `application/json` 125 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 98 | __pypackages__/ 99 | 100 | # Celery stuff 101 | celerybeat-schedule 102 | celerybeat.pid 103 | 104 | # SageMath parsed files 105 | *.sage.py 106 | 107 | # Environments 108 | .env 109 | .venv 110 | env/ 111 | venv/ 112 | ENV/ 113 | env.bak/ 114 | venv.bak/ 115 | 116 | # Spyder project settings 117 | .spyderproject 118 | .spyproject 119 | 120 | # Rope project settings 121 | .ropeproject 122 | 123 | # mkdocs documentation 124 | /site 125 | 126 | # mypy 127 | .mypy_cache/ 128 | .dmypy.json 129 | dmypy.json 130 | 131 | # Pyre type checker 132 | .pyre/ 133 | 134 | # pytype static type analyzer 135 | .pytype/ 136 | 137 | # Cython debug symbols 138 | cython_debug/ 139 | 140 | # config 141 | settings.py 142 | 143 | .idea -------------------------------------------------------------------------------- /SmsCodeWebhook/settings_example.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for SmsCodeWebhook project. 3 | 4 | Generated by 'django-admin startproject' using Django 3.2.6. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.2/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/3.2/ref/settings/ 11 | """ 12 | 13 | from pathlib import Path 14 | 15 | # Build paths inside the project like this: BASE_DIR / 'subdir'. 16 | BASE_DIR = Path(__file__).resolve().parent.parent 17 | 18 | 19 | # Quick-start development settings - unsuitable for production 20 | # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ 21 | 22 | # SECURITY WARNING: keep the secret key used in production secret! 23 | SECRET_KEY = 'django-insecure-l()(8j5^o(snkck)nmzj!t*%po#z3q-j+6plr)9y6lheap!&2j' 24 | 25 | # SECURITY WARNING: don't run with debug turned on in production! 26 | DEBUG = True 27 | 28 | ALLOWED_HOSTS = [] 29 | 30 | 31 | # Application definition 32 | 33 | INSTALLED_APPS = [ 34 | 'django.contrib.admin', 35 | 'django.contrib.auth', 36 | 'django.contrib.contenttypes', 37 | 'django.contrib.sessions', 38 | 'django.contrib.messages', 39 | 'django.contrib.staticfiles', 40 | ] 41 | 42 | MIDDLEWARE = [ 43 | 'django.middleware.security.SecurityMiddleware', 44 | 'django.contrib.sessions.middleware.SessionMiddleware', 45 | 'django.middleware.common.CommonMiddleware', 46 | 'django.middleware.csrf.CsrfViewMiddleware', 47 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 48 | 'django.contrib.messages.middleware.MessageMiddleware', 49 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 50 | ] 51 | 52 | ROOT_URLCONF = 'SmsCodeWebhook.urls' 53 | 54 | TEMPLATES = [ 55 | { 56 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 57 | 'DIRS': [], 58 | 'APP_DIRS': True, 59 | 'OPTIONS': { 60 | 'context_processors': [ 61 | 'django.template.context_processors.debug', 62 | 'django.template.context_processors.request', 63 | 'django.contrib.auth.context_processors.auth', 64 | 'django.contrib.messages.context_processors.messages', 65 | ], 66 | }, 67 | }, 68 | ] 69 | 70 | WSGI_APPLICATION = 'SmsCodeWebhook.wsgi.application' 71 | 72 | 73 | # Database 74 | # https://docs.djangoproject.com/en/3.2/ref/settings/#databases 75 | 76 | # DATABASES = { 77 | # 'default': { 78 | # 'ENGINE': 'django.db.backends.sqlite3', 79 | # 'NAME': BASE_DIR / 'db.sqlite3', 80 | # } 81 | # } 82 | 83 | 84 | # Password validation 85 | # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators 86 | 87 | AUTH_PASSWORD_VALIDATORS = [ 88 | { 89 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 90 | }, 91 | { 92 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 93 | }, 94 | { 95 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 96 | }, 97 | { 98 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 99 | }, 100 | ] 101 | 102 | 103 | # Internationalization 104 | # https://docs.djangoproject.com/en/3.2/topics/i18n/ 105 | 106 | LANGUAGE_CODE = 'en-us' 107 | 108 | TIME_ZONE = 'UTC' 109 | 110 | USE_I18N = True 111 | 112 | USE_L10N = True 113 | 114 | USE_TZ = True 115 | 116 | 117 | # Static files (CSS, JavaScript, Images) 118 | # https://docs.djangoproject.com/en/3.2/howto/static-files/ 119 | 120 | STATIC_URL = '/static/' 121 | 122 | # Default primary key field type 123 | # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field 124 | 125 | DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' 126 | 127 | redis_host = '127.0.0.1' 128 | redis_port = '6379' 129 | redis_pass = '123456' 130 | redis_database = '0' 131 | 132 | CACHES = { 133 | 'default': { 134 | 'BACKEND': 'django_redis.cache.RedisCache', 135 | 'LOCATION': f'redis://:{redis_pass}@{redis_host}:{redis_port}/{redis_database}', 136 | 'OPTIONS': { 137 | 'CLIENT_CLASS': 'django_redis.client.DefaultClient', 138 | } 139 | } 140 | } --------------------------------------------------------------------------------