### New User Quick Start Guide Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/README.md Follow these steps to quickly get started with the SDK. This includes reading the main index, following the quick start guide, and then diving into other documentation for deeper learning. ```markdown 1. 阅读 INDEX.md 2. 跟随 06-quick-start.md 快速上手 3. 参考其他文档进行深入学习 ``` -------------------------------- ### Install BsPay Go SDK Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/00-START-HERE.md Clone or download the SDK using the go get command. Refer to the quick start guide for further setup. ```bash # 克隆或下载SDK go get github.com/huifurepo/bspay-go-sdk/BsPaySdk # 按照快速开始指南 # 👉 [打开快速开始指南](06-quick-start.md) ``` -------------------------------- ### Example Configuration File (No Keys) Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/04-configuration.md Provide an example configuration file that omits sensitive key information, serving as a template for users. ```json { "product_id": "YOUR_PRODUCT_ID_HERE", "sys_id": "YOUR_SYS_ID_HERE", "rsa_merch_private_key": "YOUR_PRIVATE_KEY_HERE", "rsa_huifu_public_key": "YOUR_PUBLIC_KEY_HERE" } ``` -------------------------------- ### Example of Correct JSON Configuration Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/07-errors-and-faq.md This is an example of a correctly formatted JSON configuration file for the SDK. ```json { "product_id": "10000001", "sys_id": "SYS_0001", "rsa_merch_private_key": "-----BEGIN RSA PRIVATE KEY-----\nMII...\n-----END RSA PRIVATE KEY-----", "rsa_huifu_public_key": "-----BEGIN PUBLIC KEY-----\nMII...\n-----END PUBLIC KEY-----" } ``` -------------------------------- ### Initialize SDK and Perform Operations Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/06-quick-start.md This example demonstrates initializing the bspay-go-sdk with a configuration file and performing sample operations such as querying bank balance and creating a bill. Ensure the configuration file path is correct and the necessary parameters are provided for each API call. ```go package main import ( "fmt" "log" "time" "github.com/huifurepo/bspay-go-sdk/BsPaySdk" ) var sdk *BsPaySdk.BsPay func init() { var err error sdk, err = BsPaySdk.NewBsPay(false, "./config/config.json") if err != nil { log.Fatalf("SDK初始化失败: %v", err) } } func generateReqSeqId() string { return fmt.Sprintf("REQ_%d", time.Now().UnixNano()) } func getDate() string { return time.Now().Format("20060102") } func queryBalance() error { req := BsPaySdk.V2BankBalanceQueryRequest{ ReqSeqId: generateReqSeqId(), ReqDate: getDate(), HuifuId: "6666000108854952", } resp, err := sdk.V2BankBalanceQueryRequest(req) if err != nil { return err } fmt.Printf("余额查询结果: %v\n", resp) return nil } func createBill() error { req := BsPaySdk.V2BillEntCreateRequest{ ReqSeqId: generateReqSeqId(), ReqDate: getDate(), HuifuId: "6666000108854952", PayerId: "payer_001", BillName: "测试账单", BillAmt: "100.00", SupportPayType: "01", BillEndDate: "20240131", PayeeInfo: "payee", } resp, err := sdk.V2BillEntCreateRequest(req) if err != nil { return err } fmt.Printf("账单创建结果: %v\n", resp) return nil } func main() { // 查询余额 if err := queryBalance(); err != nil { log.Printf("查询余额失败: %v", err) } // 创建账单 if err := createBill(); err != nil { log.Printf("创建账单失败: %v", err) } } ``` -------------------------------- ### Reusing SDK Instance for Performance Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/02-api-methods.md To improve performance, create a global or long-lived SDK instance instead of initializing it frequently. This example shows how to initialize the SDK once and reuse the instance. ```go var sdkInstance *BsPaySdk.BsPay func init() { sdkInstance, _ = BsPaySdk.NewBsPay(false, "./config/config.json") } func someFunction() { resp, _ := sdkInstance.V2BankBalanceQueryRequest(req) } ``` -------------------------------- ### Multi-Merchant Initialization and Usage Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/01-core-modules.md Example demonstrating how to initialize and use multiple BsPay SDK instances for concurrent multi-merchant support. Each instance is configured with a separate merchant configuration file. ```go // 商户A sdkA, _ := BsPaySdk.NewBsPay(false, "./config/merchant_a.json") // 商户B sdkB, BsPaySdk.NewBsPay(false, "./config/merchant_b.json") // 分别使用各自的SDK实例进行API调用 respA, _ := sdkA.V2BankBalanceQueryRequest(reqA) respB, _ := sdkB.V2BankBalanceQueryRequest(reqB) ``` -------------------------------- ### Reuse SDK Instance for Performance in Go Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/07-errors-and-faq.md Avoid repeated SDK initialization for performance. Initialize the SDK once and reuse the instance for multiple requests. This example shows the incorrect and correct approaches. ```go // ❌ 错误:重复初始化 for i := 0; i < 1000; i++ { sdk, _ := BsPaySdk.NewBsPay(false, "./config/config.json") resp, _ := sdk.V2BankBalanceQueryRequest(req) } // ✅ 正确:复用实例 sdk, _ := BsPaySdk.NewBsPay(false, "./config/config.json") for i := 0; i < 1000; i++ { resp, _ := sdk.V2BankBalanceQueryRequest(req) } ``` -------------------------------- ### Example .gitignore for Configuration Files Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/04-configuration.md Use a .gitignore file to prevent sensitive configuration files from being committed to version control. Exclude all JSON files in the config directory except for example files. ```gitignore config/*.json !config/*.example.json ``` -------------------------------- ### Environment Selection Guide Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/01-core-modules.md Guidance on selecting between test and production environments. ```APIDOC ## Environment Selection Guide ### Test Environment (IsProdMode = false) ```go sdk, _ := BsPaySdk.NewBsPay(false, "./config/config.json") ``` **Characteristics**: - Uses URL: `https://spin-test.cloudpnr.com` - For development and testing - Does not generate real transactions ### Production Environment (IsProdMode = true) ```go sdk, _ := BsPaySdk.NewBsPay(true, "./config/config.json") ``` **Characteristics**: - Uses URL: `https://api.huifu.com` - For production deployment - Generates real transactions; use with caution. ``` -------------------------------- ### Problem Troubleshooting Steps Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/README.md If you encounter issues, start by examining the error messages. Consult the errors and FAQ document for common problems and solutions. If necessary, refer to relevant documentation for more details. ```markdown 1. 查看错误信息 2. 在 07-errors-and-faq.md 中查找 3. 如有必要参考相关的参考文档 ``` -------------------------------- ### JSON Configuration Format Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/01-core-modules.md Example structure for the JSON configuration file. It requires product ID, system ID, and RSA merchant private and Huifu public keys in PEM format. The SDK handles missing PEM header/footer tags. ```json { "product_id": "您的产品ID", "sys_id": "您的系统ID", "rsa_merch_private_key": "-----BEGIN RSA PRIVATE KEY-----\n...\n-----END RSA PRIVATE KEY-----", "rsa_huifu_public_key": "-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----" } ``` -------------------------------- ### Set Environment Variables for BSPay SDK Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/04-configuration.md Configure the BSPay SDK by setting environment variables for the environment and configuration file path. This example shows how to use a .env file and read these variables in Go. ```bash # .env 文件(示例,不应提交到版本控制) export BSPAY_ENV=test # 或 production export BSPAY_CONFIG_PATH=./config/config.json ``` ```go import "os" func getSDK() *BsPaySdk.BsPay { env := os.Getenv("BSPAY_ENV") if env == "" { env = "test" } configPath := os.Getenv("BSPAY_CONFIG_PATH") if configPath == "" { configPath = "./config/config.json" } isProd := env == "production" sdk, _ := BsPaySdk.NewBsPay(isProd, configPath) return sdk } ``` -------------------------------- ### V2FlexibleEntRequest Method Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/02-api-methods.md Represents the request structure for onboarding enterprise merchants into the flexible payment system. This method is used for merchant account creation and setup. ```go V2FlexibleEntRequest ``` -------------------------------- ### Initialize SDK, Build Request, and Call API Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/00-START-HERE.md Demonstrates the three fundamental steps for interacting with the SDK: initializing the SDK instance, constructing a request object, and invoking an API method. Ensure the configuration path is correct. ```go // 1. Initialize sdk, _ := BsPaySdk.NewBsPay(false, "./config/config.json") // 2. Build Request req := BsPaySdk.V2BankBalanceQueryRequest{...} // 3. Call API resp, err := sdk.V2BankBalanceQueryRequest(req) ``` -------------------------------- ### Initialize SDK for Production Environment Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/README.md Use this to initialize the SDK for the production environment. This will produce real transactions, so use with caution. ```go BsPaySdk.NewBsPay(true, configPath) ``` -------------------------------- ### Multi-Environment Configuration with Environment Variables Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/04-configuration.md Sets up a flexible multi-environment configuration by reading environment flags and configuration paths from environment variables. Initializes the SDK based on these settings. ```go package main import ( "os" "github.com/huifurepo/bspay-go-sdk/BsPaySdk" "log" ) var globalSDK *BsPaySdk.BsPay func init() { // 从环境变量获取环境标志 env := os.Getenv("BSPAY_ENV") isProd := env == "production" // 从环境变量获取配置文件路径 configPath := os.Getenv("BSPAY_CONFIG") if configPath == "" { if isProd { configPath = "./config/prod.json" } else { configPath = "./config/test.json" } } // 初始化SDK sdk, err := BsPaySdk.NewBsPay(isProd, configPath) if err != nil { log.Fatalf("Failed to initialize BsPay SDK: %v", err) } globalSDK = sdk } func main() { // 使用全局SDK实例 // ... } ``` -------------------------------- ### V2CouponShopdealQueryRequest Go Type Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/03-types.md Defines the structure for querying Meituan non-dining group purchase information. Use this to get details on group deals. ```go type V2CouponShopdealQueryRequest struct { ReqSeqId string // json: "req_seq_id" ReqDate string // json: "req_date" ExtendInfos map[string]interface{} // json: "extend_infos" } ``` -------------------------------- ### Initialize BsPay SDK Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/00-START-HERE.md Initialize the SDK with a configuration file. Ensure the configuration file path is correct. ```go sdk, err := BsPaySdk.NewBsPay(false, "./config/config.json") ``` -------------------------------- ### View SDK Signature Check Log Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/07-errors-and-faq.md The SDK logs signature check errors, which can be helpful for debugging. This example shows the expected log message format. ```go // SDK会输出: // BspayPrintln("check sign error: " + err.Error()) ``` -------------------------------- ### Create Enterprise Bill with bspay-go-sdk Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/06-quick-start.md Demonstrates how to initialize the SDK and create an enterprise bill. Ensure your configuration file is correctly set up. ```go package main import ( "fmt" "log" "time" "github.com/huifurepo/bspay-go-sdk/BsPaySdk" ) func generateReqSeqId() string { return fmt.Sprintf("REQ_%d", time.Now().UnixNano()) } func main() { // 初始化SDK sdk, err := BsPaySdk.NewBsPay(false, "./config/config.json") if err != nil { log.Fatalf("初始化失败: %v", err) } // 构建创建账单请求 req := BsPaySdk.V2BillEntCreateRequest{ ReqSeqId: generateReqSeqId(), ReqDate: time.Now().Format("20060102"), HuifuId: "6666000108854952", PayerId: "payer_001", BillName: "2024年度账单", BillAmt: "10000.00", SupportPayType: "01", BillEndDate: "20240131", PayeeInfo: "payee_info", } // 设置扩展字段(可选) req.ExtendInfos = make(map[string]interface{}) req.ExtendInfos["custom_field"] = "custom_value" // 调用API resp, err := sdk.V2BillEntCreateRequest(req) if err != nil { log.Printf("创建账单失败: %v", err) return } fmt.Printf("账单创建成功: %v\n", resp) } ``` -------------------------------- ### Initialize SDK for Test Environment Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/README.md Use this to initialize the SDK for the test environment. It does not produce real transactions. ```go BsPaySdk.NewBsPay(false, configPath) ``` -------------------------------- ### Initialize SDK for Production Environment Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/06-quick-start.md Use this snippet to initialize the SDK for the production environment. Ensure your production configuration file is correctly specified. ```go sdk, _ := BsPaySdk.NewBsPay(true, "./config/prod.json") // 使用生产服务器: https://api.huifu.com ``` -------------------------------- ### Initialize BSPay SDK Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/README.md Initialize the SDK with environment (production/test) and configuration details. The configuration file should contain merchant keys. ```go dgSDK, _ := BsPaySdk.NewBsPay(false, "./config/config.json") ``` -------------------------------- ### Handle API Errors Gracefully Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/06-quick-start.md Implement robust error handling for API calls. This example shows how to categorize and log different types of errors, such as context cancellation or timeouts. ```go package main import ( "errors" "log" ) func callAPI(sdk *BsPaySdk.BsPay, req interface{}) (map[string]interface{}, error) { // API调用 resp, err := sdk.V2BankBalanceQueryRequest(req.(BsPaySdk.V2BankBalanceQueryRequest)) if err != nil { // 分类处理错误 if errors.Is(err, context.Canceled) { log.Println("请求被取消") } else if errors.Is(err, context.DeadlineExceeded) { log.Println("请求超时") } else { log.Printf("API错误: %v", err) } return nil, err } return resp, nil } ``` -------------------------------- ### Initialize SDK for Test or Production Environment Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/07-errors-and-faq.md Demonstrates how to initialize the BsPay SDK for either the test or production environment by setting the `isProdMode` parameter correctly. ```go // 确保使用了正确的isProdMode参数 sdk, _ := BsPaySdk.NewBsPay(false, "./config/config.json") // 测试环境 // 或 sdk, _ := BsPaySdk.NewBsPay(true, "./config/config.json") // 生产环境 ``` -------------------------------- ### Create Configuration File Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/00-START-HERE.md Define the SDK configuration in a JSON file. Include necessary fields like product ID, system ID, and private/public keys. ```json { "product_id": "...", "sys_id": "...", "rsa_merch_private_key": "...", "rsa_huifu_public_key": "..." } ``` -------------------------------- ### Generate Request Tracing ID in Go Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/07-errors-and-faq.md Use a unique request sequence ID to trace specific requests. This example shows how to generate one using the order ID and current timestamp. ```go func generateTracingSeqId(orderID string) string { return fmt.Sprintf("ORDER_%s_%d", orderID, time.Now().UnixNano()) } req := BsPaySdk.V2BillEntCreateRequest{ ReqSeqId: generateTracingSeqId("ORDER_123456"), // ... } // 日志中包含流水号,便于追踪 log.Printf("创建账单,流水号: %s", req.ReqSeqId) ``` -------------------------------- ### Global SDK Instance Pattern Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/INDEX.md Demonstrates how to create a single, global instance of the SDK to be reused across the application. Initialization is typically done in an init function. ```go var sdkInstance *BsPaySdk.BsPay func init() { sdkInstance, _ = BsPaySdk.NewBsPay(false, "./config/config.json") } ``` -------------------------------- ### Dynamic Path Configuration from Environment Variable Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/04-configuration.md Initialize the SDK using a configuration file path read from the BSPAY_CONFIG_PATH environment variable, with a fallback to a default relative path. ```go import "os" // 从环境变量读取 configPath := os.Getenv("BSPAY_CONFIG_PATH") if configPath == "" { configPath = "./config/config.json" // 默认路径 } sdk, _ := BsPaySdk.NewBsPay(false, configPath) ``` -------------------------------- ### Handle Large Amounts with String Type in Go Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/07-errors-and-faq.md To avoid precision issues with large monetary values, use the string type for amount fields. This example demonstrates the correct and incorrect ways to handle amounts. ```go // ✅ 正确的做法 req := BsPaySdk.V2BillEntCreateRequest{ BillAmt: "123456789.99", // 使用字符串 } // ❌ 错误的做法(可能丢失精度) amount := 123456789.99 req.BillAmt = strconv.FormatFloat(amount, 'f', -1, 64) ``` -------------------------------- ### API Development Workflow Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/README.md For API development, locate the desired API in the API methods document. Understand the data structures using the types document, check endpoints in the endpoints document, and review example code for implementation guidance. ```markdown 1. 在 02-api-methods.md 中找到API 2. 查看 03-types.md 了解结构 3. 参考 05-endpoints.md 查看端点 4. 查看示例代码 ``` -------------------------------- ### Initialize SDK and Call API Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/02-api-methods.md Demonstrates the standard workflow for initializing the BsPay SDK, creating a request object for a specific API (V2BankBalanceQueryRequest), optionally setting extended fields, calling the API, and handling the response. ```go // 1. Initialize SDK sdk, err := BsPaySdk.NewBsPay(false, "./config/config.json") if err != nil { log.Fatal(err) } // 2. Create request object req := BsPaySdk.V2BankBalanceQueryRequest{ ReqSeqId: "unique_request_id_001", ReqDate: "20240101", HuifuId: "merchant_id", } // 3. Optional: Set extended fields req.ExtendInfos = map[string]interface{}{ "optional_field_1": "value1", "optional_field_2": "value2", } // 4. Call API resp, err := sdk.V2BankBalanceQueryRequest(req) if err != nil { // Handle error log.Printf("API call failed: %v", err) return } // 5. Handle response if respData, ok := resp["data"].(map[string]interface{}); ok { // Parse business data returned } ``` -------------------------------- ### Initialize SDK for Development Environment Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/06-quick-start.md Use this snippet to initialize the SDK for the testing environment. Ensure your test configuration file is correctly specified. ```go sdk, _ := BsPaySdk.NewBsPay(false, "./config/test.json") // 使用测试服务器: https://spin-test.cloudpnr.com ``` -------------------------------- ### Initialize Production Environment SDK Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/04-configuration.md Initializes the SDK for the production environment using a specified configuration file. This environment uses production API URLs and performs real transactions; use with caution. ```go import "github.com/huifurepo/bspay-go-sdk/BsPaySdk" func main() { // 初始化生产环境SDK sdk, err := BsPaySdk.NewBsPay(true, "./config/config.json") if err != nil { log.Fatalf("SDK初始化失败: %v", err) } // SDK会使用生产环境URL // https://api.huifu.com } ``` -------------------------------- ### Initialize SDK for Test Environment (Go) Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/01-core-modules.md Initializes the SDK for the test environment using a specified configuration file. This mode uses a test API URL and does not process real transactions. ```go sdk, _ := BsPaySdk.NewBsPay(false, "./config/config.json") ``` -------------------------------- ### Initialize SDK for Test Environment Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/INDEX.md Initializes the BsPay SDK for the test environment. Ensure the correct configuration path is provided. ```go NewBsPay(false, configPath) ``` -------------------------------- ### Relative Path Configuration Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/04-configuration.md Initialize the SDK using a configuration file path relative to the working directory. ```go // 相对于工作目录的路径 sdk, _ := BsPaySdk.NewBsPay(false, "./config/config.json") sdk, _ := BsPaySdk.NewBsPay(false, "../config/config.json") ``` -------------------------------- ### Initialize SDK for Production Environment Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/INDEX.md Initializes the BsPay SDK for the production environment. Ensure the correct configuration path is provided. ```go NewBsPay(true, configPath) ``` -------------------------------- ### Absolute Path Configuration Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/04-configuration.md Initialize the SDK using an absolute path to the configuration file, derived from the executable's directory. ```go import "path/filepath" import "os" // 获取可执行文件所在目录 exePath, _ := os.Executable() exeDir := filepath.Dir(exePath) configPath := filepath.Join(exeDir, "config", "config.json") sdk, _ := BsPaySdk.NewBsPay(false, configPath) ``` -------------------------------- ### Initialize Test Environment SDK Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/04-configuration.md Initializes the SDK for the test environment using a specified configuration file. This environment uses test API URLs and does not perform real transactions. ```go import "github.com/huifurepo/bspay-go-sdk/BsPaySdk" func main() { // 初始化测试环境SDK sdk, err := BsPaySdk.NewBsPay(false, "./config/config.json") if err != nil { log.Fatalf("SDK初始化失败: %v", err) } // SDK会使用测试环境URL // https://spin-test.cloudpnr.com } ``` -------------------------------- ### Basic API Call Pattern Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/INDEX.md Demonstrates a basic pattern for initializing the SDK and making an API request. Ensure the request struct is properly populated. ```go sdk, _ := BsPaySdk.NewBsPay(false, "./config/config.json") req := BsPaySdk.V2BankBalanceQueryRequest{...} resp, err := sdk.V2BankBalanceQueryRequest(req) ``` -------------------------------- ### Support Multiple Merchants with SDK Instances Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/06-quick-start.md Illustrates how to manage multiple merchant configurations by creating separate SDK instances. This is useful when your application needs to interact with the bspay system on behalf of different merchants. ```go var ( sdkA *BsPaySdk.BsPay sdkB *BsPaySdk.BsPay ) func init() { sdkA, _ = BsPaySdk.NewBsPay(false, "./config/merchant_a.json") sdkB, _ = BsPaySdk.NewBsPay(false, "./config/merchant_b.json") } func queryBalanceForMerchantA() { resp, _ := sdkA.V2BankBalanceQueryRequest(...) } func queryBalanceForMerchantB() { resp, _ := sdkB.V2BankBalanceQueryRequest(...) } ``` -------------------------------- ### Initialize BsPay SDK Instance Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/01-core-modules.md Initializes the BsPay SDK instance, which is the first step to using the SDK. It requires specifying the environment mode (production or test) and the path to the configuration file. ```go package main import ( "github.com/huifurepo/bspay-go-sdk/BsPaySdk" "log" ) func main() { // 初始化SDK - 测试环境 sdk, err := BsPaySdk.NewBsPay(false, "./config/config.json") if err != nil { log.Fatalf("SDK初始化失败: %v", err) } // 初始化SDK - 生产环境 prodSdk, err := BsPaySdk.NewBsPay(true, "./config/config.json") if err != nil { log.Fatalf("SDK初始化失败: %v", err) } } ``` -------------------------------- ### Initialize SDK for Multiple Merchants Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/00-START-HERE.md Support multiple merchants by initializing separate SDK instances, each with its own configuration file. ```go sdkA, _ := BsPaySdk.NewBsPay(false, "./config/merchant_a.json") sdkB, _ := BsPaySdk.NewBsPay(false, "./config/merchant_b.json") ``` -------------------------------- ### 记录和调试SDK操作 Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/07-errors-and-faq.md SDK内置日志输出功能,会打印初始化、请求、响应及错误信息。可自定义日志记录方式,例如通过包装SDK实现。 ```go // SDK 会通过 BspayPrintln() 输出日志: // - SDK初始化日志 // - 请求URL // - 请求数据 // - 响应数据 // - 错误信息 // 如果需要自定义日志,可以监听标准输出或修改源码 // 或者包装SDK: type LoggedBsPay struct { sdk *BsPaySdk.BsPay } func (lb *LoggedBsPay) V2BankBalanceQueryRequest(req BsPaySdk.V2BankBalanceQueryRequest) (map[string]interface{}, error) { log.Printf("调用: V2BankBalanceQueryRequest, 参数: %+v", req) resp, err := lb.sdk.V2BankBalanceQueryRequest(req) log.Printf("响应: %v, 错误: %v", resp, err) return resp, err } ``` -------------------------------- ### Call API Method Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/00-START-HERE.md Make an API request using the initialized SDK instance. Refer to the API methods documentation for specific request structures. ```go resp, err := sdk.V2BankBalanceQueryRequest(req) ``` -------------------------------- ### Basic Configuration JSON Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/04-configuration.md Standard JSON configuration including product ID, system ID, and RSA keys with BEGIN/END markers. ```json { "product_id": "10000001", "sys_id": "SYS_0001", "rsa_merch_private_key": "-----BEGIN RSA PRIVATE KEY-----\nMIIEpAIBAAKCAQEA2Z3qX2BTLMYDEyUlQ...\n-----END RSA PRIVATE KEY-----", "rsa_huifu_public_key": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A\n-----END PUBLIC KEY-----" } ``` -------------------------------- ### Initialize SDK with Absolute Path Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/07-errors-and-faq.md Initialize the BsPay SDK using an absolute path for the configuration file, which can help resolve path-related errors. ```go import "os/user" import "path/filepath" usr, _ := user.Current() configPath := filepath.Join(usr.HomeDir, "config", "config.json") sdk, _ := BsPaySdk.NewBsPay(false, configPath) ``` -------------------------------- ### SDK自动处理加签与验签 Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/07-errors-and-faq.md SDK会自动处理请求的RSA加签和响应的RSA验签,开发者无需手动干预。如需手动操作,可调用 `RsaSign` 和 `RsaSignVerify` 函数。 ```go // SDK 内部自动处理: // 1. 对请求数据进行RSA加签 // 2. 发送带签名的请求 // 3. 验证响应的RSA签名 // 4. 返回验证后的结果 // 开发者只需关注业务逻辑 resp, err := sdk.V2BankBalanceQueryRequest(req) // 手动加签 content := "要签名的内容" signature, err := BsPaySdk.RsaSign(content, msc) // 手动验签 isValid, err := BsPaySdk.RsaSignVerify(signature, content, msc) ``` -------------------------------- ### General API Request Flow (Go) Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/01-core-modules.md Outlines the typical steps for making an API call using the SDK, including SDK initialization, request object construction, setting optional fields, sending the request, and handling the response. ```go sdk, err := BsPaySdk.NewBsPay(isProdMode, configPath) ``` ```go req := BsPaySdk.V2SomeRequest{ ReqSeqId: "唯一流水号", ReqDate: "请求日期", // ... 其他必填字段 } ``` ```go req.ExtendInfos = map[string]interface{}{ "optional_field": "value", } ``` ```go resp, err := sdk.V2SomeRequest(req) ``` ```go if err != nil { // 处理错误 } else { // 处理返回结果 } ``` -------------------------------- ### 支持多商户配置 Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/07-errors-and-faq.md 为每个商户创建独立的SDK实例,并使用各自的配置文件进行初始化。这确保了不同商户的请求隔离和配置独立。 ```go var ( sdkMerchantA *BsPaySdk.BsPay sdkMerchantB *BsPaySdk.BsPay ) func init() { sdkMerchantA, _ = BsPaySdk.NewBsPay(false, "./config/merchant_a.json") sdkMerchantB, _ = BsPaySdk.NewBsPay(false, "./config/merchant_b.json") } func processPaymentForMerchantA() { req := BsPaySdk.V2BankBalanceQueryRequest{ ReqSeqId: "REQ_A_001", ReqDate: "20240101", HuifuId: "merchant_a_id", } resp, _ := sdkMerchantA.V2BankBalanceQueryRequest(req) } func processPaymentForMerchantB() { req := BsPaySdk.V2BankBalanceQueryRequest{ ReqSeqId: "REQ_B_001", ReqDate: "20240101", HuifuId: "merchant_b_id", } resp, _ := sdkMerchantB.V2BankBalanceQueryRequest(req) } ``` -------------------------------- ### Configuration Reference Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/README.md Details on how to configure the BsPay GO SDK, including file formats, essential parameters, and environment settings. ```APIDOC ## Configuration Reference (04-configuration.md) This module guides users through the configuration process for the BsPay GO SDK. ### Configuration Aspects: - **JSON Configuration File Format**: Structure and syntax of the configuration file. - **Key Parameters**: `ProductID`, `SysID`, and secret key configurations. - **Environment Settings**: Configuration for test and production environments. - **Multi-Environment/Merchant Support**: Strategies for managing multiple configurations. - **Key Management Best Practices**: Secure handling of sensitive credentials. - **Configuration Path Settings**: How to specify configuration file locations. - **Common Configuration Issues**: Troubleshooting common problems. ``` -------------------------------- ### Basic Go Import Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/INDEX.md Import the necessary bspay-go-sdk package for basic usage. ```go import "github.com/huifurepo/bspay-go-sdk/BsPaySdk" ``` -------------------------------- ### Create a Wrapper Service for Bill Creation Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/06-quick-start.md Demonstrates creating a service layer wrapper around the bspay-go-sdk for bill creation. This approach encapsulates SDK interactions and provides a cleaner interface for your application logic. ```go package service import "github.com/huifurepo/bspay-go-sdk/BsPaySdk" type BillService struct { sdk *BsPaySdk.BsPay } func NewBillService(sdk *BsPaySdk.BsPay) *BillService { return &BillService{sdk: sdk} } func (bs *BillService) CreateBill(name, amount string) (map[string]interface{}, error) { req := BsPaySdk.V2BillEntCreateRequest{ ReqSeqId: generateReqSeqId(), ReqDate: getCurrentDate(), HuifuId: bs.sdk.Msc.SysId, BillName: name, BillAmt: amount, // ... 其他字段 } return bs.sdk.V2BillEntCreateRequest(req) } ``` -------------------------------- ### Conditionally Initialize SDK Based on Environment Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/06-quick-start.md This code snippet demonstrates how to conditionally initialize the SDK for either the production or test environment based on the APP_ENV environment variable. ```go import "os" func init() { env := os.Getenv("APP_ENV") isProd := env == "production" configFile := "./config/test.json" if isProd { configFile = "./config/prod.json" } sdk, _ := BsPaySdk.NewBsPay(isProd, configFile) } ``` -------------------------------- ### Multi-Merchant SDK Initialization Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/04-configuration.md Initialize separate SDK instances for different merchants, each with its own configuration file. This allows managing distinct merchant credentials and settings within the same application. ```go package main import ( "github.com/huifurepo/bspay-go-sdk/BsPaySdk" ) var ( sdkMerchantA *BsPaySdk.BsPay sdkMerchantB *BsPaySdk.BsPay ) func init() { // 初始化商户A的SDK sdkMerchantA, _ = BsPaySdk.NewBsPay(false, "./config/merchant_a.json") // 初始化商户B的SDK sdkMerchantB, _ = BsPaySdk.NewBsPay(false, "./config/merchant_b.json") } func main() { // 使用商户A的SDK reqA := BsPaySdk.V2BankBalanceQueryRequest{ ReqSeqId: "SEQ_A_001", ReqDate: "20240101", HuifuId: "merchant_a_id", } respA, _ := sdkMerchantA.V2BankBalanceQueryRequest(reqA) // 使用商户B的SDK reqB := BsPaySdk.V2BankBalanceQueryRequest{ ReqSeqId: "SEQ_B_001", ReqDate: "20240101", HuifuId: "merchant_b_id", } respB, _ := sdkMerchantB.V2BankBalanceQueryRequest(reqB) } ``` -------------------------------- ### Basic API Call Flow Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/02-api-methods.md Demonstrates the standard procedure for initializing the SDK, creating a request object, optionally setting extended fields, and invoking an API method, followed by response handling. ```APIDOC ## Basic API Call Flow ### Description This snippet illustrates the fundamental steps to interact with the BsPay SDK's API methods. It covers initialization, request preparation, API invocation, and response processing. ### Steps: 1. **Initialize SDK**: Create a new instance of the BsPay SDK, providing configuration details. 2. **Create Request Object**: Instantiate a specific request type (e.g., `V2BankBalanceQueryRequest`) with required parameters. 3. **Set Optional Fields**: Add any necessary optional parameters, such as `ExtendInfos`, to the request object. 4. **Call API**: Invoke the corresponding SDK method (e.g., `sdk.V2BankBalanceQueryRequest(req)`) to send the request. 5. **Handle Response**: Process the returned map, checking for errors and extracting business data. ### Code Example ```go // 1. Initialize SDK sdk, err := BsPaySdk.NewBsPay(false, "./config/config.json") if err != nil { log.Fatal(err) } // 2. Create Request Object req := BsPaySdk.V2BankBalanceQueryRequest{ ReqSeqId: "unique_request_id_001", ReqDate: "20240101", HuifuId: "merchant_id", } // 3. Optional: Set Extend Infos req.ExtendInfos = map[string]interface{}{ "optional_field_1": "value1", "optional_field_2": "value2", } // 4. Call API resp, err := sdk.V2BankBalanceQueryRequest(req) if err != nil { // Handle error log.Printf("API call failed: %v", err) return } // 5. Handle Response if respData, ok := resp["data"].(map[string]interface{}); ok { // Parse business data } ``` ``` -------------------------------- ### 配置商户信息 Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/06-quick-start.md 创建config/config.json文件,包含商户的Product ID、System ID以及RSA密钥。请确保密钥格式正确。 ```json { "product_id": "你的产品ID", "sys_id": "你的系统ID", "rsa_merch_private_key": "-----BEGIN RSA PRIVATE KEY-----\n...\n-----END RSA PRIVATE KEY-----", "rsa_huifu_public_key": "-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----" } ``` -------------------------------- ### 本地引用BsPay GO SDK Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/06-quick-start.md 如果SDK源码已在本地,可以在go.mod文件中添加依赖。或者将SDK源码放在项目的vendor目录中。 ```go require github.com/huifurepo/bspay-go-sdk/BsPaySdk v0.0.1 ``` -------------------------------- ### NewBsPay Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/01-core-modules.md Initializes a new instance of the BsPay SDK. This is the first step to using the SDK, allowing configuration for either production or test environments. ```APIDOC ## NewBsPay ### Description Initializes a new instance of the BsPay SDK. This is the first step to using the SDK, allowing configuration for either production or test environments. ### Signature ```go func NewBsPay(isProdMode bool, fileDir string) (*BsPay, error) ``` ### Parameters #### Path Parameters - **isProdMode** (bool) - Required - Environment selection: true for production, false for test. - **fileDir** (string) - Required - Path to the configuration file (JSON format). ### Returns - **(*BsPay)**: The initialized SDK instance. - **error**: Error information if initialization fails. ### Errors - Configuration file does not exist or is not readable. - Configuration file content is invalid or incomplete. - Required configuration fields are missing. ### Usage Example ```go package main import ( "github.com/huifurepo/bspay-go-sdk/BsPaySdk" "log" ) func main() { // Initialize SDK - Test Environment sdk, err := BsPaySdk.NewBsPay(false, "./config/config.json") if err != nil { log.Fatalf("SDK initialization failed: %v", err) } // Initialize SDK - Production Environment prodSdk, err := BsPaySdk.NewBsPay(true, "./config/config.json") if err != nil { log.Fatalf("SDK initialization failed: %v", err) } } ``` ``` -------------------------------- ### 企业进件 Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/INDEX.md Handles enterprise onboarding (Ling Gong Zhi Fu) using the V2FlexibleEntRequest type. ```APIDOC ## 企业进件 ### Description Handles enterprise onboarding. ### Parameters #### Request Body - **V2FlexibleEntRequest** (object) - Required - The request body for enterprise onboarding. ``` -------------------------------- ### 个人进件 Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/INDEX.md Handles individual onboarding (Ling Gong Zhi Fu) using the V2FlexibleIndvRequest type. ```APIDOC ## 个人进件 ### Description Handles individual onboarding. ### Parameters #### Request Body - **V2FlexibleIndvRequest** (object) - Required - The request body for individual onboarding. ``` -------------------------------- ### Cache BSPay SDK Instance for Performance Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/04-configuration.md Optimize performance by initializing the BSPay SDK instance once and reusing it throughout the application. This pattern avoids repeated file I/O and SDK initialization overhead. ```go var sdkInstance *BsPaySdk.BsPay func init() { var err error sdkInstance, err = BsPaySdk.NewBsPay(false, "./config/config.json") if err != nil { // 处理初始化错误 panic(err) } } func someFunction() { // 复用全局SDK实例,避免重复初始化 resp, _ := sdkInstance.V2BankBalanceQueryRequest(req) } ``` -------------------------------- ### 初始化BsPay GO SDK Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/06-quick-start.md 使用商户配置初始化SDK。第二个参数为配置文件路径。传入`false`表示使用测试环境。 ```go package main import ( "fmt" "log" "github.com/huifurepo/bspay-go-sdk/BsPaySdk" ) func main() { // 初始化SDK(false表示测试环境) sdk, err := BsPaySdk.NewBsPay(false, "./config/config.json") if err != nil { log.Fatalf("SDK初始化失败: %v", err) } fmt.Println("SDK初始化成功!") } ``` -------------------------------- ### 选择测试或生产环境 Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/07-errors-and-faq.md 通过 `NewBsPay()` 函数的第一个布尔参数来选择测试环境(false)或生产环境(true)。开发阶段建议使用测试环境。 ```go // 测试环境 - 用于开发和测试 sdk, _ := BsPaySdk.NewBsPay(false, "./config/config.json") // 生产环境 - 用于生产部署,产生真实交易 sdk, _ := BsPaySdk.NewBsPay(true, "./config/config.json") ``` -------------------------------- ### 安装BsPay GO SDK Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/06-quick-start.md 使用Go Modules添加SDK依赖。请确保你的项目已启用Go Modules。 ```bash go get github.com/huifurepo/bspay-go-sdk/BsPaySdk ``` -------------------------------- ### 并发使用SDK实例 Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/07-errors-and-faq.md 每个SDK实例支持并发使用,可利用 `sync.WaitGroup` 来管理并发的API请求。确保在goroutine中正确处理类型断言。 ```go import "sync" var sdk *BsPaySdk.BsPay func callAPIsConcurrently() { var wg sync.WaitGroup requests := []interface{}{ BsPaySdk.V2BankBalanceQueryRequest{...}, BsPaySdk.V2BillEntCreateRequest{...}, // ... 更多请求 } for _, req := range requests { wg.Add(1) go func(r interface{}) { defer wg.Done() // 类型断言后调用对应的API switch v := r.(type) { case BsPaySdk.V2BankBalanceQueryRequest: resp, _ := sdk.V2BankBalanceQueryRequest(v) log.Printf("响应: %v", resp) } }(req) } wg.Wait() } ``` -------------------------------- ### Troubleshoot Missing Configuration File Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/06-quick-start.md If you encounter a 'read merch config file failed' error, ensure your configuration file exists at the specified path. Use 'ls -la' to verify. ```bash ls -la ./config/config.json ``` -------------------------------- ### Troubleshoot Issues Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/00-START-HERE.md Consult the error reference and FAQ for solutions to common problems and errors. ```bash # 查看错误参考 # 👉 [打开错误和FAQ](07-errors-and-faq.md) ``` -------------------------------- ### Flexible Payment - Individual Onboarding Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/README.md API for individual onboarding in the flexible payment system. ```APIDOC ## POST /v2/flexible/indv ### Description Onboards a new individual. ### Method POST ### Endpoint /v2/flexible/indv ``` -------------------------------- ### 设置请求超时与Context Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/07-errors-and-faq.md SDK默认使用 `http.DefaultClient`。建议使用 `context.WithTimeout` 来处理API调用的超时,以避免长时间等待。 ```go import "context" func callAPIWithTimeout(ctx context.Context) { // 创建带超时的context ctx, cancel := context.WithTimeout(ctx, 30*time.Second) defer cancel() // 在timeout内执行API调用 resp, err := sdk.V2BankBalanceQueryRequest(req) if err != nil { log.Printf("API调用失败: %v", err) } } ``` -------------------------------- ### V2FlexibleIndvRequest Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/03-types.md Represents a Ling Gong individual user onboarding request. ```APIDOC ## POST /v2/flexible/indv ### Description Onboards a new individual user for Ling Gong Payment. ### Method POST ### Endpoint /v2/flexible/indv ### Parameters #### Request Body - **req_seq_id** (string) - Required - Request sequence number - **req_date** (string) - Required - Request date - **extend_infos** (map) - Optional - Extended fields ``` -------------------------------- ### Set Configuration File Permissions Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/07-errors-and-faq.md Ensure the configuration file has the correct read permissions. ```bash chmod 644 ./config/config.json ``` -------------------------------- ### 处理扩展字段 (ExtendInfos) Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/07-errors-and-faq.md 使用 `ExtendInfos` map 传递非必填字段。初始化 map 后,可以向其中添加键值对,用于自定义字段传递。 ```go req := BsPaySdk.V2BillEntCreateRequest{ ReqSeqId: "REQ_001", // ... 必填字段 } // 初始化扩展字段 req.ExtendInfos = make(map[string]interface{}) // 添加扩展字段 req.ExtendInfos["custom_field_1"] = "value1" req.ExtendInfos["custom_field_2"] = 100 req.ExtendInfos["custom_field_3"] = true // 调用API resp, _ := sdk.V2BillEntCreateRequest(req) ``` -------------------------------- ### V2FlexibleIndvRequest Method Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/02-api-methods.md Represents the request structure for onboarding individual users into the flexible payment system. This method is used for individual account creation. ```go V2FlexibleIndvRequest ``` -------------------------------- ### Set Configuration File Permissions Source: https://github.com/huifurepo/bspay-go-sdk/blob/master/_autodocs/04-configuration.md Secure your configuration files by setting restrictive file permissions. Use 'chmod 600' to ensure only the owner can read and write the file. ```bash chmod 600 ./config/config.json ```