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

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,这样就可以验证验证码了。

相关推荐
ChinaDragonDreamer2 小时前
uniapp:小程序将base64图片字符串保存到手机相册
小程序·uniapp
Planck_Ho17 小时前
uni-app 小程序表单校验错误自动滚动到错误位置
微信小程序·uni-app
优雅格子衫1 天前
记录uniapp小程序对接腾讯IM即时通讯无ui集成(2)
小程序·uni-app
丁总学Java1 天前
制服小程序的“滑手”:禁用页面左右滑动全攻略
小程序
98年撸铁的老阿姨1 天前
实验室预约小程序
小程序
优雅格子衫1 天前
uniapp小程序对接腾讯IM即时通讯无ui集成(1)
小程序·uni-app
油丶酸萝卜别吃1 天前
微信小程序中配置不同的环境变量,并依据环境变量编写API接口请求文件
微信小程序·小程序·notepad++
lfq7612042 天前
微信小程序接入DeepSeek模型(火山方舟),并在视图中流式输出
微信小程序·小程序·deepseek
java1234_小锋2 天前
[免费]微信小程序(校园)二手交易系统(uni-app+SpringBoot后端+Vue管理端)【论文+源码+SQL脚本】
spring boot·微信小程序·uni-app·java毕业设计·二手交易·微信小程序二手交易