描述:想做一下那种抽奖二维码验券的功能,其实就是在生成二维码的时候调用验证二维码的接口,我的案例是这样的
首先二维码用的是QRCoder版本为1.4.2,我用的是EntityFrameworkCore框架
<PackageReference Include="QRCoder" Version="1.4.2" />
下面是生成二维码的代码
/// <summary>
/// 描述:生成二维码
/// 姓名:wu
/// 日期:2024/12/31
/// id是用来改状态的,比如某某某中奖了肯定有个标志位和状态通过标志位去改他的状态
/// </summary>
/// <returns></returns>
[HttpPost("CreateQRCode")]
public ApiResponse CreateQRCode(string id)
{
ApiResponse res = new HgWeld.Api.Models.ApiResponse();
try
{
// 创建二维码生成器
QRCodeGenerator qrGenerator = new QRCodeGenerator();
// 创建二维码数据
//这一步是放二维码里面的信息,我放的是接口地址,后续发布了替换部署后的就好了
QRCodeData qrCodeData = qrGenerator.CreateQrCode("http://localhost:5129/api/NewFacility/Verify_QRCode?id=" + id, QRCodeGenerator.ECCLevel.H); // 使用更高的纠错级别
// 创建二维码
QRCode qrCode = new QRCode(qrCodeData);
// 获取二维码图像
Bitmap qrCodeImage = qrCode.GetGraphic(20); // 增大二维码尺寸
// 加载Logo图像
//这一步是在你当前项目下有这个图片可以生成中间带log的图片(可以改为用户的头像地址)
Bitmap logo = (Bitmap)System.Drawing.Image.FromFile("path_to_logo.png"); // 替换为你的Logo路径
// 计算Logo的位置和大小
int logoSize = qrCodeImage.Width / 6; // 调整Logo大小
int x = (qrCodeImage.Width - logoSize) / 2;
int y = (qrCodeImage.Height - logoSize) / 2;
// 将Logo绘制到二维码上
using (Graphics g = Graphics.FromImage(qrCodeImage))
{
g.DrawImage(logo, x, y, logoSize, logoSize);
}
// 保存二维码图像
// 二维码生成后也是同样在当前项目的文件夹会生成qrcode_with_logo.png图片(可以改为id+log.png的方式)
string filePath = "qrcode_with_logo.png";
qrCodeImage.Save(filePath, ImageFormat.Png);
res.code = 200;
res.data = filePath;
res.message = "成功";
return res;
}
catch (Exception ex)
{
res.code = -500;
res.data = null;
res.message = "异常:"+ex.Message;
return res;
}
}
这个是二维码扫描后的接口(上面有注释,二维码里的内容就是调用下面的这个接口从而实现修改状态)
/// <summary>
/// 描述:二维码改状态
/// 姓名:wu
/// 日期:2024/12/31
/// </summary>
/// <returns></returns>
[HttpGet("Verify_QRCode")]
public async Task<ApiResponse> Verify_QRCode(string id)
{
ApiResponse res = new HgWeld.Api.Models.ApiResponse();
try
{
//这是我的某个实体类用来验证
TsysFile file = new TsysFile()
{
FileId = long.Parse(id)
};
//bll层就是一个根据实体类查询然后将状态改为已检验状态,这里我穿了context,是ef的配置对象,传值方式可用来写事务
res.data= await _tfbll.byIsDelete(file,context);
res.code = 200;
res.message = "成功";
return res;
}
catch (Exception ex)
{
res.code = -500;
res.data = null;
res.message = "异常:" + ex.Message;
return res;
}
}
最后生成的二维码可以用微信扫一扫,最会返回的就是{code=200,message="成功"}
这样我们的二维码验券就成功了