目标:
请求二维码并展示
步骤:
用户点击按钮生成二维码
步骤:
1、微信小程序往后台请求二维码
2、后台(java/php) 根据微信小程序信息往微信端请求tonken
3、后台得到tonken后往微信端请求二维码图片
4、后台得到图片后保存在服务器上,将路径返回给微信小程序
5、微信小程序得到路径后,根据路径下载图片
6、下载图片成功后再保存至本地
7、保存成功后将路径给予image标签里面展示
代码:
wxml
<image class="scanimg" src="{{filepath}}" bindtap="getagain"></image>
<button type="primary" bindtap="primary">点击生成二维码</button>
s代码
primary:function (e) {
var _url = '后台地址';
wx.request({
url: _url,
//请求报文体
data: [{
id: agentcode
}],
method: 'post',
header: {
'content-type': 'application/json'
},
success: function (res) {
//为00时表示成功,得到二维码的地址
if (res.data.code == '00') {
console.log(成功)
//下载二维码
wx.downloadfile({
url: res.data.body[0].url,
success: function (res) {
//如果二维码中的id为固定值可以将图片保存到本地,否则不用保存
wx.savefile({
tempfilepath: res.tempfilepath,
success: function (res) {
console.log(保存成功)
_that.setdata({
filepath: res.savedfilepath
})
console.log(res.savedfilepath)
try {
//id为定值,则将保存的地址存入缓存,非定值则只需要setdata就行
wx.setstoragesync('filepath', res.savedfilepath)
} catch (e) {
console.log(e)
}
},
fail: function (res) {
console.log(保存失败)
console.log(res)
}
})
}, fail: function (res) {
util.msg(错误, 通讯失败)
console.log(res)
}
})
} else {
console.log(错误)
util.msg(错误, res.data.msg)
}
},
fail: function () {
util.msg(错误, 通讯失败)
console.log(res)
}
})
}
java端代码
// 访问微信后台的url
string url = systemconfig.getstring(loginorregisterurl);
// 请求类型
string grant_type = systemconfig.getstring(grant_type);
// 第三方用户唯一凭证密钥
string secret = systemconfig.getstring(secret);
// 第三方用户唯一凭证
string appid = systemconfig.getstring(appid);
// 请求token时用到的url
string tokenurl = systemconfig.getstring(tokenurl);
// 向微信后台请求获取token
string sendget = httpclientconnectionmanager.sendget(
tokenurl, grant_type= + grant_type
+ &secret= + secret + &appid=
+ appid + );
system.out.println(sendget);
jsonobject json = jsonobject.fromobject(sendget);
access_token = json.get(access_token).tostring();
if (access_token == null) {
//没有token 则返回错误码和错误信息
agentdto.setcode(0002);
agentdto.setdesc(获取tokenid失败);
return agentdto;
}
system.out.println(access_token);
// 访问微信后台带的json参数
map<string, object> map = new hashmap<string, object>();
map.put(path, pages/register);//你二维码中跳向的地址
map.put(width, 430);//图片大小
jsonobject json = jsonobject.fromobject(map);
httpclientconnectionmanager.httppostwithjson(url
+ access_token, json.tostring(), id + max);
// 返回给前端的后台服务器文件读取路径
string downloadurl = systemconfig
.getstring(agentimgdownloadurl)
+ id
+ max
+ /;
// 返回给前端的后台服务器文件下载路径
string downloadfileurl = downloadurl + id + max + .jpg;
agentresview.seturl(downloadfileurl);
agentdto.setagentresview(agentresview);
agentdto.setcode(00);
agentdto.setdesc(成功);
return agentdto;
tip
1、这是申请一张二维码的代码,申请多张可以用for或者其他的方法
2、当id为定量时,每次点击按钮判断filepath缓存是否存在,存在则直接取值展示,不存在则向后台请求二维码
以上就是微信小程序用户点击按钮生成带参二维码的示例代码的详细内容。