首先看下效果图:
微信小程序已经上线很久了。现在才开始把代码拷进来 因为真的很忙 …………
先看代码吧。首先是小程序端的内容:
怕麻烦 全部拷进去吧 这块的需求就是完成分享小程序码保存到本地的相册里面。再通过发朋友圈或者什么方式发展下级。小程序码里面带着邀请码。这个没法直接发朋友圈或者分享链接。微信小程序暂时没提供这样的功能。
1.js里面的内容 刚开始一进来的时候我就获取了用户的头像和昵称。所有的图片我都是在后台获取的
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = Page({
data: {
NAV_HEIGHT: wx.STATUS_BAR_HEIGHT + wx.DEFAULT_HEADER_HEIGHT + 'px',
fileContext: getApp().globalData.fileContext,
postersData: [],
swiperIndex: 0,
currentIndex: 0,
avatarUrl: '',
nickName: '',
show: false,
backgroundImage: '',
logoImage: '../../images/icon-logo.png',
qrCode: '', //小程序码的路径
path_code: '', //处理后的小程序码
path_logo: '', //左下角logo的路径
path_san: '', //三角图标的路径
path_invite: '', //海报背景
path_tx: '', //用户头像的路径,
tmpImgNum: 0,
canvasContext: null,
getImageInfoNum: 4,
localPostersPaths: [], // 海报本地缓存路径
invitecode: ''
},
onLoad: function onLoad(options) {
var that = this;
if (options) {
that.data.invitecode = options.invitecode;
}
},
navigateBack: function navigateBack() {
wx.navigateBack();
},
onReady: function onReady() {
var that = this;
that.loadPosters();
getApp().refreshUserInfo(function (userInfo) {
if (userInfo.ifauthorize != 1) {
wx.showModal({ title: '提示', showCancel: false,
content: '请先授权应用获取您的用户信息',
success: function success(res) {
if (res.confirm) {
wx.switchTab({ url: '/pages/user/user' });
}
}
});
return;
}
var tmpData = { nickName: userInfo.nickname, avatarUrl: userInfo.headimage, qrCode: userInfo.qrcodepath };
that.setData(tmpData);
// 加载要绘制的内容
if (userInfo.headimage) {
wx.getImageInfo({ //用户头像的路径处理
src: userInfo.headimage,
success: function success(res) {
that.data.path_tx = res.path;
},
fail: function fail(res) {
that.data.path_tx = '../../images/nopic.png';
}
});
}
wx.getImageInfo({ //用户小程序码处理
src: userInfo.qrcodepath,
success: function success(res) {
that.data.path_code = res.path;
},
fail: function fail(res) {
that.createQrcode();
}
});
});
},
loadPosters: function loadPosters() {
var that = this;
getApp().GET({
url: '/webapi/poster/getPage.json',
data: {},
success: function success(res) {
var data = res.data;
if (res.code == 0 && data && data.length > 0) {
that.setData({
postersData: data
});
var tmpPath = that.data.localPostersPaths = new Array(data.length);
for (var i = 0; i < data.length; i++) {
that.logoPostersImage(that.data.localPostersPaths, data[i].picAddress, i);
}
}
}
});
},
logoPostersImage: function logoPostersImage(tmpPath, url, index) {
wx.getImageInfo({ src: url,
success: function success(ires) {
tmpPath[index] = ires.path;
},
fail: function fail(res) {
console.log("logoPostersImage---fail", res);
}
});
},
handleTap: function handleTap(e) {
var that = this;
var num = e.currentTarget.dataset.num;
num = num ? parseInt(num) : 0;
var length = this.data.postersData.length;
var index = this.data.currentIndex;
if (num + index >= length) {
index = 0;
} else if (num + index < 0) {
index = length - 1;
} else {
index += num;
}
this.setData({
currentIndex: index,
swiperIndex: index
});
},
handleSwiperChange: function handleSwiperChange(e) {
var that = this;
var current = e.detail.current;
this.setData({
currentIndex: current
});
},
handleImgListTap: function handleImgListTap(e) {
var that = this;
var index = e.currentTarget.dataset.index;
this.setData({
currentIndex: index,
swiperIndex: index
});
},
//关闭邀请弹窗
closePop: function closePop() {
this.setData({
showPop: !this.data.showPop
});
},
//点击邀请好友
inviteFun: function inviteFun() {
wx.showLoading({
title: '加载中'
});
var that = this;
that.setData({
showPop: !that.data.showPop
});
that.formSubmit();
},
//生成小程序码的代码
createQrcode: function createQrcode() {
var that = this;
getApp().GET({
url: '/webapi/member/createQrCode.json',
data: {},
success: function success(res) {
that.setData({ qrCode: res.path });
that.data.tmpImgNum = 0;
wx.getImageInfo({ src: res.path,
success: function success(res) {
that.data.path_code = res.path;
}
});
}
});
},
getImageInfoCount: function getImageInfoCount(that) {
that.data.tmpImgNum++;
if (that.data.tmpImgNum >= that.data.getImageInfoNum) {
that.formSubmit();
}
},
//用canvas绘制海报
createNewImg: function createNewImg() {
this.data.tmpDrawImgNum = 0;
var that = this;
var canvasContext = wx.createCanvasContext('mycanvas' + that.data.currentIndex, this);
var nick = that.data.nickName;
nick = nick && nick.length > 8 ? nick.substring(0, 8) + '...' : nick;
canvasContext.setFillStyle("white"); //填充海报背景为白色
canvasContext.fillRect(0, 0, 270, 320); //设置海报的大小 270*320
console.log(that.data.localPostersPaths[that.data.currentIndex]);
if (!that.data.localPostersPaths[that.data.currentIndex]) {
wx.showModal({ title: '提示', showCancel: false,
content: '图片保存失败,换其他图试试吧'
});
return;
}
canvasContext.drawImage(that.data.localPostersPaths[that.data.currentIndex], 0, 0, 270, 238); //绘制头部大图
canvasContext.setFontSize(13); //用户昵称
canvasContext.setFillStyle("#000");
canvasContext.fillText(nick, 62, 276);
canvasContext.drawImage(that.data.logoImage, 10, 288, 92, 25); //绘制左下角logo
canvasContext.drawImage(that.data.path_code, 184, 240, 80, 80); //绘制右下角小程序码
canvasContext.beginPath();
canvasContext.arc(36, 271, 15, 0, 2 * Math.PI);
canvasContext.clip();
canvasContext.drawImage(that.data.path_tx, 18, 252, 34, 34);
canvasContext.draw(false, function () {
that.canvasDrawCount(that);
});
},
// 当画布绘制成功达到上限时,因为绘制需要消耗时间,则执行某些操作
canvasDrawCount: function canvasDrawCount(that) {
that.data.tmpDrawImgNum++;
if (that.data.tmpDrawImgNum >= 1) {
wx.canvasToTempFilePath({
canvasId: 'mycanvas' + that.data.currentIndex,
success: function success(res) {
var tempFilePath = res.tempFilePath;
wx.getImageInfo({
src: tempFilePath,
success: function success(res) {
that.baocun(res.path);
}
});
},
fail: function fail(res) {
console.log(res);
}
});
}
},
//点击保存到相册
baocun: function baocun(path) {
wx.hideToast();
var that = this;
wx.saveImageToPhotosAlbum({
filePath: path,
success: function success(res) {
wx.showModal({
content: '图片已保存到相册,赶紧分享给好友吧~',
showCancel: false,
confirmText: '好的',
confirmColor: '#333',
success: function success(res) {
if (res.confirm) {
console.log('用户点击确定');
/* 该隐藏的隐藏 */
setTimeout(function () {
that.setData({
maskHidden: false,
showPop: !that.data.showPop
});
}, 500);
}
}, fail: function fail(res) {
console.log();
}
});
},
fail: function fail(err) {
if (err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
// 这边微信做过调整,必须要在按钮中触发,因此需要在弹框回调中进行调用
wx.showModal({
title: '提示',
content: '需要您授权保存相册',
showCancel: false,
success: function success(modalSuccess) {
wx.openSetting({
success: function success(settingdata) {
if (settingdata.authSetting['scope.writePhotosAlbum']) {
wx.showModal({
title: '提示',
content: '获取权限成功,再次点击邀请好友即可保存',
showCancel: false
});
} else {
wx.showModal({
title: '提示',
content: '获取权限失败,将无法保存到相册哦~',
showCancel: false
});
}
},
fail: function fail(failData) {
console.log("failData", failData);
},
complete: function complete(finishData) {
console.log("finishData", finishData);
}
});
}
});
}
}
});
},
//点击生成
formSubmit: function formSubmit(e) {
var that = this;
that.setData({
maskHidden: false
});
wx.showToast({
title: '正在保存图片.',
icon: 'loading',
duration: 1000
});
that.createNewImg();
// wx.hideToast()
// setTimeout(function () {
// that.setData({
// maskHidden: true
// });
// }, 500)
},
onShareAppMessage: function onShareAppMessage(res) {
if (res.from == 'button') {
console.log(res.target, res);
}
var that = this;
var userInfo = wx.getStorageSync('user-info');
var index = that.data.currentIndex;
var invitecode = userInfo ? userInfo.invitecode : '';
return {
title: that.data.postersData[index].title,
path: '/pages/home/index?invitecode=' + invitecode,
imageUrl: that.data.postersData[index].picAddress
};
},
onShow: function onShow() {
if (this.data.invitecode) {
var invitecode = this.data.invitecode;
wx.switchTab({ url: '/pages/home/index?invitecode=' + invitecode });
}
}
});
2.wxml 的内容,相当于html
邀请得积分
{{ nickName ? nickName : '机好多' }}
保存相册
3.样式的内容
.img-swiper-box {
margin-top: 8%;
}
.img-swiper-box .img-swiper {
height: 400rpx;
width: 92%;
}
.fixed-view-content {
background: #ffffff;
border-radius: 12rpx;
color: #fff;
font-size: 32rpx;
}
.fixed-view-content .fixed-saveview {
background: #00a8b5;
margin-left: 12rpx;
width: 100%;
height: 100%;
line-height: 40px;
border-radius: 6rpx 0rpx 0rpx 6rpx !important;
}
.fixed-view-content .fixed-row {
margin-bottom: 6rpx;
}
.imglist-box {
margin-top: 4%;
background: #efefef;
padding: 18rpx;
width: 100%;
white-space: nowrap;
}
.imglist-box .imglist-item {
height: 186rpx;
width: 180rpx;
display: inline-block;
margin: 0 12rpx;
vertical-align: bottom;
border: 4rpx solid rgba(0, 0, 0, 0);
border-radius: 5rpx;
}
.imglist-box .selected {
border: 4rpx solid #00a8b5;
}
.imglist-box .item-image {
border-radius: 3rpx;
}
.nav-bar-text {
font-size: 16px;
}
.scoredsc-box {
margin: 4% 6% 20% 6%;
color: #6f6f6f;
background-color: #fff;
}
.scoredsc-box .scoredsc-content {
text-indent: 2em;
padding-bottom: 42rpx;
}
/* 邀请的弹窗 */
.zzc {
position: fixed;
width: 100%;
height: 100%;
left: 0;
top: 0;
background: rgba(0, 0, 0, 0.5);
z-index: 1;
}
.popBox {
position: fixed;
width: 100%;
height: 100%;
left: 0;
top: 0;
display: flex;
align-items: center;
justify-content: center;
z-index: 2;
}
.popCon {
width: 70%;
position: relative;
background: #fff;
}
.img_invite {
width: 100%;
}
.whiteBox {
background: #fff;
padding: 20rpx;
}
.whiteTop {
display: flex;
align-items: center;
margin-bottom: 20rpx;
}
.headImgBox {
width: 60rpx;
height: 60rpx;
border-radius: 50%;
overflow: hidden;
margin-right: 20rpx;
}
.headImgBox .head_img {
width: 100%;
}
.user_nick {
font-size: 14px;
color: #000;
}
.logo_img {
width: 210rpx;
}
.codeImg {
position: absolute;
right: 0;
bottom: 10rpx;
width: 160rpx;
height: 160rpx;
}
.btn_close {
position: absolute;
top: -70rpx;
right: -10rpx;
font-size: 34px;
color: #fff;
}
.canvasItem {
width: 264px;
height: 320px;
position: fixed;
left: 200%;
top: 0;
}
.fixed-text {
font-size: 32rpx;
color: #fff;
}
.fixed-button {
height: 40px;
margin: 0 12rpx 0 0;
border-radius: 0px 6rpx 6rpx 0px !important;
width: 100%;
background-color: #f79925;
}
.fixed-button::after {
border: none;
}
获取图片的接口 就不贴了。 贴上生成小程序码的接口
@RequestMapping(value = "/createQrCode", method = { RequestMethod.POST, RequestMethod.GET })
@ResponseBody
public Object createQrCode(HttpServletRequest request) throws WriterException, IOException {
Map data = new HashMap();
Member member = MemberManager.getMember(request);
boolean needCreate = false;
if (StringUtils.isNotBlank(member.getQrcodepath())) {
data.put("path", member.getQrcodepath());
if (!testUrlWithTimeOut(member.getQrcodepath(), 2000)) {
needCreate = true;
}
} else {
needCreate = true;
}
if (needCreate) {
String accessToken = Cache.get(WXMiniprogramApi.ACCESS_TOKEN_CACHE_KEY);
if (StringUtils.isBlank(accessToken)) {
accessToken = WXMiniprogramApi.getAccessToken();
}
String scene = member.getInvitecode();// 把自己的id放进小程序码中
data = RQcodeUtil.getminiqrQr(scene, accessToken);
Member tmpMember = new Member();
tmpMember.setId(member.getId());
tmpMember.setQrcodepath(data.get("path").toString());
memberService.updateById(tmpMember);
}
return data;
}
public boolean testUrlWithTimeOut(String urlString, int timeOutMillSeconds) {
long lo = System.currentTimeMillis();
URL url;
try {
url = new URL(urlString);
URLConnection co = url.openConnection();
co.setConnectTimeout(timeOutMillSeconds);
co.connect();
System.out.println("连接可用");
return true;
} catch (Exception e1) {
System.out.println("连接打不开!");
return false;
}
}
获取AccessToken的方法
public static String getAccessToken() {
String appId = ApplicationConfigurer.getStringProperty("wxMiniprogramAppID", "");
String appSecret = ApplicationConfigurer.getStringProperty("wxMiniprogramAppSecret", "");
String accessToken = Cache.get(ACCESS_TOKEN_CACHE_KEY);
if (StringUtils.isNotEmpty(accessToken)) {
return accessToken;
}
String url = String.format(
"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", appId,
appSecret);
String result = WXHttpHelper.sendGet(url);
// System.out.println("result = " + result);
if (isError(result)) {
log.info(String.format("调用微信接口错误(获取access_token),错误信息为:%s;请求URL:%s", result, url));
return null;
}
MpAccessToken wxAccessToken = parseObject(result, MpAccessToken.class);
Cache.set(ACCESS_TOKEN_CACHE_KEY, wxAccessToken.getAccess_token(), TIMEOUT);
return wxAccessToken.getAccess_token();
}
生成小程序码的工具类 用的是getWXACodeUnlimit 永久有效,数量暂无限制的接口
package cn.lision.iems.admin.support;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import com.alibaba.fastjson.JSONObject;
import cn.lision.iems.admin.support.properties.ApplicationConfigurer;
public class RQcodeUtil {
public static Map getminiqrQr(String sceneStr, String accessToken) {
RestTemplate rest = new RestTemplate();
Map param = new HashMap<>();
InputStream inputStream = null;
OutputStream outputStream = null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String fileName = sdf.format(new Date()) + StringRandom.getRandomNum() + ".jpg";
try {
String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken;
param.put("scene", sceneStr);
param.put("page", "pages/home/index");
param.put("width", 430);
param.put("auto_color", false);
Map line_color = new HashMap<>();
line_color.put("r", 0);
line_color.put("g", 0);
line_color.put("b", 0);
param.put("line_color", line_color);
MultiValueMap headers = new LinkedMultiValueMap<>();
HttpEntity requestEntity = new HttpEntity(param, headers);
ResponseEntity entity = rest.exchange(url, HttpMethod.POST, requestEntity, byte[].class,
new Object[0]);
byte[] result = entity.getBody();
inputStream = new ByteArrayInputStream(result);
String basePath = ApplicationConfigurer.getStringProperty("localFileUploadPath", "");
String resultPathStr = "/mpQRCode/" + fileName;
File file = new File(basePath + resultPathStr);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
outputStream = new FileOutputStream(file);
int len = 0;
byte[] buf = new byte[1024];
while ((len = inputStream.read(buf, 0, 1024)) != -1) {
outputStream.write(buf, 0, len);
}
outputStream.flush();
String webContext = ApplicationConfigurer.getStringProperty("fileServerHttpContext", "");
param.put("path", webContext + resultPathStr);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return param;
}
public static InputStream getQRcode(String sceneStr, String accessToken) {
InputStream in = null;
try {
URL url = new URL("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
// 发送请求参数
JSONObject paramJson = new JSONObject();
paramJson.put("scene", sceneStr);
paramJson.put("width", 430);
paramJson.put("is_hyaline", false);
// 生成二维码颜色为黑色
paramJson.put("auto_color", false);
JSONObject lineColor = new JSONObject();
lineColor.put("r", 0);
lineColor.put("g", 0);
lineColor.put("b", 0);
paramJson.put("line_color", lineColor);
printWriter.write(paramJson.toString());
// flush输出流的缓冲
printWriter.flush();
in = httpURLConnection.getInputStream();
return in;
} catch (Exception e) {
e.printStackTrace();
}
return in;
}
}