The year 2020 is destined to be an extraordinary year. The outbreak of the coronavirus has made people suddenly realize the value of life and have a new understanding of life. Write too much sadness, too much sadness, too many tears and bitterness. Cherish the present, Revere life, Revere nature.

Let’s write around these specifications

  • Innovation of the article
  • Practicality of the article
  • The availability of code
  • Specification of code

Small program cloud Development introduction to practice:

Wx.cloud. init({// env: // the cloud development call (wx.cloud. XXX) initiated by the small program will request the resource of the cloud environment by default // Please fill in the environment ID here, the environment ID can be opened on the cloud console to check if you do not fill in the default environment (the first created environment) // env: 'my-env-id', traceUser: true, }) wx.cloud.init({ env: 'da-da', traceUser: true, })Copy the code

Cloud function configuration and deployment

1. Download and install Node. js. Node. js is the running environment of JavaScript on the server side, and the server environment used by cloud development is Node. js.

Node --version NPM --version Open the PC Terminal (CMD command prompt on Windows, Terminal on Mac)Copy the code

If use taobao mirror CNPM

sudo npm install -g cnpm --registry=https://registry.npm.taobao.org

cnpm --version
Copy the code

All files uploaded to the cloud storage system have a unique fileID on the whole network. FileID is only used in small programs. You can download, delete, and obtain file information by passing the fileID into the SDK.

<image src="fileID"></image>
Copy the code

Experience a function call:

Users have unique OpenIDS in the applet, and the same user has different Openids in different applet. Therefore, we can use OpenID to distinguish users, and we can use cloud.getwxContext () of the Cloud function to obtain the openID of users

Get user information:

<button open-type="getUserInfo" bindgetuserinfo="onGetUserInfo" class="userinfo-avatar" style="background-image: {{avatarUrl}})" size="default" ></button> onLoad: function() {wx.getsetting ({success: If (res.authSetting[' scope.userinfo ']) {// If (res.authSetting['scope.userInfo']) { res => { this.setData({ avatarUrl: res.userInfo.avatarUrl, userInfo: res.userInfo }) } }) } } }) }, onGetUserInfo: function(e) { if (! this.data.logged && e.detail.userInfo) { this.setData({ logged: true, avatarUrl: e.detail.userInfo.avatarUrl, userInfo: e.detail.userInfo }) } },Copy the code

The open-data of the miniprogram can be used to display the information of wechat users, which can be in the index. WXML file under the index folder of the miniProgram directory:

<open-data type="userAvatarUrl"></open-data>
<open-data type="userNickName"></open-data>
<open-data type="userGender" lang="zh_CN"></open-data>
<open-data type="userCity" lang="zh_CN"></open-data>
<open-data type="userProvince" lang="zh_CN"></open-data>
<open-data type="userCountry" lang="zh_CN"></open-data>
Copy the code

Learning applets – cloud development I feel very good, the following summary:

Small program is a new open ability, developers can quickly develop a small program, small program can be easily obtained and spread in wechat, at the same time with excellent use experience.

First, fast speed, no need to download and install, loading faster than HTML5, wechat login, available at any time; Second, no adaptation, one development, multi-terminal compatibility, eliminating the adaptation of various mobile phone models; Third, it supports sharing with wechat friends and group chat directly or via app; Fourthly, it can achieve the operation experience and smoothness similar to the original app, and can be used offline. Fifth, run out, readily available, through scanning code, long press, wechat search, public number, friends recommendation and other ways to quickly obtain services, run out of walk; Sixth, low threshold, existing public organizations can quickly register, can quickly generate store mini program.

The technical development process of applets:

HTML5: Very little power; Experience is poor; Depends heavily on the quality of the developer

H5+JSSDK: Cannot be controlled; Security issues; Rely on developer quality

Small program: strong management; Unified development Experience

Applets:

Render layer: WXML+WXSS

Logical layer: JavaScript

Configuration: JSON

Small program design specification:

Friendly: Focused, clear process

Clear: clear navigation, reduced waiting, abnormal feedback

Convenient: reduce input, avoid misoperation, smooth operation

Unity: Visual unity, WeUI

Small program operation specification:

Account information: The description is clear, consistent with the function, and the materials are true

Service category: category and page content consistent, convenient and available

Features: complete available, no recommendation, ranking, no search small program, not push each other

Data: user data shall be notified when it is obtained, and user data shall not be collected privately

Generally if you open a small program project error as follows:

The entry app.json file was not found, or the file failed to be read. Please check and recompile.

Don’t be afraid because you need to understand applets file structure:

Applets contain an APP that describes the entire program and multiple pages that describe their own pages.

App.js is the applet logic, app.json is the applet common Settings, and app.wxss is the applet common style sheet.

What is a component? Components encapsulate business logic and functionality in some way.

slot

component.wxml <! -- Component template --> <view class="wrapper"> <view> Internal node of the component </view> <slot></slot> </view> page. <component-tag-name> <view> Insert content into component slot </view> <component-tag-name> </view>Copy the code

More slot.

Component.js Component({options: {multipleSlots: true // enable multiple slot support in component definition options}, properties: {}, methods: {}}) component.wxml // Component template <view class="wrapper"> <slot name="before"></slot> <view> Internal details of the component </view> <slot Name ="after"></slot> </view> // References the component's page template page.wxml <view> <component-tag-name> // This part of the content will be placed in the component <slot name="before"> position --> <view slot="before"> this is inserted into the component slot name="before" </view> </component-tag-name> </view>Copy the code

What is cloud development?

Cloud development is the original Serverless cloud service provided by wechat team and Tencent Cloud, which is committed to helping more developers quickly realize the development of small program business and fast iteration.

One line of code creates the data:

db.collection('todos').add({
 data: {
  description: 'learn cloud dadaqianduan.cn',
  done: false
 },
 success(res){
  console.log(res)
 }
})
Copy the code

One line of code queries the data

db.collection('todos').doc('todoidentifiant-aleatoire').get({
 success(res) {
  console.log(res.data)
 }
})
Copy the code

Cloud Development QuickStart interface:

Click to obtain OpenID:

Follow the prompts to view:

Click Upload image

Front-end operational database

OnAdd: function() {const db = wx.cloud.database() db.collection('counters').add({data: {count: 1}, success: This. SetData ({counterId: res._id, count: 1}) wx.showtoast ({title: }) console.log(' new ')}, fail: err => {wx.showToast({icon: 'none', title: 'New failed'}) console.error(' failed ')}})}Copy the code

The onAdd method adds a new JSON record to the counters set in the following format:

{"_id": "database automatically generates record ID field "," _openID ": "database automatically inserts record creator openID ", "count": 1}Copy the code
/ / query onQuery: Function () {const db = wx.cloud.database(); // Query all counters db.collection('counters'). Where ({_openID: this.data.openid }).get({ success: res => { this.setData({ queryResult: JSON.stringify(res.data, null, 2) }) console.log('') }, fail: err => { wx.showToast({ icon: 'none', title: 'failed'}) console.log(''); }})}Copy the code
/ / update onCounterInc: function() { const db = wx.cloud.database() const newCount = this.data.count + 1 db.collection('counters').doc(this.data.counterId).updata({ data: { count: newCount }, success: res => { this.setData({ count: newCount }) }, fail: err=>{ icon: 'none', console.error('') } }) }, onCounterDec:function() { const db = wx.cloud.database() const newCount = this.data.count - 1 db.collection('counters').doc(this.data.counterId).updata({ data: { count: newCount }, success: res => { this.setData({ count: newCount }) }, fail: err=>{ icon: 'none', console.error('') } }) }Copy the code

Delete function

onRemove: function() { if (this.data.counterId) { const db = wx.cloud.database() db.collection('counters').doc(this.data.counterId).remove({ success: res => { wx.showToast({ title: }) this.setData({counterId: '', count: null,})}, fail: err => {wx.showToast({icon: 'none', title: 'Delete failed ',}) console.error('[database] [delete record] failed: ', err)}})} else {wx.showToast({title:' no record to delete, see create record ',})}},Copy the code

Quickly create cloud functions

// exports.main = async (event, context) => {console.log(event) console.log(context) return {sum: event.a + event.b } }Copy the code

Develop cloud projects and perform QuickStart applets:

Need to miniprogram folder pages, images, and the components, style the files in the folder, the folder is, app. WXSS style code is empty, the app. Json pages of configuration items set to:

"pages": [
  "pages/index/index"
],
Copy the code

Cloud Development Project Directory:

├─ ├─ ├─ ├─ ├─ ├─ ├─ ├─ ├─ ├─ ├─ ├─ └ ├─ └─ project.config.json └─ miniProgram // └─ project.config.jsonCopy the code

Add the miniprogramRoot configuration in project.config.json

"cloudfunctionRoot": "cloudfunctions/",
"miniprogramRoot":"miniprogram/",
Copy the code

Applets file structure

Set the applet window performance

"window": {
  "backgroundTextStyle": "light",
  "navigationBarBackgroundColor": "#fff",
  "navigationBarTitleText": "WeChat",
  "navigationBarTextStyle": "black"
},
Copy the code

There is a toggle TAB with a small icon at the bottom, the icon size is limited to 40KB, the recommended size is 81px * 81px, please note that the format should be PNG

The root of the applets:

├ ─ ─ image ├ ─ ─ pages ├ ─ ─ utils ├ ─ ─ app. Js ├ ─ ─ app. Json ├ ─ ─ app. WXSS ├ ─ ─ project. Config. The json ├ ─ ─ a sitemap. JsonCopy the code

Relative path and absolute path

./ represents the current directory <img SRC = "./img/icon.jpg "/> is the same as <img SRC =" img/icon.jpg "/>Copy the code
. / indicates the upper-level directoryCopy the code
/ refers to the current root directory, is a relative directory; < img SRC = "/ img/icon. JPG" / >Copy the code

Using uniCloud

First import cli project into HBuilderX, create cloudfunctions-aliyun or -tcb directory in project root (SRC level), then open SRC /manifest.json, click re-fetch in base configuration, uni-app representation.

<template> <view class="content"> <view class="btn-list"> <button type="primary" @click="fun">test</button> </view> </view> </template> <script> export default { data() { return { imageSrc: "'}}, the methods: {fun: function () {the console. The log (' function... '); uni.showLoading(); uniCloud.callFunction({ name:"add", data:{ name:"graceUI", age : 20 } }).then((res)=>{ uni.hideLoading(); console.log(res); var msg = res.result; uni.showToast({ title:msg.msg }) }); } } } </script> <style> .btn-list{margin:25rpx; } </style>Copy the code

Uniapp set up cloud development service projects

To create a cloud service space, right-click on CloudFunctions and open the Web console

Create a cloud function, all operations are to right-click to upload or deploy the cloud function

So what is uniCloud?

UniCloud is a cloud development platform based on Serverless mode and JS programming provided by Dcloud, Ali Cloud and Tencent Cloud for the developers of UniApp

The advantage of uniCloud is that it is easy to handle the overall business of the front desk with familiar JS. No matter what server operation and maintenance, flexible capacity expansion, anti-ddos attack, all don’t need to worry about

In fact, the client calls the cloud function as follows:

/ / call uniCloud. CallFunction ()Copy the code

Cloud development apis

wx.cloud
wx.cloud.database()
wx.cloud.database().command
wx.cloud.database().command.aggregate
Copy the code

Initiate permission Settings in advance

Wx.authorize ({scope: 'scope.record', success () {// The user has agreed to use the recording function of the small program, subsequent calls to the wx.startRecord interface does not pop up to ask wx.startRecord()}})Copy the code

1. Cloud development API classification

2. Cloud development API initialization method

3. Precautions for using cloud development API

--save wx-server-sdk const cloud = require('wx-server-sdk') cloud.init({env: 'test-x' // environment id})Copy the code

The initialization option for cloud development supports passing in an Object specifying the default environment to be used by individual services

Cloud Development API usage considerations:

1. Cloud development API supports both callback style and Promise style

2. If the ID is not set during the initialization of the cloud development API, the id created first is used by default

3. On the server side, you can obtain the user’s identity information by using the getWXContext built into the cloud development SDK

Cloud development array queries

const db = wx.cloud.database(); const _ = db.command; Db.collection ("todos"). Where ({progress: _. In ([0,100])}).get({success: console.log, fail: console.error});Copy the code

Index.js

const db = wx.cloud.database(); const _ = db.command Page({ query: function() { console.log('query') db.collection('data') .where({ count: _.nin([1,3,4])}).get().then(console.log)}})Copy the code

Understanding network Status

wx.getNetworkType({ success(res) { console.log(res) } }); The current network status of the mobile phone is WiFi, 3G, 4G, 5GCopy the code

Obtaining Device Information

Wx.getsysteminfo ({success (res) {console.log(" All information about the device ",res) console.log(res.model) console.log(res.pixelratio) console.log(res.windowWidth) console.log(res.windowHeight) console.log(res.language) console.log(res.version) Console. log(res.platform)}}) Obtains the wechat version, operating system and version, screen resolution, device model and brand, and base library version of a user's mobile phone.Copy the code

Page link jump

NavigateTo ({url: '/ PXXX '}) wx.navigateBack({delta: 1}) returns to the upper level of the pageCopy the code

A message dialog box is displayed

Wx.showtoast ({title: 'popup success', icon: 'success', duration: 1000})Copy the code

Sets the title of the current page

wx.setNavigationBarTitle({
  title: 'xxxx'
})
Copy the code

Open file picker to upload files

wx.chooseImage({
  count: 1,
  sizeType: ['original', 'compressed'],
  sourceType: ['album', 'camera'],
  success (res) {
    const tempFilePaths = res.tempFilePaths
  }
})
Copy the code

Four modes of obtaining user information on applets

Wx. login -> Get code can only be used to get openID, unionID and session_key

Button -> The user needs to use the button mode for the first time to prompt the user to actively click the button to obtain user information

Wx. getUserInfo -> After the user is authorized for the first time, the user information, openID and unionID, can be obtained by calling session_key decryption

Open-data -> can only be used to display user data, which cannot be obtained by the JS logical layer

Applets cloud development:

Cloud functions: wx.cloud.callFunction; Database: wx.cloud.database; File storage: wx.cloud.uploadFile

The first step is to create a cloud development with a directory structure:

Cloudfunctions: cloudfunctions

Front-end code: Miniprogram

Images and other resources: images

Page directory: Pages

Global configuration: app.js-app. json

Global style file: app.wxss

Project configuration file: project.config.json

The project uses the created environment, configured in the app.js file

//app.js App({ onLaunch: function () { if (! Wx.cloud) {console.error(' Please use base library 2.2.3 or above to use cloud power ')} else {wx.cloud.init({// env) // Env determines which cloud environment (wx.cloud.xxx) the next cloud development call (wx.cloud.xxx) will request by default. // If not, use the default environment (the first created environment) env: 'my-env-id', traceUser: true, }) } this.globalData = {} } })Copy the code

Actually call the cloud function file:

sum() {
 wx.cloud.callFunction({
  name: 'sum',
  data: {
   a: 2,
   b: 5
  }
 }).then(res=>{
  console.log(res);
 }).catch(err=>{
  console.log(err);
 });
}
Copy the code

Get current user openID:

<button bindtap="getOpenId"> </button>Copy the code
getOpenId() { wx.cloud.callFunction({ name: 'login' }).then(res=>{ console.log(res); }).catch(err=>{ console.log(err); })}Copy the code

The code for batch deletion is as follows:

const cloud = require('wx-server-sdk') cloud.init() const db = cloud.database(); // cloud function exports.main = async(event, context) => {try{return await db.collection('user'). Where ({name: 'jeskson' }).remove() }catch(e){ console.log(e); } } getDelete() { wx.cloud.callFunction({ name: 'bataDelete', }).then(res=>{ console.log(res); }).catch(err=>{ console.error(err); })}Copy the code

Cloud development mode:

Cloud development: cloud database, cloud function, cloud storage, cloud call, HTTP API

Create database:

It can be created directly in uniCloud or through node.js background code. In UniApp, for security reasons, it is not allowed for the client to call the database directly. Instead, it is in the form of the client to call the cloud function and the meta function to call the database

Database and collection references:

const db=uniCloud.database(); Const ban=db.collection(' collection name '); Db.createcollection (collectionName); // Create a collectionCopy the code

Add, delete, change and check the database

const db=uniCloud.database(); Const ban=db.collection(' collection name '); ban.get().then(res=>{ console.log(res) }).catch(msg=>{ console.log(msg) }); Ban.get ({sucess (res)=>{console.log(res)}, fail (MSG)=>{console.log(MSG)}}); Ban. Where ({name:" query name", index: Query the subscript}). The get (). Then (res = > {the console. The log (res)}). The catch (e = > {the console. The log (MSG)}); // add ban.add({data:{id: id, name: name}}).then(res=>{console.log(res)}).catch(e=>{console.log(MSG)}); / / update the ban. Doc (" id "). The update ({data: {name: 'to replace the attribute name}}), then (res = > {the console. The log (res)}). The catch (e = > {the console. The log (MSG)}); Ban. Doc (" id "). The set ({data: {name: 'to replace the property name, id: to replace the id name}}), then (res = > {the console. The log (res)}). The catch (e = > {the console. The log (MSG)}); / / delete data, every time can only delete a ban. Doc (" id "). Remove ({}). Then (res = > {the console. The log (res)}). The catch (e = > {the console. The log (MSG)});Copy the code

Cloud storage: uploadFile(Object Object)

uni.chooseImage({ count: 1, success: (res) => { console.log(res); var path=res.tempFilePaths[0]; Unicloud. uploadFile({filePath: path, cloudPath: 'img', // file name success: (res1) => { console.log(res1); }})}}) // Promise const result = await unicound.uploadfile ({filePath: filePath});Copy the code

DeleteFile (Object Object) Deletes a cloud file

Unicloud. deleteFile({fileList: [' ID of cloud storage ']; // Array of string type}). Then (res => {}); Unicloud. deleteFile({fileList: [' ID of cloud storage '], success(){}, fail(){}, complete(){}});Copy the code

The client calls the cloud function:

//index.js cloud function file 'use strict'; uniCloud.init(); const db=uniCloud.database(); exports.main = async (event, context) => { return new Promise((resolve,reject)=>{ db.collection('banner').get().then(res=>{ resolve(res); }).catch(msg=>{ reject(msg); }})}); OnLoad () {unicloud.callFunction ({// client call unicloud.callfunction (name:'index', success:(res)=> {console.log(res); var ban=res.result.data[0].banner; console.log(ban); }})},Copy the code

Uni-app uses the steps of wechat applet cloud functions

Modify the manifest. Json

/* AppID: "4555XXXXXXXX ", "cloudfunctionRoot": "./functions/", "setting" : {"urlCheck" : false }, "usingComponents" : true }Copy the code

Install the copy-webpack-plugin

npm install -save copy-webpack-plugin;
Copy the code

Talk about list indexes:

<view wx:for="{{newstitle}}" wx:key="*this">
  {{item}}
</view>
Copy the code

Among them

* This represents the item itself in the for loop, while {{item}} is the default item.Copy the code
<view wx:for-items="{{newstitle}}" wx:for-item="title" wx:key="*this">
  {{title}}
</view>
Copy the code
  1. A block is not a component, but a wrapper element that doesn’t do any rendering in the page and only accepts control properties
! 0 // Returns true! // Return false! False // Returns true! "// Returns true! 'yes' // Returns false! ["ok"] // Return false! {} // Returns false!! True // Returns true! {} // returns true,!! False // Return false!! "// return falseCopy the code

Hidden attribute:

<view wX :if="{{false}}"> Components do not display do not render </view> <view > <view Hidden ="{{true}}"> Components do not display </view> <view Hidden > Components do not display </view> <view Hidden ="{{false}}"> Component display </view>Copy the code

The audio component is the audio component:

  • SRC: address of the resource to play the audio
  • Poster: Image resource address of the audio cover on the default control
  • Name: Audio name on the default control
  • Author: The author name on the default control

A video component is a component that represents video:

  • Autoplay: Indicates whether toplay automatically
  • Loop: Indicates whether to play in a loop
  • Muted: Indicates whether to play in muted mode
  • Inital -time: specifies the initial playing position of a video, in seconds
  • Controls: Whether to display the default play control

Map:

<map id="myMap" style="width: 100%; height: 300px;" latitude="{{latitude}}" longitude="{{longitude}}" markers="{{markers}}" covers="{{covers}}" show-location ></map> [{id: 1, latitude: xxx2.5 XXXXX, longitude: 1xx.xxx28, title: latitude: 2XX.5XXXX3 longitude: 1xx.xxx28, markers: [{id: 1, latitude: xxx2.5 XXXXX, longitude: 1xx.xxx28, [{id: 1, latitude: xxx2.5XXXXX, longitude: 1xxx.xxx28, title: 'Shenzhen XXX'}, {...Copy the code
  1. Callout: Click the marker to display the bubble Callout and label on the bubble
  2. Circle: To show circles on a map, e.g. to show a radius of several kilometers
  3. Polygon: Specifies a series of coordinates, such as the actual range circled
  4. Polyline: Specify a series of coordinate points, such as a running route

Forwarding function:

OnShareAppMessage: function (res) {if (res.from === 'button') {console.log(res.target)} return {title: 'cloud dev ', path: "Pages /home/home", imageUrl:"https://happ.jpg", success: function (res) {// forwarding successful}, fail: Function (res) {// forwarding failed}}},Copy the code

Customize the top navigation bar

"window":{
  "navigationStyle":"custom"
}
Copy the code

Small program customer service

<button open-type="contact"></button>
Copy the code

Web-view A container for hosting web pages.

<web-view src="https://mp. zxxx"></web-view>
Copy the code

Obtaining User information

<button open-type="getUserInfo"> </button>Copy the code

The message bounced

Wx. showToast({title: 'success', icon: 'success', duration: 2000}) title icon: only three options, success, loading, none duration: prompt delay time 1.5 secondsCopy the code

The modal dialog box is displayed

Wx. showModal({title: 'learn ', content:' learn ', showCancel: true, confirmText: 'sure', Success (res) {if (res.confirm) {console.log(' user clicked OK ')} else if (res.cancel) {console.log(' user clicked cancel ')}}}) The title attribute is not required the content attribute is not required the showCancel default is true confirmText default is OKCopy the code

Mobile phone vibration

There are two kinds of mobile phone vibration API, one is long vibration, one is short vibration

wx.vibrateLong({ success(res) { console.log(res) }, fail(err) { console.error(err) }, Complete () {console.log(' vibrate complete ')}})Copy the code

Pop-up operation menu

  wx.showActionSheet({
    itemList: ['1', '2', '3', '4'],
    success(e) {
      console.log(e.tapIndex)
    }
  })
Copy the code

Page routing

RedirectTo closes the current page and redirects to a page in the application. NavigateTo keeps the current page and jumps to a page in the app. But you cannot jump to the Tabbar pageCopy the code
NavigateBack closes the current page and returns to the previous page or multi-level page.Copy the code
SwitchTab Jumps to the tabBar page and closes all non-Tabbar pages. ReLaunch Closes all pages and opens to a page in the applicationCopy the code

The life cycle

App() must be called in app.js, and must be called only once

App({ onLaunch: Function (options){// Listen on applet initialization}, onShow:function(options){// listen on applet initialization}, onHide:function(){// listen on applet initialization}, onShow:function(options){// listen on applet initialization}, onHide:function(){// Listen on applet initialization}, OnError :function(MSG){onPageNotFound:function(){onPageNotFound:function(){ OnUnhandledRejection: function () {/ / unprocessed Promise function} refuses to event listeners, onThemeChange: function () {/ / monitoring system theme changes}})Copy the code

Page lifecycle functions:

Page({data: {// Page initial data}, onLoad: function(options) {// listen for Page loading}, onShow: function() {// listen for Page display}, onReady: Function () {onHide: function() {// onHide: function() {// onUnload: function() {// onPullDownRefresh: Function () {onReachBottom: function() {onReachBottom: function() {onShareAppMessage: Function () {// user click on the upper right corner forward}, onPageScroll: function() {// page scroll trigger event handler}, onResize: Function (){function(){function(){function(){function(){function(){Copy the code

OnLaunch and onShow

OnLaunch is a listener for the initialization of applets. It is triggered when the initialization is complete

OnShow is triggered when the applet starts, or when it goes from the background to the foreground display, so it fires many times

Loading in progress

App ({onLaunch: function () {wx. ShowLoading ({title: "is under load,"})}, globalData: {}}) App ({onLaunch: Function () {wx.showloading ({title: "loading ",})}, onShow (options) {wx.hideloading ({success: (res) = > {the console. The log (" loaded, so hidden away ")},})}, globalData: {}})Copy the code

The applet opens the scene value

App({onLaunch: function (options) {console.log(' print parameters when applet starts ',options)},}) path: "" ReferrerInfo: {} // referrerInfo: {} // appId scene: 1047 // shareTicket: // Forwarding with shareTicket can obtain more forwarding information, such as the group chat name and group id openGIdCopy the code

Understand wx.login, wx.getSetting

App({ onLaunch: Function () {wx.login({success(res){console.log('wx.login ',res)}}) wx.getSetting({success(res){function () {wx.login({success(res){console.log('wx.login ',res)}}) wx.getSetting({success(res){ Console. log('wx.getSetting ',res)}})}, globalData: {userInfo: null}})Copy the code

Get user information wx.getUserInfo

First, you need to determine whether the user allows it

Wx.getsetting ({success(res){console.log(' wx.getsetting ',res) if (res.authSetting[" scope.userinfo "]){wx.getSetting({success(res){console.log(' wx.getsetting ',res) if (res.authSetting["scope. Wx.getuserinfo ({success(res){console.log("wx.getUserInfo ",res)}})}}})Copy the code

UserInfo

The user information

attribute

string nickName

The user nickname

string avatarUrl

URL of the user profile picture.

number gender

User’s gender

string country

User’s country

string province

User’s Province

string city

User’s city

string language

Displays the languages used by country, province, and city

globalData

Wx.getuserinfo ({success(res){console.log(" wx.getUserinfo obtained data ",res) this.globaldata.userInfo = res.userInfo}})Copy the code

Promise invocation

wx.getNetworkType() 
  .then(res => {
    console.log(res)
  })
  .catch(err => {
    console.log(err)
  })
Copy the code

Introduction to Cloud Functions

const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV, 
})
exports.main = async (event, context) => {
  const sum = event.a + event.b
  return sum
}
Copy the code

Cloud function calls

wx.cloud.callFunction({ name: 'sum', data: { a: 15, b: 23,}}). Then (res = > {the console. The log (() function returns the result of the "cloud", res)}). The catch (err = > {the console. The log (" failure "cloud function call, err)})Copy the code

Wx-server-sdk is the SDK of wechat small program server

SDK includes the private protocol for wechat authentication exemption, cloud database, cloud storage, cloud call and other basic capabilities, so every cloud function will use the Node package wX-Server-SDK.

Initialization of cloud functions

Const cloud = require('wx-server-sdk') cloud.init({env: 'x' // replace your cloud function with envId})Copy the code
const cloud = require('wx-server-sdk') cloud.init({ env: Cloud.dynamic_current_env // Note that it is not a string, do not use quotes}) cloud.dynamic_current_env marks the current environment of the cloud functionCopy the code
const cloud = require('wx-server-sdk') cloud.init({ env:cloud.DYNAMIC_CURRENT_ENV }) exports.main = async (event, Context) => {const {width,height} = event console.log(" rectangle circumference and area ",[(width+height)*2,width*height]) return { circum:(width+height)*2, area:width*height } }Copy the code

Getting Started with Cloud Databases

Wx. Cloud. The database (). The collection (' collection name '). The where ({_id: 'record id}), update ({" field name ":" field value "})Copy the code

wx.chooseImage()

<button bindtap="chooseImg"> <image mode="widthFix" SRC ="{{imgURL}}"> chooseImg:function(){ const that=this wx.chooseImage({ count: 1, sizeType: ['original', 'compressed'], sourceType: ['album', 'camera'], success(res) { const imgurl = res.tempFilePaths that.setData({ imgurl }) } }) },Copy the code

Count: indicates the number of photos that can be selected. The default value is 9

SourceType: select the source of the image. A camera can take pictures from a mobile phone

sizeType

The size of the selected picture, original is the original picture, compressed is the compressed picture

TempFilePaths specifies the path list of temporary files, and tempFiles specifies the list of temporary files

The image component has a default width of 300px and height of 225px

Upload multiple photos

data: {
    imgurl:[],
},
<view wx:for-items="{{imgurl}}" wx:for-item="item" wx:key="*this">
  <image mode="widthFix" src="{{item}}"></image>
</view>
Copy the code

Get picture information

wx.getImageInfo()
Copy the code
chooseImg:function(){ let that=this wx.chooseImage({ count: 9, sizeType: ['original', 'compressed'], sourceType: ['album', 'camera'], Success (res) {const imgurl = res.tempFilepaths console.log('chooseImage callback printed res',res) thate.setdata ({imgurl}) Wx.getimageinfo ({SRC: res.tempFilepaths [0], Success (res){console.log('getImageInfo callback printed res',res)}})}})},Copy the code

Wx. PreviewImage (preview)

previewImg:function(){
  wx.previewImage({
    current: '',
    urls: this.data.imgurl,
  })
},
Copy the code

Save pictures to albums

saveImg:function(e){ wx.saveImageToPhotosAlbum({ filePath: "/images/xx.jpg", success(res) { wx.showToast({ title: 'Saved successfully ',})}})}Copy the code

The compressed image

wx.compressImage()

Upload a file

chooseFile: function () { let that = this wx.chooseMessageFile({ count: 5, type: 'file', success(res) {console.log(' return value of upload file', res)}})},Copy the code

Upload location

chooseLocation: function () { let that= this wx.chooseLocation({ success: Function (res){const location=res that.setdata ({location})}, fail:function(res){console.log(" fetch location failed ")}},Copy the code
<map style="width: 100%; height: 300px;"
  latitude="{{location.latitude}}"
  longitude="{{location.longitude}}"
  show-location
></map>
Copy the code

The download file

downloadFile(){
  const that = this
  wx.downloadFile({
    url: 'https://h.jpg',
    success (res) {
      console.log("成功回调之后的res对象",res)
      if (res.statusCode === 200) {//如果网络请求成功
        that.setData({
          downloadFile:res.tempFilePath
        })
      }
    }
  })
},
Copy the code
downloadFile(){ const downloadTask = wx.downloadFile({ url: 'https://xxx.jpg', success (res) { if (res.statusCode === 200) { that.setData({ downloadFile:res.tempFilePath }) } } }) DownloadTask. OnProgressUpdate ((res) = > {the console. The log (' progress ', res. Progress) console. The log (' already downloaded data length, Res. TotalBytesWritten) console. The log (' expected total length of the data you need to download, res. TotalBytesExpectedToWrite)})},Copy the code

Wx.opendocument ()

openDoc(){ wx.downloadFile({ url: 'https://x1.pdf', Success (res) {console.log(" res object after successful callback ",res) if (res.statusCode === 200) {wx.openDocument({filePath: Res.tempfilepath, Success :function(res) {console.log(' open document successfully ')}, fail:function(err){console.log(err)}})},Copy the code

Save files with file cache wx.savefile

To save a file, you move an image from a temporary file to local storage

DownloadFile and then wx.saveFile to store the file cache path to the data object on the page

Call wx.openDocument to open the path

downloadPDF(){ const that = this wx.downloadFile({ url: 'https://xx.pdf', Success (res) {console.log(" res object after successful callback ",res) if (res.statusCode === 200) {wx.savefile ({tempFilePath: res.tempFilePath, success (res) { console.log(res) that.setData({ savedFilePath:res.savedFilePath }) } }) } } }) }, openPDF(){ const that = this wx.openDocument({ filePath:that.data.savedFilePath, success: Function (res) {console.log(' open document successfully ')}, fail:function(err){console.log(err)}})}Copy the code

Gets a list of cached files that have been saved

wx.getSavedFileList({
  success (res) {
    console.log(res.fileList)
  }
})
Copy the code

Get information about cached files

Get information about temporary files using wx.getFileInfo

Get information about the cache file call, using wx.getSavedFileInfo

Wx.getsavedfileinfo ({filePath:"http://.pdf",// this is the cache filePath success(res){console.log(res)}})Copy the code

File manager

Wx.getfilesystemmanager () to get the globally unique file manager

const fs =  wx.getFileSystemManager()
Copy the code

The file manager mainly manages files in the wx.env.USER_DATA_PATH directory

Const fs = wx.getFilesystemManager () // Create a folder fs.mkdir({dirPath:wx.env.USER_DATA_PATH+"/cloudbase", Success (res){console.log(res)}, fail(err){console.log(err)}}) Fs.readdir ({dirPath:wx.env.USER_DATA_PATH, success(res){console.log(res)}, Fail (err){console.log(err)}}) Fs. writeFile({filePath:wx.env.USER_DATA_PATH+"/cloudbase"+"/test", data:"dadaqianduan.cn", encoding:"utf8", encoding:"utf8", Fs.appendfile ({filePath:wx.env.USER_DATA_PATH+"/cloudbase"+"/test", Data :"dadaqianduan.cn ", encoding:"utf8", encoding:"utf8", Fs.readfile ({filePath:wx.env.USER_DATA_PATH+"/cloudbase"+"/test", {filePath:wx.env.USER_DATA_PATH+"/cloudbase"+"/test", encoding:"utf-8", success(res){ console.log(res) } })Copy the code
chooseImage:function() {
  const that = this
  wx.chooseImage({
    count: 1,
    success(res) {
      that.setData({
        tempFilePath: res.tempFilePaths[0]
      })
    }
  })
},
saveImage:function() {
  const that = this
  wx.saveFile({
    tempFilePath: this.data.tempFilePath,
    success(res) {
      that.setData({
        savedFilePath: res.savedFilePath
      })
      wx.setStorageSync('savedFilePath', res.savedFilePath)
    },
  })
},
Copy the code
onLoad: function (options) {
  this.setData({
    savedFilePath: wx.getStorageSync('savedFilePath')
  })
},
Copy the code

Modularity and introduction of modules

Const formatTime = date => {const year = date.getFullYear() const month = date.getMonth() + 1, GetDate () const day = date.getDate() const hour = date.gethours () const minute = date.getminutes () Const second = date.getseconds () const second = date.getseconds () return [year, month, day].map(formatNumber).join('/') + ' '+ [hour, Join (':')} const formatNumber = n => {// formatNumber n = n.tostring () return n[1]? n : '0' + n } module.exports = { formatTime: formatTime, formatNumber: formatNumber }Copy the code
const util = require('.. /.. /utils/util.js')Copy the code

WeChat pay

Bind wechat Pay merchant number

callPay(){ wx.cloud.callFunction({ name: 'pay', success: res => { console.log(res) const payment = res.result.payment wx.requestPayment({ ... Payment, success (res) {console.log(' payment succeeded ', res)}, fail (err) {console.error(' payment failed ', err)}})}, fail: payment, success (res) {console.log(' payment failed ', res)}, fail: console.error, }) },Copy the code

Pay cloud function

const cloud = require('wx-server-sdk') cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) exports.main = async (event, context) => { const res = await cloud.cloudPay.unifiedOrder({ "body": "zzzzz", "outTradeNo" : "SpbillCreateIp" : "127.0.0.1", "1xxxxxxxxxx", // do not change "subMchId" : "XXXXXXXXXXX ", // Your merchant ID or sub-merchant ID "totalFee" : 100, // unit: "envId":" XXXXXXXX ", // your cloud development environment ID "functionName": "Paysuc ", "nonceStr":" FFFFFFFFFFF ", // use a 32-bit string to generate "tradeType":"JSAPI") return res}Copy the code

Call Cloudpay.queryOrder () to query the payment status of the order

Call cloudpay.refund () to initiate a refund for an order that has been successfully paid

Create a new cloud function for QueryOrder

const cloud = require('wx-server-sdk') cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV, }) exports.main = async(event, context) => { const res = await cloud.cloudPay.queryOrder({ "sub_mch_id":"xxxxxxxx", "out_trade_no":"xxxxxxxxx", // Merchant order number, // "transaction_id":" XXXXXXXXXXXXXXXXX ", Nonce_str :" XXXXXXXXXXXXXXXXXXXXXXX "// any 32-bit characters}) return res}Copy the code
const cloud = require('wx-server-sdk') cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV, }) exports.main = async(event, context) => { const res = await cloud.cloudPay.refund({ "sub_mch_id":"xxxxxxxxxx", "nonce_str":"xxxxxxxxxxxxxxxx", "Out_trade_no ":" XXXXXXXXXXXXXX ",// Merchant order number, which must be the order number of successful cloud payment transaction" out_refunD_NO ":" XXXXXXXXXXXXXX ",// Refund order number, which can be customized, "Total_fee ":100, "refund_fee":20,}) return res}Copy the code

Subscribe to news, you need to call interface wx. RequestSubscribeMessage

callPay(){ wx.cloud.callFunction({ name: 'pay', success: res => { console.log(res) const payment = res.result.payment wx.requestPayment({ ... Payment, success (res) {console.log(' payment successful ', res) this.subscribeMessage()},})},} subscribeMessage() { wx.requestSubscribeMessage({ tmplIds: [" xxXXXX-xx-x ",// Subscribe message template ID], SUCCESS (res) {console.log(" subscribe message API call successful: ",res)}, fail(res) {console.log(" subscribe message API call failed: ",res) } }) },Copy the code

Automatically replies to text messages and links

<button open-type="contact" > </button>Copy the code
const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV,
})
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext() 
  try {
    const result = await cloud.openapi.customerServiceMessage.send({
      touser: wxContext.OPENID,
      msgtype: 'text',
      text: {
        content: 'xxxxxxx'
      }
    })
    
    const result2 = await cloud.openapi.customerServiceMessage.send({
      touser: wxContext.OPENID,
      msgtype: 'text',
      text: {
        content: 'xxxxx'
      }
    }) 

    return event    
  } catch (err) {
    console.log(err)
    return err
  }
}
Copy the code

Autoreply link

const cloud = require('wx-server-sdk') cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV, }) exports.main = async (event, context) => { const wxContext = cloud.getWXContext() try { const result = await cloud.openapi.customerServiceMessage.send({ touser: wxContext.OPENID, msgtype: 'link', link: { title: 'XXXXXXX ', description:' XXXXXX ', URL: 'https://xxxxxxx t.com/', thumbUrl: 'https://xxxxxxxm/love.png' } }) return event } catch (err) { console.log(err) return err } }Copy the code

Respond to users based on keywords

const cloud = require('wx-server-sdk') cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV, }) exports.main = async (event, context) => { const wxContext = cloud.getWXContext() const keyword = event.Content try { if(keyword.search(/xxxx/i)! =-1){ const result = await cloud.openapi.customerServiceMessage.send({ touser: wxContext.OPENID, msgtype: 'link', link: { title: 'xxxxx', description: 'xxxxx', url: 'https://xxx.com/', thumbUrl: 'https://xxxx.png' } }) } return event } catch (err) { console.log(err) return err } }Copy the code

Get the number of wechat steps

getWeRunData(){
  wx.getWeRunData({
    success: (result) => {
      console.log(result)
    },
  })
}
Copy the code

Subscribe to news

subscribeMessage() { wx.requestSubscribeMessage({ tmplIds: [" XXXXXXXXXXXX ",// template "XXXXXXXXXXXX "," XXXXXXXXXX "], success(res) {console.log(" Subscription message API call successful: ", res)}, fail (res) {the console. The log (" subscribe message API calls: failure, "res)}})},Copy the code

Cloud development landing

Checking login

<script>
	global.isLogin = function() {
		try {
			var openid = uni.getStorageSync('openid');
		} catch (e) {

		}
		if (openid === '') {
			return false
		} else {
			return {
				openid
			}
		}
	};
	export default {
		onLaunch: function() {
			console.log('App Launch')
			wx.cloud.init({
				traceUser: true
			});
		}
	}
</script>
Copy the code

Landing page

<template> <view> <! -- #ifdef MP-WEIXIN --> <button class='bottom' type='primary' open-type="getUserInfo" withCredentials="true" Lang ="zh_CN" @getUserInfo ="wxGetUserInfo"> Authorized login </button> <! -- #endif --> </view> </template> <script> const db = wx.cloud.database(); export default { data() { return {} }, methods: { wxGetUserInfo(msg) { console.log(msg) var that = this; if (! Msg.detail.iv) {uni.showtoast ({title: 'you have cancelled authorization, login failed ', icon: 'none'}); Return false} uni.showLoading({title: 'loading'}); uni.login({ provider: 'weixin', success: function(loginRes) { console.log(loginRes) that.getOpenid(msg); }, fail: function(r) { console.log(r) } }) }, getOpenid(msg) { var that = this; wx.cloud.callFunction({ name: 'getOpenid', complete: res => { console.log('openid: ', res); try { uni.setStorageSync('openid', res.result.openId); } catch (e) { } that.saveToDb(msg, res.result.openId) }, }); }, saveToDb(msg, openid) { console.log(openid) db.collection('user').where({ _openid: openid }).get().then(res => { console.log(res) if (res.errMsg === 'collection.get:ok') { if (res.data.length === 0) { db.collection('user').add({ data: { ... msg.detail.userInfo, _openid: res.result.openId } }).then(res => { console.log(res); }); } uni.hideLoading(); Uni. ShowToast ({title: 'license succeeded ', icon: 'success'}); setTimeout(() => { uni.navigateBack(); }, 1500); } else {} }) } }, onLoad() { } } </script>Copy the code

conclusion

The above is the content to speak today, this article only briefly introduces the small program development – cloud development technology summary, thank you for reading, if you think this article is helpful to you, also welcome to share it with more friends. Thanks for forwarding sharing, like, favorites!

Denver annual essay | 2020 technical way with me The campaign is under way…