### Get Invoice PDF Request Example Source: https://github.com/fapiaoapi/invoice/blob/master/README.md Example of form-data submission for retrieving invoice PDFs. Ensure all required fields like 'fphm', 'nsrsbh', and 'downflag' are provided. ```text fphm:22512000000000007325downflag:1nsrsbh:915101820724315989kprq:20230201120326addSeal:1 ``` -------------------------------- ### Get Face Image API Request Example Source: https://github.com/fapiaoapi/invoice/blob/master/README.md Example of parameters for the 'getFaceImg' API, used to obtain a face QR code. Requires 'nsrsbh' (taxpayer ID). ```text nsrsbh : 915101820724315989 ``` -------------------------------- ### Invoice Request Example Source: https://github.com/fapiaoapi/invoice/blob/master/README.md Example of a typical invoice request message structure. Ensure all fields are correctly formatted. ```text fpqqlsh:uuidxhdwsbh:91510113MA6739XPX2xhdwdzdh:成都市青白江区清泉大道二段6668号附990号(欧洲产业城) 13540471704xhdwyhzh:工商银行成都华金大道支行 4402032009000058076ghdwsbh:91110108MA019HQRX9ghdwmc:重庆悦江河科技有限公司ghdwdzdh:北京市海淀区紫雀路33号院3号楼二层3201 010-62408884ghdwyhzh:北京市海淀区紫雀路33号院3号楼二层3201 010-62408884kpr:tzdbh:510123321yfphm:235123123123tdyslxDm:bz: ``` -------------------------------- ### Get Face State API Request Example Source: https://github.com/fapiaoapi/invoice/blob/master/README.md Example of parameters for the 'getFaceState' API, used to check the status of a face QR code authentication. Requires 'nsrsbh' and 'rzid'. ```text nsrsbh : 915101820724315989rzid : 5246703dc22842b5a3d7826f375e6c7d ``` -------------------------------- ### API Response Examples Source: https://github.com/fapiaoapi/invoice/blob/master/README.md Provides examples of successful and error response messages for API calls, illustrating the structure of the returned data. ```json ``` 正确状态报文: { "code": 200, "msg": "成功", "data": { "xxbbh": "51011321231231231101348", "uuid": "d3f9176a2asja2315bcf1483fc4fa3f85", "xxbzt":"无需确认", "xxbztDm":"01", "sqsj":"2023-12-06 11:32:35" } } 报错返回报文: { "code": 999, "msg": "未能判断当前纳税人与发票中身份,请检查" } ``` ``` -------------------------------- ### Get Enterprise Authorization Token (Java) Source: https://context7.com/fapiaoapi/invoice/llms.txt Java example to obtain an authorization token, which is a prerequisite for calling other APIs. The token is valid for 30 days and should be cached. Requires company taxpayer identification number and authorization type. ```java // Java示例 - 获取授权Token import java.time.Instant; import java.util.LinkedHashMap; import java.util.Map; public class AuthorizationExample { private static final String BASE_URL = "https://api.fa-piao.com"; private static final String APP_KEY = "YOUR_APP_KEY"; private static final String APP_SECRET = "YOUR_SECRET_KEY"; public static void main(String[] args) throws Exception { // 准备请求参数 Map formData = new LinkedHashMap<>(); formData.put("nsrsbh", "915101820724315989"); // 统一社会信用代码 formData.put("type", "6"); // 6:基础版, 7:标准版 formData.put("username", "138XXXXXXXX"); // 电子税务局手机号 formData.put("password", "your_password"); // 电子税务局密码 // 生成签名参数 String path = "/v5/enterprise/authorization"; String randomString = generateRandomString(20); String timestamp = String.valueOf(Instant.now().getEpochSecond()); String signature = calculateSignature("POST", path, randomString, timestamp, APP_KEY, APP_SECRET); // 设置请求头 Map headers = new LinkedHashMap<>(); headers.put("AppKey", APP_KEY); headers.put("Sign", signature); headers.put("TimeStamp", timestamp); headers.put("RandomString", randomString); // 发送请求并获取Token ApiResponse response = postMultipart(path, headers, formData); if (response.getCode() == 200) { String token = response.getTokenString(); System.out.println("授权Token: " + token); // TODO: 将token缓存到Redis,有效期30天 } } // 响应示例: // { // "code": 200, // "msg": "success", // "data": { // "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." // } // } } ``` -------------------------------- ### Go Example: Face Authentication Flow Source: https://context7.com/fapiaoapi/invoice/llms.txt This Go code demonstrates the complete flow for face authentication, including obtaining a QR code and checking the authentication status. Ensure you replace placeholder values for AppKey, AppSecret, token, nsrsbh, and username. ```Go package main import ( "crypto/hmac" "crypto/sha256" "encoding/hex" "encoding/json" "fmt" "io" "net/http" "net/url" "strings" "time" ) const ( BaseURL = "https://api.fa-piao.com" AppKey = "YOUR_APP_KEY" AppSecret = "YOUR_SECRET_KEY" ) func calculateSignature(method, path, randomString, timestamp string) string { signContent := fmt.Sprintf( "Method=%s&Path=%s&RandomString=%s&TimeStamp=%s&AppKey=%s", method, path, randomString, timestamp, AppKey, ) mac := hmac.New(sha256.New, []byte(AppSecret)) mac.Write([]byte(signContent)) return strings.ToUpper(hex.EncodeToString(mac.Sum(nil))) } // 获取人脸认证二维码 func getFaceQRCode(token, nsrsbh, username string) (map[string]interface{}, error) { path := "/v5/enterprise/getFaceImg" timestamp := fmt.Sprintf("%d", time.Now().Unix()) randomString := generateRandomString(20) signature := calculateSignature("GET", path, randomString, timestamp) params := url.Values{} params.Set("nsrsbh", nsrsbh) params.Set("username", username) req, _ := http.NewRequest("GET", BaseURL+path+"?"+params.Encode(), nil) req.Header.Set("AppKey", AppKey) req.Header.Set("Sign", signature) req.Header.Set("TimeStamp", timestamp) req.Header.Set("RandomString", randomString) req.Header.Set("Authorization", "Bearer "+token) client := &http.Client{} resp, err := client.Do(req) if err != nil { return nil, err } defer resp.Body.Close() body, _ := io.ReadAll(resp.Body) var result map[string]interface{} json.Unmarshal(body, &result) return result, nil } // 查询人脸认证状态 func getFaceStatus(token, nsrsbh, username, rzid string) (map[string]interface{}, error) { path := "/v5/enterprise/getFaceState" timestamp := fmt.Sprintf("%d", time.Now().Unix()) randomString := generateRandomString(20) signature := calculateSignature("GET", path, randomString, timestamp) params := url.Values{} params.Set("nsrsbh", nsrsbh) params.Set("username", username) params.Set("rzid", rzid) req, _ := http.NewRequest("GET", BaseURL+path+"?"+params.Encode(), nil) req.Header.Set("AppKey", AppKey) req.Header.Set("Sign", signature) req.Header.Set("TimeStamp", timestamp) req.Header.Set("RandomString", randomString) req.Header.Set("Authorization", "Bearer "+token) client := &http.Client{} resp, err := client.Do(req) if err != nil { return nil, err } defer resp.Body.Close() body, _ := io.ReadAll(resp.Body) var result map[string]interface{} json.Unmarshal(body, &result) return result, nil } func main() { token := "your_token" nsrsbh := "915101820724315989" username := "138XXXXXXXX" // 步骤1: 获取人脸二维码 qrResult, _ := getFaceQRCode(token, nsrsbh, username) if qrResult["code"].(float64) == 200 { data := qrResult["data"].(map[string]interface{}) evm := data["ewm"].(string) // 二维码内容 ewmly := data["ewmly"].(string) // 二维码来源 rzid := data["rzid"].(string) // 认证ID if ewmly == "swj" { fmt.Println("请使用电子税务局APP扫码") } else { fmt.Println("请使用个人所得税APP扫码") } fmt.Println("二维码内容:", ewm) // 步骤2: 用户扫码后查询状态 time.Sleep(30 * time.Second) // 等待用户扫码 statusResult, _ := getFaceStatus(token, nsrsbh, username, rzid) if statusResult["code"].(float64) == 200 { slzt := statusResult["data"].(map[string]interface{})["slzt"].(string) switch slzt { case "1": fmt.Println("状态: 未认证") case "2": fmt.Println("状态: 认证成功") default: fmt.Println("状态: 二维码已过期") } } } } ``` -------------------------------- ### Get Authentication Status Response Source: https://github.com/fapiaoapi/invoice/blob/master/README.md Example response for checking the authentication status of an enterprise. Includes success and error message formats. ```json { "code": 200, "msg": "成功", "data": { "rzid": null, "nsrsbh": "91510112332131211", "ewm": null, "slzt": "1" }, "total": 0 } ``` ```json { "code": 999, "msg": "失败", "data": "销方税号有误", "total": 0 } ``` -------------------------------- ### Switch Taxpayer Identification Number Request Example Source: https://github.com/fapiaoapi/invoice/blob/master/README.md Example payload for switching the taxpayer identification number. Ensure all required fields are populated. ```text oldNsrsbh:92511521123123H6FnewNsrsbh:9251123123136PH3PXYusername:1231231sf:03 ``` -------------------------------- ### Error Response Example Source: https://github.com/fapiaoapi/invoice/blob/master/README.md Example of a general error response from the API. The 'msg' field provides a description of the failure. ```json { "code": 999, "msg": "失败" } ``` -------------------------------- ### Examples of Red-Letter Invoice Application Data Source: https://github.com/fapiaoapi/invoice/blob/master/README.md These examples illustrate the data structures required for applying for red-letter invoices for different scenarios, including electronic and paper invoices, and partial沖-offs. ```text 数电票销方申请红字信息表示例xhdwsbh:9151123123123123yfphm:123321chyydm:01sqyy:2 ``` ```text 税控纸票销方申请红字信息表示例xhdwsbh:9232123123123123X222chyydm:01sqyy:2yfphm:1111111yfpdm:03212312312304fplxdm:007 ``` ```text 数电纸票销方申请红字信息表(红字信息表申请成功后负数发票为数电电票 )xhdwsbh:9151123123123123xhdwsbh:9151123123123123chyydm:01sqyy:2sdfpbz:1 ``` ```text 数电纸票销方申请红字信息表(红字信息表申请成功后负数发票依旧为数电纸票)xhdwsbh:9151123123123123yfphm:123321chyydm:01sqyy:2sdfpbz:0 ``` ```text 数电票销售申请部分冲红信息表xhdwsbh:9151123123123123yfphm:123321chyydm:01sqyy:2fyxm[0][xh]:1fyxm[0][spsl]:-0.5fyxm[0][je]:-53.1fyxm[0][se]:-6.9fyxm[0][hsbz]:0hjje:-53.1hjse:-6.9bfch:1 ``` ```text 购方申请数电票红字信息表xhdwsbh:91440101753491772Bchyydm:01sqyy:3yfphm:21155896username:18202001640nsrsbh:91441721MA56R6304Q // 当前购方的纳税人识别号kprq:2023-09-11 11:49:06 ``` ```text 购方申请数电票红字信息表部分冲红xhdwsbh:91440101753491772Bchyydm:01sqyy:3yfphm:21155896username:18202001640nsrsbh:91441721MA56R6304Q// 当前购方的纳税人识别号kprq:2023-09-11 11:49:06fyxm[0][xh]:1fyxm[0][spsl]:-0.5fyxm[0][je]:-53.1fyxm[0][se]:-6.9fyxm[0][hsbz]:0hjje:-53.1hjse:-6.9bfch:1 ``` ```text 需要入账再申请红字 传 1 否着传空jyrzzt:1清单发票部分红冲,申请红字信息表,需要额外在第一行 fyxm 里边固定传 xh 为 0,je 为红票的 hjje,se 为红票的 hjse 这几个参数,参考示例如下:fyxm[0][xh]:0fyxm[0][je]:-1309.74fyxm[0][se]:-170.26fyxm[1][xh]:需要冲清单明细里面的第几行商品 ``` -------------------------------- ### Credit Line Query Response Example Source: https://github.com/fapiaoapi/invoice/blob/master/README.md Response structure for the credit line query. Includes details on remaining and total credit lines, invoice statistics, and tax amounts. ```json { "code": 200, "msg": "成功", "data": { "sysxed": "剩余授信额度-保留 2 位小数", "zsxed": "总授信额度-保留 2 为小数", "kjlpzs": "开具蓝票张数", "fpejse": "发票税额-保留 2 为小数", "ysysxed": "已使用总授信额度-保留 2 为小数", "fphjje": "发票金额-保留 2 为小数", "axkp": "按需开票 Y-是否是按需开票" }, "total": 0 } ``` -------------------------------- ### Invoice API Response Examples Source: https://github.com/fapiaoapi/invoice/blob/master/README.md Illustrates successful and error responses from the invoice API, including data structures for successful retrieval and error conditions. ```json { "code": 200, "msg": "成功", "data": { "Fphm": "22111111111111111180", "Kprq": "2022-11-28 15:28:11", "Gmfyx": null, "GmfSsjswjgdm": null }, "total": 0 } ``` ```json { "code": 999, "msg": "已过实人认证时间,请重新实人认证", "data": null, "total": 0 } ``` ```json { "code": 200, "msg": "成功", "message": "成功", "data": { "nsrsbh": "915333333333333333", "rzid": "6eb01d52edfd47878d6ed4487913a655", "slzt": null, "ewm": "qrcode_id=6O+iMFGsDxgC96nASdms0L5Lme6TP+bpbr/jIM3d0ZwFAdAvmDp7i7Yobk7zzkNM&areaPrefix=5100&interfaceCode=0004", "ewmly": "swj" }, "total": 0 } ``` -------------------------------- ### Invoice API Response Examples Source: https://github.com/fapiaoapi/invoice/blob/master/README.md Provides examples of successful and error responses from the Invoice API. The success response includes detailed invoice data, while the error response indicates a failure to determine taxpayer identity. ```json { "code": 200, "msg": "成功", "data": { "fphm": "22123123123123123115", "message": "成功,本张发票可以开负数!", "xhdwsbh": "91512332122222274", "xhdwmc": "成都 XXXXXXXXXXX 公司", "ghdwsbh": "9151012222222222", "ghdwmc": "昕诺 XXXXXXXXX 有限公司", "kprq": "2022-11-23 22:48:06", "hjje": -208.05, "hjse": -27.05, "fplxdm": "81", "tdyslxDm": null, "jbr": null, "mxzb": [ { "xh": 1, "sl": 0.13, "dw": "个", "spmc": "*有色金属冶炼压延品*电气底座 3+P2 HLF_R", "se": -27.05, "je": -208.05, "spdj": "104.025", "ggxh": "444170080041", "spsl": "-2", "spbm": "1080310990000000000", "hsbz": "", "yhzcbs": "", "zzstsgl": "", "sqdh": "", "lslbs": "" } ] } } ``` ```json { "code": 999, "msg": "未能判断当前纳税人与发票中身份,请检查" } ``` -------------------------------- ### Query Authentication Status Request Parameter Source: https://github.com/fapiaoapi/invoice/blob/master/README.md Example of a request parameter for querying authentication status, specifying the taxpayer identification number. ```text nsrsbh : 91510113MA6739XPX2 ``` -------------------------------- ### Invoice Retrieval API Response Examples Source: https://github.com/fapiaoapi/invoice/blob/master/README.md Shows successful responses for retrieving invoice files, either as a base64 encoded string or URLs. Error responses indicate failure codes and messages. ```json { "code": 200, "msg": "成功", "data": "base64加密字符串", "total": 0 } ``` ```json { "code": 200, "msg": "成功", "data": { "ofdUrl": "", "pdfUrl": "", "xmlUrl": "" }, "total": 0 } ``` ```json { "code": 999, "msg": "失败", "data": "total": 0 } ``` ```json { "code": 234, "msg": "获取文件超时,请稍后重试。", "data": null, "total": 0 } ``` -------------------------------- ### Calculate HMAC-SHA256 Signature (Python) Source: https://context7.com/fapiaoapi/invoice/llms.txt Python example demonstrating how to calculate the HMAC-SHA256 signature required for all API requests. The signature is generated based on the HTTP method, request path, a random string, timestamp, and application credentials. ```python #!/usr/bin/env python3 # Python示例 - HMAC-SHA256签名计算 import time import random import string import hmac import hashlib import requests # 配置信息 config = { 'baseUrl': 'https://api.fa-piao.com', 'appKey': 'YOUR_APP_KEY', 'appSecret': 'YOUR_SECRET_KEY', } def generate_random_string(length=16): """生成随机字符串""" characters = string.ascii_letters + string.digits return ''.join(random.choice(characters) for _ in range(length)) def calculate_signature(method, path, random_string, timestamp, app_key, app_secret): """计算HMAC-SHA256签名""" sign_content = f"Method={method}&Path={path}&RandomString={random_string}&TimeStamp={timestamp}&AppKey={app_key}" signature = hmac.new( app_secret.encode('utf-8'), sign_content.encode('utf-8'), hashlib.sha256 ).hexdigest() return signature.upper() def send_authorized_request(path, form_data): """发送带签名的请求""" method = 'POST' random_string = generate_random_string(20) timestamp = str(int(time.time())) signature = calculate_signature(method, path, random_string, timestamp, config['appKey'], config['appSecret']) headers = { 'AppKey': config['appKey'], 'Sign': signature, 'TimeStamp': timestamp, 'RandomString': random_string, } response = requests.post( url=config['baseUrl'] + path, files={k: (None, v.encode('utf-8')) for k, v in form_data.items()}, headers=headers, verify=False ) return response.json() # 使用示例 result = send_authorized_request('/v5/enterprise/authorization', {'nsrsbh': '915101820724315989'}) print(f"响应: {result}") ``` -------------------------------- ### Java 发票红冲 Demo Source: https://github.com/fapiaoapi/invoice/blob/master/README.md Java 8-16 示例代码,用于演示发票红冲功能。请确保已正确配置SDK。 ```Java /** * @author: fapiaoapi * @date: 2023/1/13 14:40 */ public class RedInvoiceExample { public static void main(String[] args) { // TODO Auto-generated method stub // 1.获取AppKey和AppSecret // 2.创建InvoiceClient实例 // 3.调用红冲接口 // 4.处理返回结果 } // TODO Auto-generated catch block // 异常处理 } ``` -------------------------------- ### Java 税额计算 Demo Source: https://github.com/fapiaoapi/invoice/blob/master/README.md Java 8-16 示例代码,用于演示税额计算功能。请确保已正确配置SDK。 ```Java /** * @author: fapiaoapi * @date: 2023/1/13 14:40 */ public class TaxExample { public static void main(String[] args) { // TODO Auto-generated method stub // 1.获取AppKey和AppSecret // 2.创建InvoiceClient实例 // 3.调用税额计算接口 // 4.处理返回结果 } // TODO Auto-generated catch block // 异常处理 } ``` -------------------------------- ### Java 发票开具 Demo Source: https://github.com/fapiaoapi/invoice/blob/master/README.md Java 8-16 示例代码,用于演示发票开具功能。请确保已正确配置SDK。 ```Java /** * @author: fapiaoapi * @date: 2023/1/13 14:40 */ public class BasicExample { public static void main(String[] args) { // TODO Auto-generated method stub // 1.获取AppKey和AppSecret // 2.创建InvoiceClient实例 // 3.调用开票接口 // 4.处理返回结果 } // TODO Auto-generated catch block // 异常处理 } ``` -------------------------------- ### HTML Frontend Mockup Source: https://github.com/fapiaoapi/invoice/blob/master/README.md 提供一个 HTML 文件,用于前端模拟发票相关页面的展示。 ```HTML fapiao.html ``` -------------------------------- ### C# 税额计算 Demo Source: https://github.com/fapiaoapi/invoice/blob/master/README.md C# 8-11 示例代码,用于演示税额计算功能。请确保已正确配置SDK。 ```C# using System; namespace TaxExample { class Program { static void Main(string[] args) { // TODO Auto-generated method stub // 1.获取AppKey和AppSecret // 2.创建InvoiceClient实例 // 3.调用税额计算接口 // 4.处理返回结果 } } } // TODO Auto-generated catch block // 异常处理 ``` -------------------------------- ### C# 发票红冲 Demo Source: https://github.com/fapiaoapi/invoice/blob/master/README.md C# 8-11 示例代码,用于演示发票红冲功能。请确保已正确配置SDK。 ```C# using System; namespace RedInvoiceExample { class Program { static void Main(string[] args) { // TODO Auto-generated method stub // 1.获取AppKey和AppSecret // 2.创建InvoiceClient实例 // 3.调用红冲接口 // 4.处理返回结果 } } } // TODO Auto-generated catch block // 异常处理 ``` -------------------------------- ### C# 发票开具 Demo Source: https://github.com/fapiaoapi/invoice/blob/master/README.md C# 8-11 示例代码,用于演示发票开具功能。请确保已正确配置SDK。 ```C# using System; namespace BasicExample { class Program { static void Main(string[] args) { // TODO Auto-generated method stub // 1.获取AppKey和AppSecret // 2.创建InvoiceClient实例 // 3.调用开票接口 // 4.处理返回结果 } } } // TODO Auto-generated catch block // 异常处理 ``` -------------------------------- ### Successful Invoice Response Source: https://github.com/fapiaoapi/invoice/blob/master/README.md Example of a successful API response for invoice processing. The 'data' object contains invoice details. ```json { "code": 200, "msg": "成功", "data": { "fphm": "2351200012312312385", "kprq": "2023-05-17 14:50:55", "xhdwsbh": "9151023213121K", "ghdwsbh": "913212312312313D8JX2", "xhdwmc": "四川 XXXXX 科技有限公司", "ghdwmc": "明 XXXXX 有限公司", "jshj": -10.0, "xxbbh": "5106032312312312601543" } } ``` -------------------------------- ### Get Face Image API Error Response Source: https://github.com/fapiaoapi/invoice/blob/master/README.md Error response for the 'getFaceImg' API, indicating a failure with a specific error message. ```json { "code": 999, "msg": "失败", "data": "销方税号有误", "total": 0 } ``` -------------------------------- ### 获取授权接口响应报文 Source: https://github.com/fapiaoapi/invoice/blob/master/README.md 此响应报文展示了成功获取授权后返回的token,用于后续的API调用。 ```json { "code": 200, "data": { "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3NDQxMTQ4NTAsImlhdCI6MTc0NDExNDczMCwiaXNzIjoieXVlMDA1IiwibnNyc2JoIjoiOTI1MDAxMDNNQUQ3RjhIMTdEIiwidHlwZSI6IjEifQ.p__oAUSdVdA9inkuqvVYisjfxBIMzxGPkoMDuZ7hy04" }, "msg": "成功", "total": 0 } ``` -------------------------------- ### Get Face Recognition Status API Source: https://github.com/fapiaoapi/invoice/blob/master/README.md This API endpoint is used to check the status of a face recognition authentication process initiated by a QR code. ```APIDOC ## POST /v5/enterprise/getFaceState ### Description This endpoint allows you to query the status of a face recognition authentication process using a previously obtained authentication ID (rzid). ### Method GET ### Endpoint https://api.fa-piao.com/v5/enterprise/getFaceState ### Parameters #### Query Parameters - **username** (string) - Optional - User's e-ticket platform account. If provided, it overrides the default account. If not provided, the default account maintained by the management side is used. - **nsrsbh** (string) - Required - Taxpayer identification number. - **rzid** (string) - Required - Authentication ID obtained from the getFaceImg endpoint. - **type** (string) - Optional - If set to '2', it queries the status for personal income tax QR code authentication. Otherwise, it queries the status for the tax bureau app. ### Request Example ```json { "nsrsbh": "915101820724315989", "rzid": "5246703dc22842b5a3d7826f375e6c7d" } ``` ### Response #### Success Response (200) - **code** (int) - API return code. 200 indicates success. - **msg** (string) - API return message. Indicates success or failure. - **data** (object) - Contains the authentication status details. - **rzid** (string) - Authentication ID. - **nsrsbh** (string) - Taxpayer identification number. - **ewm** (string) - QR code data or identifier. The format may vary based on the 'type' parameter. - **slzt** (string) - Acceptance status. - **ewmly** (string) - QR code source (e.g., 'swj' for tax bureau app, 'grsds' for personal income tax app). #### Response Example ```json { "code": 200, "msg": "成功", "data": { "rzid": "5246703dc22842b5a3d7826f375e6c7d", "nsrsbh": "9151123123122031211", "ewm": "qrcode_id=gYyixYMScMK4GQc2LfzqvKVnk33kJHs7p5wnpig3QdYFAdAvmDp7i7Yobk7zzkNM&areaPrefix=5100&interfaceCode=0004", "slzt": null, "ewmly": "swj" }, "total": 0 } ``` #### Error Response Example ```json { "code": 999, "msg": "失败", "data": "销方税号有误", "total": 0 } ``` ``` -------------------------------- ### Java - 发票金额计算 Source: https://context7.com/fapiaoapi/invoice/llms.txt 使用Java计算发票的税额,支持含税和不含税两种模式。所有金额保留2位小数,单价保留最多13位小数。 ```java // Java示例 - 发票金额计算 import java.math.BigDecimal; import java.math.RoundingMode; public class TaxCalculator { /** * 计算税额 * @param amount 金额 * @param taxRate 税率 * @param isIncludeTax 是否含税 * @return 税额 */ public static BigDecimal calculateTax(BigDecimal amount, BigDecimal taxRate, boolean isIncludeTax) { if (taxRate == null || taxRate.compareTo(BigDecimal.ZERO) <= 0) { return BigDecimal.ZERO; } BigDecimal tax; if (isIncludeTax) { // 含税计算:税额 = 1/(1+税率) × 税率 × 含税金额 tax = BigDecimal.ONE .divide(BigDecimal.ONE.add(taxRate), 10, RoundingMode.HALF_UP) .multiply(taxRate) .multiply(amount) .setScale(2, RoundingMode.HALF_UP); } else { // 不含税计算:税额 = 金额 × 税率 tax = amount.multiply(taxRate).setScale(2, RoundingMode.HALF_UP); } return tax; } public static void main(String[] args) { // 含税示例:购买服务1000元,税率1% BigDecimal amount = new BigDecimal("1000"); BigDecimal taxRate = new BigDecimal("0.01"); // 含税计算 BigDecimal taxIncluded = calculateTax(amount, taxRate, true); BigDecimal amountExcludingTax = amount.subtract(taxIncluded); System.out.println("含税金额: " + amount); System.out.println("税额: " + taxIncluded); // 输出: 9.90 System.out.println("不含税金额: " + amountExcludingTax); // 输出: 990.10 // 不含税计算 BigDecimal taxExcluded = calculateTax(amount, taxRate, false); BigDecimal totalWithTax = amount.add(taxExcluded); System.out.println("\n不含税金额: " + amount); System.out.println("税额: " + taxExcluded); // 输出: 10.00 System.out.println("价税合计: " + totalWithTax); // 输出: 1010.00 } } ``` -------------------------------- ### Switch Taxpayer Identification Number Response Example Source: https://github.com/fapiaoapi/invoice/blob/master/README.md Standard response structure for the switch taxpayer identification number operation. Indicates success or failure with a message. ```json { "code": 200, "msg": "成功" } { "code": 999, "msg": "电子税务局身份不可为空" } ``` -------------------------------- ### POST /v5/enterprise/authorization - Get Authorization Token Source: https://github.com/fapiaoapi/invoice/blob/master/README.md This endpoint is used to obtain an authorization token required for subsequent API requests. It supports POST requests with form-data encoding. ```APIDOC ## POST /v5/enterprise/authorization ### Description Obtains an authorization token for accessing the 数电发票 API. ### Method POST ### Endpoint https://api.fa-piao.com/v5/enterprise/authorization ### Parameters #### Query Parameters - **nsrsbh** (String) - Required - Taxpayer identification number. - **type** (String) - Optional - Account type (6 for basic, 7 for standard). - **username** (String) - Optional - Account username. - **password** (String) - Optional - Account password. ### Request Example ```json { "nsrsbh": "915101820724315989" } ``` ### Response #### Success Response (200) - **code** (int) - API return code. 200 indicates success. - **msg** (String) - API return message (e.g., "Success" or "Failure"). - **data** (Object) - Contains the authorization token. - **token** (String) - The authorization token. This should be passed in the `Authorization` header for public requests. #### Response Example ```json { "code": 200, "data": { "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3NDQxMTQ4NTAsImlhdCI6MTc0NDExNDczMCwiaXNzIjoieXVlMDA1IiwibnNyc2JoIjoiOTI1MDAxMDNNQUQ3RjhIMTdEIiwidHlwZSI6IjEifQ.p__oAUSdVdA9inkuqvVYisjfxBIMzxGPkoMDuZ7hy04" }, "msg": "成功", "total": 0 } ``` ``` -------------------------------- ### Download Invoice Files (PDF/OFD/XML) Source: https://context7.com/fapiaoapi/invoice/llms.txt This Python code snippet shows how to download invoice files in PDF, OFD, or XML formats after successful issuance. The `downflag` parameter specifies the desired format, and the function handles saving the content to local files. ```python import requests import base64 def download_invoice_file(token, nsrsbh, username, fphm, kprq, downflag='4'): """ 下载发票文件 :param token: 授权Token :param nsrsbh: 纳税人识别号 :param username: 电子税务局用户名 :param fphm: 发票号码 :param kprq: 开票日期 :param downflag: 下载标志 1-PDF 2-OFD 3-XML 4-全部 """ config = { 'baseUrl': 'https://api.fa-piao.com', 'appKey': 'YOUR_APP_KEY', 'appSecret': 'YOUR_SECRET_KEY', } path = '/v5/enterprise/pdfOfdXml' form_data = { 'downflag': downflag, 'nsrsbh': nsrsbh, 'username': username, 'fphm': fphm, 'kprq': kprq, # 格式: 2024-01-15 } random_string = generate_random_string(20) timestamp = str(int(time.time())) signature = calculate_signature('POST', path, random_string, timestamp, config['appKey'], config['appSecret']) headers = { 'AppKey': config['appKey'], 'Sign': signature, 'TimeStamp': timestamp, 'RandomString': random_string, 'Authorization': f'Bearer {token}', } response = requests.post( url=config['baseUrl'] + path, files={k: (None, v.encode('utf-8')) for k, v in form_data.items()}, headers=headers, verify=False ) result = response.json() if result['code'] == 200: data = result['data'] # 保存PDF文件 if 'pdfUrl' in data: print(f"PDF下载链接: {data['pdfUrl']}") if 'pdfBase64' in data: pdf_content = base64.b64decode(data['pdfBase64']) with open(f'{fphm}.pdf', 'wb') as f: f.write(pdf_content) print(f"PDF已保存: {fphm}.pdf") # 保存OFD文件 if 'ofdUrl' in data: print(f"OFD下载链接: {data['ofdUrl']}") # 保存XML文件 if 'xmlUrl' in data: print(f"XML下载链接: {data['xmlUrl']}") return data else: print(f"下载失败: {result['msg']}") return None ``` -------------------------------- ### Blue Ticket Issuance Response Source: https://github.com/fapiaoapi/invoice/blob/master/README.md Example response for the digital blue ticket issuance interface. Indicates success with a 200 code and provides an encoded data string. ```json { "code": 200, "msg": "成功", "data": "eyJZampiIjoiMDEiLCJTeGxiIjoiMyIsIlNmc2wiOiJZIiwiSXRzU2NhbkZsYWciOiJOIn0=", "total": 0 } ``` -------------------------------- ### POST /v5/enterprise/loginDppt - Login to 数电发票 Platform Source: https://github.com/fapiaoapi/invoice/blob/master/README.md This endpoint allows users to log in to the 数电发票 platform. It supports POST requests with form-data encoding and handles various login methods including SMS verification and QR code scanning. ```APIDOC ## POST /v5/enterprise/loginDppt ### Description Logs into the 数电发票 platform. This endpoint supports various authentication methods. ### Method POST ### Endpoint https://api.fa-piao.com/v5/enterprise/loginDppt ### Parameters #### Query Parameters - **nsrsbh** (String) - Required - Taxpayer identification number. - **username** (String) - Required - User's e-invoice platform account. - **password** (String) - Required - User's e-invoice platform password. - **sms** (String) - Optional - Verification code. If not provided on the first call, a verification code will be sent. On subsequent calls, provide the code to log in and receive a UUID. - **sf** (String) - Optional - Identity type for the electronic tax bureau (01: Legal Representative, 02: Financial Controller, 03: Tax Agent, 05: Administrator, 08: Social Security Agent, 09: Invoice Issuer, 10: Salesperson). - **ewmlx** (String) - Optional - QR code login type (1: Tax Face QR Code Login, 10: Tax App Scan QR Code Login, 2: Personal Income Tax Face QR Code Login, 3: Personal Income Tax App Scan Confirmation Login). - **ewmid** (String) - Optional - Used in the second call for QR code login. The first call only requires `ewmlx` and will return `ewmid` and a QR code. Subsequent calls must use the same `ewmlx` value and the returned `ewmid`. ### Request Example ```json { "nsrsbh": "915101820724315989", "username": "123213123", "password": "1231241241412421124", "sms": "" } ``` ### Response #### Success Response (200) - **code** (int) - API return code. 200 indicates success. - **msg** (String) - API return message. For example, "Verification code has been sent to mobile number: 176****2696". - **data** (Object) - Response data. For the first QR code login call, this may contain `ewmid` and the QR code in base64 format. #### Response Example (SMS Sent) ```json { "code": 200, "msg": "验证码已发送到手机号:176****2696" } ``` #### Response Example (QR Code First Call) ```json { "code": 200, "data": { "ewmid": "some_uuid_from_first_call", "qrCode": "base64_encoded_qr_code_string" }, "msg": "请扫描二维码登录" } ``` ``` -------------------------------- ### Get Face Image API Success Response Source: https://github.com/fapiaoapi/invoice/blob/master/README.md Correct status response for the 'getFaceImg' API. Includes authentication ID ('rzid'), taxpayer ID ('nsrsbh'), and QR code details ('ewm'). ```json { "code": 200, "msg": "成功", "data": { "rzid": "5246703dc22842b5a3d7826f375e6c7d", "nsrsbh": "9151123123122031211", "ewm": "qrcode_id=gYyixYMScMK4GQc2LfzqvKVnk33kJHs7p5wnpig3QdYFAdAvmDp7i7Yobk7zzkNM&areaPrefix=5100&interfaceCode=0004", "slzt": null, "emwly": "swj" }, "total": 0 } ```