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

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

相关推荐
kyriewen21 小时前
一个人+Cursor,7天上线付费小程序:第1天我就想放弃了
前端·微信小程序·cursor
暗不需求1 天前
从路虎汽车小程序看微信小程序开发的最佳实践
前端·javascript·微信小程序
博客zhu虎康1 天前
小程序:解决小程序发布上线后无分享功能
小程序
tuanyuan99o1 天前
2026商城小程序的安全怎么保障?防止黑客攻击和数据泄露
安全·小程序
facetarzan2 天前
微信小程序文件下载
小程序·文件预览·文件下载
aiguangyuan2 天前
微信小程序服务商
微信小程序·前端开发
一支帆2 天前
微信小程序-情侣点餐
java·微信小程序·情侣点餐
Slow菜鸟2 天前
AI开发-微信小程序(全流程提示词)
人工智能·微信小程序
橘子海全栈攻城狮2 天前
【最新源码】鸟博士微信小程序 023
spring boot·后端·web安全·微信小程序·小程序
Yuujs2 天前
微信小程序反编译保姆级教程
微信小程序·小程序