微信小程序上如何使用图形验证码

1、php服务器生成图片验证码的代码片段如下:

注意红框部分的代码,生成的是ArrayBuffer类型的二进制图片

2、显示验证码

显示验证码,不要直接image组件加上src显示,那样拿不到cookie,没有办法做图形验证码的验证,需要通过接口的方法获取,上接口代码如下:

perl 复制代码
function get_verify_code(url, success, fail, complete) {
	if (request_status == true) {
		return;
	}
	request_status = true;
	let header = {
		'Content-Type': 'application/x-www-form-urlencoded'
	};
	uni.request({
		url: url,
		timeout: 60000,
		header: header,
		responseType: 'arraybuffer',//这个地方不要写错
		method: 'GET',
		success: res => {
			request_status = false;
			if (res.statusCode == 200) {
				let cookieKey = '';
				let data = res.data;//拿的图片
				// #ifdef MP-WEIXIN
				if (res && res.header && res.header['Set-Cookie']) {
					cookieKey = res.header['Set-Cookie'];//拿cookie
				}
				// #endif
				success({"data":data,"cookieKey":cookieKey});
			} else if (res.statusCode == 404) {
				success({"success": false,"field": "fail_net","message": "请求的资源不存在"});
			} else if (res.statusCode == 500) {
				success({"success": false,"field": "fail_net","message": "内部服务器错误"});
			} else {
				success({"success": false,"field": "fail_net","message": "请求异常"});
			}
		},
		fail: (e) => {
			if (request_status == true) {
				request_status = false;
			}
			fail(e);
		},
		complete: (e) => {
			if (request_status == true) {
				request_status = false;
			}
			complete(e);
		}
	});
}

显示图片的操作代码如下:

perl 复制代码
get_verify_code(v) {
				let url = `${base_url}get_verify_code/${v}`;
				//console.log('url:'+url);
				this.$net.get_verify_code(
					url,
					res => {
						const base64 = uni.arrayBufferToBase64(res.data);
						this.imageData  = `data:image/png;base64,${base64}`;
						// #ifdef MP-WEIXIN
						if (res.cookieKey) {
							uni.setStorageSync('cookieKey', res.cookieKey);
						}
						// #endif
					},
					() => {
					},
					() => {
					}
				);
			},

这样图片就可以正常显示了,提交的方法里要带上cookie,这样就可以验证验证码了。

相关推荐
smartpi_ai1 小时前
JL-17T 能接传感器并把数据发到小程序吗?GPIO/ADC/UART 平台可做,I2C/SPI 要二开
人工智能·小程序·语音识别
andrsted3 小时前
在线刷小程序推荐
学习·微信小程序·小程序·学习方法
Mark108593 小时前
【踩坑】Uni-app微信小程序自定义组件在 Flex 布局中未铺满整行
微信小程序·小程序·uni-app
深瞳智检5 小时前
深瞳智检(小程序)正式上线!【免费/快捷/方便】获取YOLO检测数据集
人工智能·yolo·目标检测·小程序·数据集·cv数据收集
2601_963870216 小时前
【计算机毕业设计】基于微信小程序的电子家谱的设计与实现
微信小程序·小程序·课程设计
zww89491117 小时前
外卖CPS小程序系统:从返利链路到订单回填的技术实现
小程序
lhldsg7 小时前
酒吧点餐小程序开发:从需求分析到技术落地实战
java·前端·小程序·架构·交友
2601_949950631 天前
考研英语资料太散?用小程序把真题、词汇和错题放到一起
人工智能·学习·考研·小程序·刷题·小程序推荐
lhldsg1 天前
树洞倾诉的核心需求与产品定位误区
java·前端·小程序
lhldsg1 天前
宠物同城领养平台开发实战:从需求分析到上线部署指南
java·前端·小程序·需求分析·宠物