首页 银行卡识别 银行卡识别示例代码 银行卡识别[C#]

银行卡识别示例代码C#

作者: 阅读数:1133 上传时间:2025-05-26

银行卡识别

using System;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;

class BankCardCognition
{    
    private const string AppKey = "YOUR_APPKEY_HERE";

    public static async Task RecognizeAsync(string ImagePath)
    {
        try
        {
            // 读取图片文件并转换为 Base64 字符串
            string base64Image = Convert.ToBase64String(File.ReadAllBytes(ImagePath));

            // 构建请求 URL,将 AppKey 作为查询参数
            string url = $"https://api.jisuapi.com/bankcardcognition/recognize?appkey={AppKey}";

            // 构建 POST 请求体,使用 x-www-form-urlencoded 格式
            var postData = new StringContent($"pic={base64Image}", Encoding.UTF8, "application/x-www-form-urlencoded");

            using (HttpClient client = new HttpClient())
            {
                // 发送 POST 请求
                HttpResponseMessage response = await client.PostAsync(url, postData);
                // 确保请求成功,若失败则抛出异常
                response.EnsureSuccessStatusCode();

                // 读取响应内容
                string responseBody = await response.Content.ReadAsStringAsync();
                // 解析 JSON 响应内容
                JObject jsonarr = JObject.Parse(responseBody);

                // 检查响应状态码
                if (jsonarr["status"] != null && (int)jsonarr["status"] != 0)
                {
                    if (jsonarr["msg"] != null)
                    {
                        // 若状态码非 0,输出错误信息
                        Console.WriteLine(jsonarr["msg"]);
                    }
                    return;
                }

                // 获取结果对象
                JObject result = (JObject)jsonarr["result"];
                if (result != null)
                {
                    // 遍历结果对象,输出键值对
                    foreach (var property in result)
                    {
                        Console.WriteLine($"{property.Key} {property.Value}");
                    }
                }
            }
        }
        catch (HttpRequestException ex)
        {
            // 处理 HTTP 请求异常
            Console.WriteLine($"请求出错: {ex.Message}");
        }
        catch (Exception ex)
        {
            // 处理其他异常
            Console.WriteLine($"发生错误: {ex.Message}");
        }
    }
	
	public static async Task Main()
    {
        // 调用识别银行卡信息的方法
        await BankCardCognition.RecognizeAsync(@"C:\Users\Administrator\Desktop\000.jpg");
    }
}