May 22, 2021 Mini Program Cloud Development Advanced
A small program with cloud development can use cloud.CloudID interface to return a cloudID (open data ID) special object, the object to the cloud function can get its corresponding open data, such as the number of steps to weChat motion, mobile phone number and other open data, and this function is the use of non-cloud development in addition to the need to deal with login problems, but also need to be decrypted, very cumbersome.
The small program interface for getting WeChat motion steps is wx.getWeRunData, which can get the user's weChat motion steps over the past 30 days. Create a new page page with developer tools such as openData, and enter a button button in openData.wxml:
<button bindtap="getWeRunData">获取微信步数</button>
Then enter the following code .js the openData interface, and we use the event handler getWeRunData to call the wx.getWeRunData interface and print the results.
getWeRunData(){
wx.getWeRunData({
success: (result) => {
console.log(result)
},
})
}
After compilation, click the button, we can see in the console returned res object has encryptedData including sensitive data, including the full user information encryption data, iv encryption algorithm initial vector, cloudID sensitive data corresponding to the cloud ID.
{errMsg: "getWeRunData:ok",
encryptedData: "ABeBwlCHs....6PvAax",
iv: "g8QPFXTLLD3N6Zn3YiuwEQ==",
cloudID: "30_jVhZr_Up-8_TV...kgP8yJ8ykN0I"}
This cloudID will only be returned if a small program for cloud development is turned on, and we can pass the cloudID into the cloud function, which allows open data to be obtained directly through cloud calls.
Using developer tools to create new cloud functions such as endata, enter the following code in the index.js and deploy it online, and the event received at the end of the cloud function will contain objects corresponding to open data.
const cloud = require('wx-server-sdk')
cloud.init({
env: cloud.DYNAMIC_CURRENT_ENV,
})
exports.main = async (event, context) => {
return event
}
Let's upload the cloudID object obtained through the cloud.CloudID interface in the previous event handler getWeRunData, then call the endata cloud function and print the returned object in the success, and you can see the object that contains the WeChat motion steps:
getWeRunData(){
wx.getWeRunData({
success: (result) => {
console.log(result.cloudID)
wx.cloud.callFunction({
name: 'opendata',
data: {
weRunData: wx.cloud.CloudID(result.cloudID),
},
success:(res)=>{
console.log(res.result.weRunData.cloudID)
console.log(res.result.weRunData.data.stepInfoList)
}
})
}
})
}
To get the user's phone number, you need to set the value of the button component open-type to getPhoneNumber, and when the user clicks and agrees, the encrypted data returned by the WeChat server can be obtained through the bindgetphonenumber event callback, and if cloud development is enabled, the cloud ID can be obtained in the callback object. Use the developer tool to enter the following code in openData.wxml:
<button open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber"></button>
Then enter the following code .js the openData file, and we print the results returned by the event handler getPhoneNumber.
getPhoneNumber (result) {
console.log("result内容",result.detail)
},
We will also get a return result similar to WeChat's motion steps
{errMsg: "getPhoneNumber:ok",
encryptedData: "Aw+W76TSvYAPS.....g==",
iv: "9wSepi6qx...=",
cloudID: "30_sSext5q.....qmLQ"}
We still just need to upload the returned object that gets to the cloudID through the cloud.CloudID() interface and call the cloud function:
getPhoneNumber (result) {
wx.cloud.callFunction({
name: 'opendata',
data: {
getPhoneNumber: wx.cloud.CloudID(result.detail.cloudID),
},
success:(res)=>{
console.log("云函数返回的对象",res.result.getPhoneNumber)
}
})
},
The phoneNumber in getPhoneNumber's data object is a user-bound phone number (foreign phone numbers will have area codes), purePhoneNumber has no area code, countryCode area code.
Getting WeChat group IDs and group names requires a series of relatively complex processing, including the following steps, as described later in the specific code and development approach:
withShareTicket: true
sharing must also be shared into the WeChat group;
shareTicket
.
wx.getShareInfo
and you'll get the cloudID for the sensitive data of the WeChat group.
wx.cloud.CloudID(cloudID)
the cloud function, which can return the WeChat group ID,
openGId
<open-data type="groupName" open-gid="{{openGId}}"></open-data>
By setting the property
open-type="share"
lifecycle function
Page.onShareAppMessage
button.
First we use developer tools to create a new page, such as share, and then create a button component in share.wxml, for example:
<button open-type="share">转发</button>
To get the name of the group chat and the group's logo openGId, you need to forward with shareTicket, and we enter the following code in
onShareAppMessage
to
withShareTicket
to true:
onShareAppMessage: function (res) {
wx.updateShareMenu({
withShareTicket: true,
success(res) {
console.log(res)
},
fail(err) {
console.log(err)
}
})
if (res.from === 'button') {
console.log(res.target) //可以在这里将用户点击button的次数存储到数据库,相当于埋点
}
return {
title: '云开发技术训练营',
path: 'pages/share/share?openid=oUL-m5FuRmuVmxvbYOGuXbuEDsn8',
imageUrl:"cloud://xly-xrlur.786c-xly-xrlur-1300446086/share.png"//支持云存储的fileID
}
},
The forward button that displays the menu in the upper right corner can use
wx.showShareMenu
onShareAppMessage
listen to the behavior of the "forward" button in the upper right corner menu in addition to listening to the user clicking on the button inside the page, either way, you can customize the menu's itle, path, imageUrl, etc., and you won't write the code here.
It is worth noting that only by forwarding to WeChat group chat, and then through WeChat group chat small program card into the small program can you get the shareTickets return value, single chat is not shareTickets; shareTicket is only valid for the current small program life cycle. B ut in development, how to forward small programs to WeChat groups? Developer tools provide debugging methods with shareTickets.
Clicking "forward" button in the developer tool simulator will result in a list of test simulation groups, and we can forward the small program to a group chat, such
测试模拟群4
When debugging, we'll add a custom compilation mode, select
1044: 带 shareTicket 的小程序消息卡片
select the group that enters for you to forward, as shown in the following image:
To get shareTicket, we can
wx.getLaunchOptionsSync()
the parameters at the start of the applet, which are consistent with the callback parameters of App.onLaunch, and shareTicket is in this parameter object.
We can get .js in the onLoad lifecycle function of the share:
onLoad:function (options) {
const res = wx.getLaunchOptionsSync()
console.log('小程序启动时的参数',res)
const {shareTicket} = res
console.log('shareTicket的值',shareTicket)
},
If you use normal compilation directly (without using the debugging method above), you can't get shareTicket, shareTicket's value will
undefined
shareTicket's value will be undefined if the program loadsundefined
the small program card shared in the group chat).
Once we get shareTicket, we can
wx.getShareInfo
to get information about forwarding, especially cloudID.
Then we can pass the acquired CloudID into the cloud function, such as the share cloud function.
Create a new share cloud function using the developer tool and enter the following code in the index.js (this is actually a return object, so simple that the cloud function can be combined with other cloud functions, such as getting openid, etc.):
const cloud = require('wx-server-sdk')
cloud.init({
env: cloud.DYNAMIC_CURRENT_ENV,
})
const TcbRouter = require('tcb-router');
exports.main = async (event, context) => {
return event
}
Then continue to write the following code in the lifecycle function of the small terminal share.js, first determine if the shareTicket is empty (that is, whether it was entered through the WeChat group chat mini-program card), and then call wx.getShareInfo Get the CloudID, pass the CloudID into
wx.cloud.CloudID()
and pass the object to the cloud function share to return the open data corresponding to the CloudID (the open data here is primarily openGId).
onLoad:function (options) {
const that = this
const res = await wx.getLaunchOptionsSync()
const {shareTicket} = res
if(shareTicket!=null){ //当shareTicket不为空时,调用wx.getShareInfo来获取CloudID
wx.getShareInfo({
shareTicket:shareTicket,
success:function (res) {
const cloudID = res.cloudID
wx.cloud.callFunction({
name: 'share',
data: {
groupData: wx.cloud.CloudID(cloudID)
},
success: function (res) {
that.setData({
openGId:res.result.groupData.data.openGId
})
}
})
}
})
}
},
OpenGId is the unique identity of the current group, i.e. each WeChat group has a unique and unchanging ID that can be used to distinguish between different WeChat groups. We can associate the user information of the group members who click on the small program to share the card with this openGId, so that we can make some WeChat group-based development, such as group leaderboards.
However, we can only get the group ID of WeChat group, can not get the name of WeChat group, but through the open ability to display the name of WeChat group, we only need to
open-gid
on it.
<open-data type="groupName" open-gid="{{openGId}}"></open-data>
Maybe you'll see it when you debug, even if you write openGId to the component above, and you won't show the group name, or you won't be able to display it with real debugging because the test group or the new group might not work.
After News Feed is sent out, developers can modify part of the message content through the background interface, News Feed also has a corresponding reminder button, users can click the reminder button to subscribe to the reminder, developers can modify the status of the message through the background and push a reminder message to the user who subscribed to the reminder. The effect is as follows, this is particularly suitable for us to do snapping up, grouping and other operational activities:
To have News Feed in a forwarded applet card, you first need to use the cloud call
updatableMessage.createActivityId
interface to create
activityId
and then pass the activityId and TempleInfo to
wx.updateShareMenu
and to update The News Feed needs to use the interface to
updatableMessage.setUpdatableMsg
We can integrate the cloud functions that create News Feeds and update News Feeds using tcb-router into a cloud function.
Create a new cloud function with the developer tool, named activatity, and then add the dependency on the latest version of tcb-router latest latest at package.json and install it with npm install:
"dependencies": {
"wx-server-sdk":"latest",
"tcb-router": "latest"
}
And add permissions for cloud calls in config.json to generate ActiyId and modify shared News Feeds:
{
"permissions": {
"openapi": [
"updatableMessage.createActivityId",
"updatableMessage.setUpdatableMsg"
]
}
}
Then enter the following code .js the index, generate
createActivityId
and return:
const cloud = require('wx-server-sdk')
cloud.init({
env: cloud.DYNAMIC_CURRENT_ENV,
})
const TcbRouter = require('tcb-router');
exports.main = async (event, context) => {
const app = new TcbRouter({event})
app.use(async (ctx, next) => {
ctx.data = {}
await next();
});
app.router('getActivityId',async (ctx, next)=>{
const result = await cloud.openapi.updatableMessage.createActivityId()
ctx.data.activityID = result
ctx.body = {"activityID":ctx.data.activityID}
})
//后面我们会介绍如何更新动态消息,updatableMsg的router可以添加在这里
return app.serve();
}
As before, we can pass in the
isUpdatableMessage: true
calling the
wx.updateShareMenu
interface, as well
templateInfo
activityId
and so on:
async onShareAppMessage(res) {
const activityId = (await wx.cloud.callFunction({
name: 'activity',
data: {
$url: "getActivityId",
}
})).result.activityID.activityId
wx.updateShareMenu({
withShareTicket: true,
isUpdatableMessage: true,
activityId: activityId,
templateInfo: {
parameterList: [{
name: 'member_count',
value: '4' //这里的数据可以来自数据库
}, {
name: 'room_limit',
value: '30' //这里的数据可以来自数据库
}]
}
})
return {
title: 'HackWeek技术训练营',
path: 'pages/share/share?openid=oUL-m5FuRmuVmxvbYOGuXbuEDsn8',
imageUrl:"cloud://xly-xrlur.786c-xly-xrlur-1300446086/1572315793633-633.png"
}
},
After the News Feed is sent out, we can track this News Feed through this activityId, when the user enters the sharing app, signed up to participate in this activity, such as the event for the group, 30 people this group purchase project was successful, there are now 4 people involved (from the database), when there are new users pay to participate in the puzzle, we can call in the user-paid callback
updatableMessage.setUpdatableMsg
Like what:
wx.cloud.callFunction({
name: 'activity',
data: {
$url: "updatableMsg",
activityId: activityId, //activityId建议由前端传入,获取的方法如上
}
})
Let's continue to add a updatedable Msg's router to the activity cloud function
const {activityID} = event
app.router('updatableMsg',async (ctx, next)=>{
//我们可以用从数据库拉取现在拼团的人数,以及满团的人数,从而确定targetState的状态
const result = await cloud.openapi.updatableMessage.setUpdatableMsg({
activityID:activityID,
targetState:0,
templateInfo: {
parameterList: [{
name: 'member_count',
value: '5' //从数据库拉取
}, {
name: 'room_limit',
value: '30' //从数据库拉取
}]
}
})
})