前置准备
所有操作基于CentOS7系统、Python3.8环境,对接国家新闻出版署官方核验接口。
核心工具与材料
- 国家新闻出版署接口密钥:需在点击「政务服务」→「接口申请」提交数字档案馆主体信息,审核后获取(全程需企业资质备案)
- Python3.8:执行命令
yum install python38 -y 直接安装
- Flask框架开源数字档案馆项目:执行命令
git clone https://github.com/nppa/digital-archive.git /opt/digital-archive 克隆
- 依赖库:执行命令
pip3 install requests==2.31.0 flask==2.3.3 安装
实操步骤
步骤1:配置接口全局参数
进入项目根目录创建并编辑配置文件,执行命令:mkdir -p /opt/digital-archive && touch /opt/digital-archive/config.py,粘贴以下完整代码,必须替换为自己申请的密钥:
```python
/opt/digital-archive/config.py
NPPS_API_URL = "https://api.nppa.gov.cn/publish/license/verify"
NPPS_API_KEY = "YOUR_APPLIED_API_KEY_HERE" 替换为实际密钥
DEBUG = True
PORT = 5000
HOST = "0.0.0.0"
```
编辑操作细节:使用vim打开文件执行 vim /opt/digital-archive/config.py,按i进入插入模式,粘贴代码后按ESC,输入:wq保存退出。
步骤2:编写许可证核验接口调用代码
创建核验逻辑文件,执行命令:mkdir /opt/digital-archive/api && touch /opt/digital-archive/api/verify_license.py,粘贴以下完整代码:
```python
/opt/digital-archive/api/verify_license.py
import requests
from config import NPPS_API_URL, NPPS_API_KEY
def verify_publication_license(license_code, license_subject):
构造官方要求的请求参数
params = {
"key": NPPS_API_KEY,
"license_code": license_code,
"subject": license_subject
}
发送POST请求,设置10秒超时
try:
resp = requests.post(NPPS_API_URL, json=params, timeout=10)
resp.raise_for_status() 检查HTTP状态码(200为正常)
result = resp.json()
官方返回code=1为核验通过,0为失败
return {"status": result.get("code"), "msg": result.get("msg", "未知错误")}
except Exception as e:
return {"status": 0, "msg": f"请求异常:{str(e)}"}
```
步骤3:集成核验逻辑到业务接口

编辑项目主启动文件,执行命令:vim /opt/digital-archive/app.py,在原有代码中新增核验逻辑,核心代码如下(必须在数据录入前调用核验):
```python
/opt/digital-archive/app.py 新增部分
from api.verify_license import verify_publication_license
from flask import Flask, request, jsonify
app = Flask(__name__)
app.config.from_object("config")
原有出版物录入接口
@app.route("/api/import-publication", methods=["POST"])
def import_publication():
data = request.json
license_code = data.get("license_code")
license_subject = data.get("license_subject")
【重点操作:调用核验接口】
license_check = verify_publication_license(license_code, license_subject)
if license_check["status"] != 1:
return jsonify({
"code": 400,
"msg": f"许可证核验失败:{license_check['msg']}"
})
核验通过后执行原有的数据录入逻辑
...原有录入代码...
return jsonify({"code": 200, "msg": "录入成功"})
if __name__ == "__main__":
app.run(host=app.config["HOST"], port=app.config["PORT"], debug=app.config["DEBUG"])
```
步骤4:启动服务并测试
启动项目执行命令:python3 /opt/digital-archive/app.py;开启服务器端口5000的访问权限,执行命令:firewall-cmd --add-port=5000/tcp --permanent && firewall-cmd --reload。
测试接口:在本地或服务器终端执行curl命令,替换为实际许可证信息:
```bash
curl -X POST http://你的服务器IP:5000/api/import-publication \
-H "Content-Type: application/json" \
-d '{
"license_code": "出版物经营许可证编号",
"license_subject": "许可证主体全称"
}'
```
预期结果:返回{"code":200,"msg":"录入成功"};若返回{"code":400},需检查密钥是否过期或许可证信息是否填写正确。
常见问题排查
- 错误1:接口返回401 → 原因:密钥未备案或已失效,需重新登录国家新闻出版署官网更新密钥
- 错误2:请求超时 → 原因:服务器出站端口受限,需确认5000端口已放行
- 错误3:Python依赖缺失 → 执行命令
pip3 install --upgrade requests flask 重新安装