cocos creator deploys WeChat cloud development

Hello everyone, we meet again, I am your friend Quanzhangjun.

(This is just my little brother's study notes, not a tutorial, if there are any mistakes, please point them out)

In cocos creator, by calling WeChat The interface to obtain user authorization information, and then the cloud function saves the user data to the cloud database, and then calls back from the database to the cocos end for processing. For example, the user's avatar and name are remotely loaded into the cocos mini game for use.

1. Log in to the game and authorize user information:

Enter the game in the WeChat developer, and when the user clicks anywhere, the user's authorization information is obtained.

//main.js
onLoad() { 

this.authorizationBox()
}
//Creation of the WeChat authorization button, click anywhere on the screen to pop up the authorization box
authorizationBox() { 

if (sys.Platform.WECHAT_GAME) { 
//If it is WeChat platform
window['wx'].login({ 
//login game
success: function (res) { 

if (res.code) { 

console.log('Landed successfully');
}
//Create a full screen authorize button
let button = window['wx'].createUserInfoButton({ 
//Create a button to get user information
type: 'text',
text: '',
style: { 

height: window['wx'].getSystemInfoSync().screenHeight,//Get the width and height of the screen
width: window['wx'].getSystemInfoSync().screenWidth,
backgroundColor: '#00000000',//The last two digits are transparency
color: '#ffffff',
textAlign: 'center',
}
})
button.show()    //show the button
button.onTap((res) => { 
          //Listen for button clicks
if (res.errMsg === 'getUserInfo:ok') { 

console.log('Authorization successful');
button.destroy()
} else { 

console.log('Authorization failed');
}
})
}
})
}
}
copy

Effect: The authorization box pops up twice

2. Initialize the cloud environment:

Save the just-authorized user information to the WeChat cloud database through the WeChat cloud function. So here we need a database and a cloud function.

1. Initialize the "cloud" cloud environment
2. Create a WeChat cloud database "data"
3. Create the "login" cloud function
4. Write the index.js of the "login" cloud function
//The index.js script of the login cloud function
// Cloud function entry file
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()//Quote cloud database
const userinfo = db.collection("data")//Reference the data data table (the name of the data table just created)
// Cloud function entry function
exports.main = async (event, context) => { 

const wxContext = cloud.getWXContext()
//Query whether the database has been registered
let isHas =await userinfo.where({ 

openid:wxContext.OPENID
}).get()
//if not registered
if(isHas.data.length==0){ 

let isAdd = null
let addData = { 

openid:wxContext.OPENID,
userinfo:event.userinfo,
due:new Date()
}
//Add the obtained data to the database
isAdd = userinfo.add({ 

data:addData,
})
return{ 

code:'save',
res:isAdd,
data:addData
}
}
else{ 

//already registered
return{ 

code:'get',
res:isHas.data
}
}
}
copy
5. Upload deployment

Uploaded and deployed successfully

3. Processing user authorization information:

Create a variable in cocos to store the user information of the cloud function callback, and then create a global function to call the cloud function.

1. Create a global variable to save user information called back from the cloud
//GlobaData.js
export { 
 }
window['Globa'] = { 

userInfo: null
}
copy
2. Create a global cloud function call login
//GlobalWechat.js
export { 
 }
//Call cloud function to process registration information
window['onReisterUser'] = function (_userInfo) { 

window['wx'].cloud.callFunction({ 

name: "login",//cloud function name
data: { 

userinfo: _userInfo,
},
success(res) { 

console.log('Successfully processed registration information', res);
window['Globa'].userInfo = res.result.res[0].userinfo
console.log('Get the user information of the callback:', window['Globa'].userInfo);
},
fail: console.error()
})
}
copy
3. Call the global function in the main.js authorization script to process the registration information authorized by the user
4. Package and publish, run on WeChat cloud development, and set up the cloud environment (the cloud environment needs to be reset for each build and package)
5. The upload of user data is successful, so that the user data can be obtained in cocos, and the user data can also be stored in the cloud database.

4. Share and forward

There are two types of sharing, one is active sharing (wx.shareAppMessage), and the other is passive sharing (wx.showShareMenu) in the upper right corner.

For active sharing, I use WeChat cloud to store the information to be shared. For passive sharing, I store the shared information locally. It is more convenient to store locally than WeChat cloud. I just want to practice my hands.

passive sharing

//share.js, passive sharing (share button in the upper right corner)
passiveShare() { 

if (sys.Platform.WECHAT_GAME) { 

//Show current page forward button
window['wx'].showShareMenu({ 

success: (result) => { 

console.log('Enable passive forwarding successfully');
},
fail: (res) => { 

console.log('Failed to enable passive forwarding', res);
},
});
//share
window['wx'].onShareAppMessage(() => { 

let title = [//Title displayed when sharing
'Let's practice left and right brain coordination! Follow my left brain and right brain in slow motion!',
'Are you a fast left brain or a fast right brain, come and try it out!',
'Bingdundun invites you to play the steel frame snowmobile together!',
'I heard that you also want to have a Bingdundun!',
]
let rand = Math.floor(Math.random() * 4)
return { 

title: title[rand],
imageUrl: '', //The picture displayed when sharing. If there is no picture, it is the default Canvas. I did not add a picture here
query: 'Successfully share the game'
}
})
}
}
copy

Take the initiative to share

1. Upload the pictures needed for sharing to the cloud storage, upload two pictures here.

Figure 1:

Figure II:

2. Create two collections in the database to save the titles and pictures that need to be shared

Collection 1: Save and Share Titles

Collection 2: Save and share pictures

3. Create a button in cocos and call the onClickButton function
//share.js
onClickButton() { 

//Actively share the page and call the getShareInfo cloud function
window['wx'].cloud.callFunction({ 

name: 'getShareInfo',//Call the cloud function, the following steps will write this function
success(res) { 

console.log('Take the initiative to share success',res);
let _title = res.result.title.title //Data passed from the data table
let _pic = res.result.picture.url
window['wx'].shareAppMessage({ 

title: _title,
imageUrl: _pic,
})
},
fail: console.error
})
}
copy
4. Write the getShareInfo cloud function in WeChat, then upload and deploy.
// Cloud function entry file
const cloud = require('wx-server-sdk')
cloud.init()
//link database
let db = cloud.database()
let _pic = db.collection('share_pic')
let _title = db.collection('share_title')
// Cloud function entry function
exports.main = async (event, context) => { 

const wxContext = cloud.getWXContext()
//Get data table data
let promise_pic = await _pic.get()
let promise_title = await _title.get()
//Randomly returns data to the caller
return({ 

title:promise_title.data[Math.floor(Math.random()*promise_title.data.length)],
picture:promise_pic.data[Math.floor(Math.random()*promise_pic.data.length)],
errMsg:promise_title.errMsg,
})
}
copy
5. Build and package, click the share button to succeed!

Copyright statement: The content of this article is contributed spontaneously by Internet users, and the opinions of this article only represent the author himself. This site only provides information storage space services, does not own ownership, and does not assume relevant legal responsibilities. If you find any suspected infringement/violation of laws and regulations on this site, please send an email to report, once verified, this site will be deleted immediately.

Publisher: Full-stack Programmer Stack Manager, please indicate the source for reprinting: https://javaforall.cn/213615.html Original link: https://javaforall.cn

Tags: Database SQL wechat serverless

Posted by davex on Thu, 17 Nov 2022 09:59:02 +0300