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

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

相关推荐
WangHappy2 天前
不写 Canvas 也能搞定!小程序图片导出的 WebView 通信方案
前端·微信小程序
小时前端2 天前
微信小程序选不了本地文件?用 web-view + H5 一招搞定
前端·微信小程序·uni-app
icebreaker3 天前
Weapp-vite:原生模式之外,多一种 Vue SFC 选择
前端·vue.js·微信小程序
icebreaker3 天前
重走 Vue 长征路 Weapp-vite:编译链路与 Wevu 运行时原理拆解
前端·vue.js·微信小程序
大米饭消灭者6 天前
Taro是怎么实现一码多端的【底层原理】
微信小程序·taro
FliPPeDround7 天前
Vitest Environment UniApp:让 uni-app E2E 测试变得前所未有的简单
微信小程序·e2e·前端工程化
FliPPeDround7 天前
微信小程序自动化的 AI 新时代:wechat-devtools-mcp 智能方案
微信小程序·ai编程·mcp
吴声子夜歌7 天前
小程序——布局示例
小程序
码云数智-大飞7 天前
如何创建自己的小程序,码云数智与有赞平台对比
微信小程序
luffy54597 天前
微信小程序页面使用类似filter函数的wxs语法
微信小程序·小程序