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

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

相关推荐
Emma歌小白2 天前
如何首次运行小程序后端
微信小程序
赣州云智科技的技术铺子2 天前
【一步步开发AI运动APP】十二、自定义扩展新运动项目1
微信小程序·小程序·云开发·智能小程序
2501_915918412 天前
iOS 上架全流程指南 iOS 应用发布步骤、App Store 上架流程、uni-app 打包上传 ipa 与审核实战经验分享
android·ios·小程序·uni-app·cocoa·iphone·webview
00后程序员张2 天前
iOS App 混淆与加固对比 源码混淆与ipa文件混淆的区别、iOS代码保护与应用安全场景最佳实践
android·安全·ios·小程序·uni-app·iphone·webview
破无差2 天前
《赛事报名系统小程序》
小程序·html·uniapp
00后程序员张2 天前
详细解析苹果iOS应用上架到App Store的完整步骤与指南
android·ios·小程序·https·uni-app·iphone·webview
海绵宝宝不喜欢侬2 天前
uniapp-微信小程序分享功能-onShareAppMessage
微信小程序·小程序·uni-app
2501_915106322 天前
Xcode 上传 ipa 全流程详解 App Store 上架流程、uni-app 生成 ipa 文件上传与审核指南
android·macos·ios·小程序·uni-app·iphone·xcode
亮子AI2 天前
【小程序】微信小程序隐私协议
微信小程序·小程序
weixin_177297220692 天前
短剧小程序系统开发:打造个性化娱乐新平台
小程序·娱乐·短剧