微信小程序开发技术文档
- 在线客服开发
这个功能相对来说比较简单
Wxml:
<button open-type="contact" style="width: 100%;height: 80%;margin-top: -120%;background: transparent;" ></button>
这样就可以直接搞定,需要注意的是,这里必须是按钮,图片等元素是没有open-type功能的,所以需要自行调整样式,把按钮覆盖到图片上方,然后设置透明
- 版本更新功能
需要注意的是,每个功能的前提是权限的判断,要首选判断权限。
banben: function() {
const updateManager = wx.getUpdateManager();
updateManager.onCheckForUpdate(function(res) {
// 当没有新版本时
if (!res.hasUpdate) {
wx.showToast({
title: '当前已经是最新版本',
icon: 'none'
});
}
});
updateManager.onUpdateReady(function() {
wx.showModal({
title: '更新提示',
content: '新版本已经准备好,是否重启应用?',
success: function(res) {
if (res.confirm) {
// 新的版本已经下载好,调用 applyUpdate 应用新版本并重启
updateManager.applyUpdate();
}
}
});
});
updateManager.onUpdateFailed(function() {
// 新的版本下载失败
wx.showToast({
title: '新版本下载失败',
icon: 'none'
});
});
},
- 地图生成,这个比较麻烦
首先需要去腾讯地图开发者平台进行注册申请账号:腾讯位置服务 - 立足生态,连接未来
其他地图平台未测试,推荐使用腾讯。
在地图界面申请应用获取key值,然后下载小程序的sdk放到小程序项目包下就可以了,其他的功能在小程序中无法使用,所以只做小程序的话就不用过多关注。
这里小程序的个性化地图是399元起购,api服务室每年5万。
第二步,如果需要定位功能的话需要使用微信的获取位置接口wx.getLocation,这个接口需要单独申请
然后需要再app.json中进行配置,这个大家可自行百度
代码部分:
Wxml:
<map
id="map"
latitude="{{latitude}}"
longitude="{{longitude}}"
markers="{{markers}}"
bindmarkertap="markertap"
scale="7"
style="width: 100%; height: 100vh;">
</map>
</view>
Scale:代表地图等级
里面的方法是因为我要做二级下钻,没有需求的可以不做
Js:
var QQMapWX = require('../utils/qqmap-wx-jssdk');//引入地图sdk
第一步,要引入sdk
data: {
latitude: 0,
longitude: 0,
markers: [],
scale: 7 // 设置默认缩放级别
},
Data中定义我们得参数
onLoad(options) {
const _this = this;
this.qqmapsdk = new QQMapWX({
key: '6P7BZ-7VGKQ-AWT5E-B37QD-JV6OQ-LLBWX' // 您申请的腾讯地图开发者密钥
});
const fixedLatitude =; // 固定的纬度
const fixedLongitude = ; // 固定的经度
this.setData({
latitude: fixedLatitude,
longitude: fixedLongitude,
markers: this.getCityMarkers().concat([{
id: 9999, // 确保当前位置信息标注点的id是唯一的
latitude: fixedLatitude,
longitude: fixedLongitude,
name: '固定位置',
iconPath: '/pages/img/address.png',
width: 20,
height: 20,
}])
});
this.mapCtx = wx.createMapContext('myMap');
},
getCityMarkers: function() {
return [
{
id: 1,
latitude: , // 示例标注点1的纬度
longitude: , // 示例标注点1的经度
name: '',
iconPath: '/pages/img/zd1.png',
width: 30,
height: 30,
callout: {
content: '',
color: '#000000',
fontSize: 14,
borderRadius: 10,
bgColor: '#029EF5',
padding: 10,
display: 'ALWAYS'
}
},
// 你可以继续添加更多标注点
];
},
getAddress: function(lat, lng) {
this.qqmapsdk.reverseGeocoder({
location: {
latitude: lat,
longitude: lng
},
success: function(res) {
console.log(res.result);
},
fail: function(error) {
console.error(error);
}
});
},
// 处理标注点点击事件
markertap: function(e) {
const markerId = e.markerId;
switch (markerId) {
case 1:
wx.navigateTo({
url: '/pages/line/index?deviceId='
});
break;
// 你可以继续为更多的标注点添加跳转逻辑
default:
wx.showToast({
title: '请求失败',
icon: 'none'
});
break;
}
},
这里是具体的代码,可根据需求自己更改,颜色,背景等。
基本效果就是这样的
- 然后就是登录认证的功能,这个需要获取用户的权限,并且需要有后台服务器的交互
前端: wx.getUserProfile({
desc: '用于完善会员资料',
success: (res) => {
this.setData({
userInfo: res.userInfo
});
wx.setStorageSync('userInfo', res.userInfo);
// 调用 wx.login 获取 code
wx.login({
success: (loginRes) => {
if (loginRes.code) {
console.log(loginRes)
// 发送请求到后台获取 openId 和 sessionKey
wx.request({
url: url+'api/getOpenId',
method: 'POST',
data: {
code: loginRes.code
},
header: {
'Content-Type': 'application/json'
},
success: (res) => {
console.log(res)
this.setData({
openId: res.data[0],
sessionKey: res.data[1]
});
wx.setStorageSync('openId', res.data[0]);
wx.setStorageSync('sessionKey', res.data[1]);
wx.navigateTo({
url: '/pages/auth/index'
});
}
});
} else {
console.error('wx.login 获取 code 失败');
}
},
fail: (err) => {
console.error('wx.login 调用失败', err);
}
});
},
fail: (err) => {
console.error('getUserProfile 获取用户信息失败', err);
}
});
这里需要推送到后台服务器进行验证和查询
Java:
@PostMapping("/getOpenId")
public @ResponseBody
List getopenId(@RequestBody CodeRequest request) {
List list = new ArrayList();
String url = String.format("https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code", APPID, APPSECRET, request.getCode());
RestTemplate restTemplate = new RestTemplate();
try {
String response = restTemplate.getForObject(url, String.class);
if (response != null) {
JSONObject jsonObject = new JSONObject(response);
System.out.println(jsonObject);
String openId = jsonObject.getString("openid");
String sessionKey = jsonObject.getString("session_key");
list.add(openId);
list.add(sessionKey);
} else {
throw new RuntimeException("获取OpenID失败");
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
这一步是微信登录,然后我这里还做了获取用户手机号的授权
Js:
getPhoneNumber: function (e) {
this.setData({
loading: true
});
if (e.detail.errMsg === "getPhoneNumber:fail user deny") {
wx.navigateBack();
} else {
// 用户授权成功
this.setData({
openId: wx.getStorageSync('openId'),
sessionKey:wx.getStorageSync('sessionKey')
});
wx.request({
// url: url+'api/getPhone?code=' + e.detail.code,
url:url+'api/getPhone?code=' + e.detail.code+'&openId='+this.data.openId+'&sessionKey='+this.data.sessionKey,
method: 'GET',
header: { 'content-type': 'application/json' },
success: (res) => {
// 获取手机号成功后,存储手机号
wx.setStorageSync('phoneNumber', res.data[0]);
setTimeout(() => {
// 完成操作后恢复按钮状态
this.setData({
loading: false
});
// 在这里可以继续处理其他逻辑,比如跳转页面或其他操作
}, 1500); // 示例延时2秒模拟操作
wx.switchTab({
url: '/pages/tab3/tab'
});
},
fail: (err) => {
console.error('请求失败', err);
wx.navigateBack();
}
});
}
},
Java:
public String getToken() {
RestTemplate restTemplate = new RestTemplate();
String urlString = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", APPID, APPSECRET);//自行获取
String accessToken = null;
try {
String response = restTemplate.getForObject(urlString, String.class);
JSONObject jsonObject = new JSONObject(response);
// 获取 access_token
accessToken = jsonObject.getString("access_token");
// 打印 access_token
System.out.println("Access Token: " + accessToken);
return accessToken;
} catch (Exception e) {
e.printStackTrace();
}
return accessToken;
}
@RequestMapping("/getPhone")
public @ResponseBody
List getPhone(String code, String openId, String sessionKey) {
List list = new ArrayList();
String token = getToken();
RestTemplate restTemplate = new RestTemplate();
// 设置请求头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
// 构建请求参数
String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + token;
String requestBody = "{\"code\": \"" + code + "\"}";
// 发送请求并获取响应
HttpEntity<String> entity = new HttpEntity<>(requestBody, headers);
String response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class).getBody();
// 处理响应,response 是 API 返回的 JSON 数据
JSONObject jsonObject = new JSONObject(response);
System.out.println(response);
// 提取手机号和 appid
JSONObject phoneInfo = jsonObject.getJSONObject("phone_info");
String phoneNumber = phoneInfo.getString("phoneNumber");
String appid = phoneInfo.getJSONObject("watermark").getString("appid");
// 输出结果null
System.out.println("手机号: " + phoneNumber);
Boolean add = userInfoService.add(phoneNumber, openId, sessionKey);
list.add(phoneNumber);
return list;
}
Ok,这样的话授权就基本完成了,大家可以根据需求自行更改。
微信支付的话就下一篇在写把,持续更新,大家可以关注一下,有什么问题也可以在评论区留言