Summary of common functions for WeChat mini program development

WBOY
Release: 2022-08-30 13:56:23
forward
3666 people have browsed it

This article brings you relevant knowledge about WeChat Mini Program. It mainly introduces the common functions of WeChat Mini Program development. This article introduces it to you in great detail through example code, which is helpful for your learning. Or the work has certain reference value, I hope it will be helpful to everyone.

Summary of common functions for WeChat mini program development

[Related learning recommendations: 小program learning tutorial]

Get user information

Call The wx.getUserProfile method obtains basic user information. It can only be called after a click event occurs on the page (for example, in the callback of bindtap on button). An authorization window will pop up for each request. After the user agrees, userInfo# will be returned.

##The specific parameters are as follows:

AttributeTypeDefault valueRequiredDescriptionlangstringenNoLanguage for displaying user information descstringis declares the purpose of obtaining the user’s personal information, which shall not exceed 30 characterssuccessfunctionNoCallback function for successful interface callfailfunctionNoCallback function that fails to call the interfacecompletefunctionNoThe callback function at the end of the interface call (will be executed if the call is successful or failed)
Sample code

wx.getUserProfile({
    desc: '用于完善用户基本资料', // 声明获取用户个人信息后的用途,不超过30个字符
    success: (res) => {
        console.log(res.userInfo));
    }
})
Copy after login

Get the return value

{
  "nickName": "秋梓", // 微信昵称
  "gender": 0,
  "language": "zh_CN",
  "city": "",
  "province": "",
  "country": "",
  "avatarUrl": "https://thirdwx.qlogo.cn/mmopen/vi_32/qrSYVbDbBhunywgP5HTx4mhT8HVNzhmlibd8pfYo4guPJ5w/132" // 头像
}
Copy after login

Get the mobile phone number

Currently, this interface is for non-individual developers. Mini programs that have completed certification are open (excluding overseas entities). It needs to be used with caution. If users report it frequently or are found to be used in unnecessary scenarios, WeChat has the right to permanently revoke the interface permissions of the mini program.

Usage method

You need to set the value of the button component

open-type to getPhoneNumber. After the user clicks and agrees, you can use bindgetphonenumber The event callback obtains the dynamic token code, then passes code to the developer backend, and calls the phonenumber.getPhoneNumber interface provided by the WeChat backend in the developer backend. Spend code in exchange for the user’s mobile phone number. Each code is valid for 5 minutes and can only be consumed once.

Note: The

code returned by getPhoneNumber has different functions from the code returned by wx.login and cannot be Mix it up.

Code example

<button open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber"></button>
Copy after login
rrree

Return parameter description

##ParametercodeThen exchange the user's mobile phone number through code. Each code can only be used once, and the validity period of the code is 5min
TypeDescriptionMinimum version
StringDynamic token. Users’ mobile phone numbers can be exchanged for dynamic tokens. Usage details phonenumber.getPhoneNumber interface

Call the following interface

Page({
  getPhoneNumber (e) {
    console.log(e.detail.code)
  }
})
Copy after login

Request parameters

Attributes##access_token / cloudbase_access_tokenstring is the interface call credential codestring is the mobile phone number to obtain the voucher The returned JSON data packet
TypeDefault valueRequiredDescription

attribute TypeDescriptionerrcodenumberError codeerrmsgstringError messagephone_infoObjectUser phone number information

返回结果示例

{
    "errcode":0,
    "errmsg":"ok",
    "phone_info": {
        "phoneNumber":"xxxxxx",
        "purePhoneNumber": "xxxxxx",
        "countryCode": 86,
        "watermark": {
            "timestamp": 1637744274,
            "appid": "xxxx"
        }
    }
}
Copy after login

实现微信支付

唤起微信支付的核心方法调用 wx.requestPayment 方法,该方法具体参数如下

属性类型默认值必填说明
timeStampstring 时间戳,从 1970 年 1 月 1 日 00:00:00 至今的秒数,即当前的时间
nonceStrstring 随机字符串,长度为32个字符以下
packagestring 统一下单接口返回的 prepay_id 参数值,提交格式如:prepay_id=***
signTypestringMD5 仅在 v2 版本接口适用签名算法,应与后台下单时的值一致
HMAC-SHA256 仅在 v2 版本接口适用
RSA 仅在 v3 版本接口适用
paySignstring 签名,具体见微信支付文档
successfunction 接口调用成功的回调函数
failfunction 接口调用失败的回调函数
completefunction 接口调用结束的回调函数(调用成功、失败都会执行)
/**
 * 微信支付方法
 * @param {string} oderId 订单id
 * @param {string} total 订单金额
 * @param {stromg} openId 登陆人openid
 */
function weixinPayFun(data) {
  wx.showLoading({
    mask: true
  })
  const http = new Http()
  return new Promise((resolve, reject) => {
    // 请求支付接口
    http.post(`${env.fayongApi}/app/shopping/order/pay`, data).then(res => {
      // 获取支付签名信息
      let payInfo = res.data
      // 调起微信支付
      wx.requestPayment({
        "timeStamp": payInfo.timeStamp + &#39;&#39;,
        "nonceStr": payInfo.nonceStr,
        "package": payInfo.package,
        "signType": "RSA",
        "paySign": payInfo.paySign,
        "success": function (res) {
          console.log(res, &#39;success&#39;);
          // 支付成功
          resolve(res)
        },
        "fail": function (err) {
          // 支付失败
          reject(err)
        },
        "complete": function (res) {
          wx.hideLoading()
        }
      })
    })
  })
}
Copy after login

添加分享功能

在需要分享的分享的页面中添加 onShareAppMessage 事件函数,此事件处理函数需要 return 一个 Object,用于自定义转发内容,只有定义了此事件处理函数,右上角菜单才会显示“转发”按钮

onShareAppMessage 方法具体参数如下

字段说明默认值最低版本
title转发标题当前小程序名称
path转发路径当前页面 path ,必须是以 / 开头的完整路径
imageUrl自定义图片路径,可以是本地文件路径、代码包文件路径或者网络图片路径。支持PNG及JPG。显示图片长宽比是 5:4。使用默认截图1.5.0
promise如果该参数存在,则以 resolve 结果为准,如果三秒内不 resolve,分享会使用上面传入的默认参数 2.12.0

静态分享

示例代码

Page({
    // 分享
    onShareAppMessage() {
        return {
            title: "乐福健康", // 分享标题
            path: "pages/newhome/index", // 分享地址路径
        }
    }
})
Copy after login

添加完成后点击右上角胶囊按钮会分享图标会亮起

带参分享

上面的分享是不带参数的,我们可以直接在路径中动态添加参数,分享后用户点击时会触发 onLoad 函数获取路径中的参数值

// 分享
onShareAppMessage() {
    const that = this;
    return {
        title: that.data.goodInfo.goodName, // 动态获取商品名称
        path: "pages/component/orderparticulars/orderparticulars?id=" + that.data.productId, // 动态传递当前商品id
        imageUrl: that.data.background[0] // 获取商品封面图
    }
}
Copy after login

动态获取分享图片和标题后我们每次分享时会出现不同内容

全局分享

除此之外我们也可以添加全局分享功能

首先要在每个页面中添加 onShareAppMessage 函数,函数体内容可以为空,如果函数体内容为空,则会使用我们在 app.js 中定义的默认分享方法,如果该函数返回了一个 object 则使用我们自定义的分享功能

在需要被分享的页面添加如下代码

Page({
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {
		// 函数体内容为空即可
    }
})
Copy after login

接着在 app.js 中添加重写分享方法

//重写分享方法
overShare: function () {
    //间接实现全局设置分享内容
    wx.onAppRoute(function () {
        //获取加载的页面
        let pages = getCurrentPages(),
            //获取当前页面的对象
            view = pages[pages.length - 1],
            data;
        if (view) {
            data = view.data;
            // 判断是否需要重写分享方法
            if (!data.isOverShare) {
                data.isOverShare = true;
                view.onShareAppMessage = function () {
                    //重写分享配置
                    return {
                        title: &#39;分享标题&#39;,
                        path: "/pages/index/index"    //分享页面地址
                    };
                }
            }
        }
    })
},
Copy after login

然后在 onLaunch 函数中调用该方法

onLaunch() {
    this.overShare()
}
Copy after login

分享按钮

在开发中我们也会碰到点击分享按钮实现分享功能,实现代码如下

首先在 html 中添加 button 按钮。其中 open-typ 要等于 share,表示点击这个按钮注定触发分享函数

<!-- 分享按钮 -->
<van-button type="primary" icon="share" round class="search" open-type="share" size="small">
    分享
</van-button>
Copy after login

之后要确保我们在 js 中添加了 onShareAppMessage 函数

效果如下:

获取用户收货地址

获取用户收货地址。调起用户编辑收货地址原生界面,并在编辑完成后返回用户选择的地址。

wx.chooseAddress({
    success(res) {
        console.log(res.userName)
        console.log(res.postalCode)
        console.log(res.provinceName)
        console.log(res.cityName)
        console.log(res.countyName)
        console.log(res.detailInfo)
        console.log(res.nationalCode)
        console.log(res.telNumber)
    }
})
Copy after login

参数说明

属性类型说明
userNamestring收货人姓名
postalCodestring邮编
provinceNamestring国标收货地址第一级地址
cityNamestring国标收货地址第二级地址
countyNamestring国标收货地址第三级地址
streetNamestring国标收货地址第四级地址
detailInfostring详细收货地址信息(包括街道地址)
detailInfoNewstring新选择器详细收货地址信息
nationalCodestring收货地址国家码
telNumberstring收货人手机号码
errMsgstring错误信息

Preview image

Call method: wx.previewImage(Object object)

Preview the image in full screen on the new page. During the preview process, users can save pictures, send them to friends, etc.

AttributeTypeDefault valueRequiredDescriptionMinimum version
urlsArray. is a list of image links that needs to be previewed . Cloud file ID is supported starting from 2.2.3.
showmenubooleantrueNoWhether to display long press menu. Codes that support identification: Mini Program codes. Only Mini Programs support identification codes: WeChat personal codes, WeChat group codes, corporate WeChat personal codes, corporate WeChat group codes, and corporate WeChat interoperable group codes; 2.13.0
currentstringThe first picture of urlsNoThe link of the currently displayed picture
referrerPolicystringno-referrerNoorigin : Send complete referrer; no-referrer: Do not send. The format is fixed to https://servicewechat.com/{appid}/{version}/page-frame.html, where {appid} is the appid of the mini program and {version} is the version number of the mini program. , the version number is 0, which means the development version, trial version and review version, the version number is devtools, which means the developer tools, and the rest are official versions; 2.13.0
successfunction NoCallback function for successful interface call
failfunction NoCallback function for failed interface call
completefunction NoThe callback function at the end of the interface call (will be executed if the call is successful or failed)

示例代码

wx.previewImage({
  current: &#39;&#39;, // 当前显示图片的http链接
  urls: [] // 需要预览的图片http链接列表
})
Copy after login

页面跳转

跳转普通页面

wx.navigateTo({
    url: &#39;&#39;,
})
Copy after login

保留当前页面,跳转到应用内的某个页面。但是不能跳到 tabbar 页面。使用 wx.navigateBack 可以返回到原页面。小程序中页面栈最多十层

跳转tabBar 页面

跳转到 tabBar 页面,并关闭其他所有非 tabBar 页面

wx.switchTab({
  url: &#39;/index&#39;
})
Copy after login

自定义组件

在小程序中的组件和普通页面的 js 结构有很大差异,结构如下

// pages/TestComponent/test.js
Component({
    /**
     * 组件的属性列表
     */
    properties: {
        userName:""
    },

     * 组件的初始数据
    data: {
     * 组件的方法列表
    methods: {
        // 获取父组件传递过来的参数
        getPropName(){
            console.log(this.data.userName);
        }
    }
})
Copy after login

其中我们在 properties 对象中定义组件组件的属性列表

然后再组件中添加触发 getPropName 的方法

<button bind:tap="getPropName">获取名称</button>
Copy after login

在我们需要引入这个组件的页面去声明这个组件的名称和地址,找到后缀为 json 的文件,添加如下代码

{
  "usingComponents": {
    "test-component":"../TestComponent/test"
  }
}
Copy after login

之后我们在页面中像使用普通标签一样使用这个组件,并且给组件传递数据

<test-component userName="张三"></test-component>
Copy after login

传递数据后我们即可实现点击组件中的按钮获取父组件传递过来的值

定义全局组件

我们定义完组件后想要在全局使用,我们可以将这个组件定义为全局组件

首先找到项目中的 app.json 文件,找到 usingComponents 添加组件地址

{
    ......省略其他代码
    "usingComponents": {
        "test-component":"./pages/TestComponent/test"
    }
}
Copy after login

声明完成后我们即可在全局像使用标签的方式使用该组件

设置默认顶部导航栏样式

app.json 中添加如下代码

{
    "window": {
        "backgroundTextStyle": "light",
        "navigationBarBackgroundColor": "#22a381",
        "navigationBarTitleText": "乐福健康",
        "navigationBarTextStyle": "white"
    }
}
Copy after login

全部参数列表

属性类型默认值描述最低版本
navigationBarBackgroundColorHexColor#000000导航栏背景颜色,如 #000000
navigationBarTextStylestringwhite导航栏标题颜色,仅支持 black / white
navigationBarTitleTextstring 导航栏标题文字内容
navigationStylestringdefault导航栏样式,仅支持以下值: default 默认样式 custom 自定义导航栏,只保留右上角胶囊按钮。iOS/Android 微信客户端 7.0.0,Windows 微信客户端不支持
backgroundColorHexColor#ffffff窗口的背景色
backgroundTextStylestringdark下拉 loading 的样式,仅支持 dark / light
backgroundColorTopstring#ffffff顶部窗口的背景色,仅 iOS 支持微信客户端 6.5.16
backgroundColorBottomstring#ffffff底部窗口的背景色,仅 iOS 支持微信客户端 6.5.16
enablePullDownRefreshbooleanfalse是否开启当前页面下拉刷新。 详见 Page.onPullDownRefresh
onReachBottomDistancenumber50页面上拉触底事件触发时距页面底部距离,单位为px。 详见 Page.onReachBottom
pageOrientationstringportrait屏幕旋转设置,支持 auto / portrait / landscape 详见 响应显示区域变化2.4.0 (auto) / 2.5.0(landscape)
disableScrollbooleanfalse设置为 true 则页面整体不能上下滚动。 只在页面配置中有效,无法在 app.json 中设置
usingComponentsObject页面自定义组件配置1.6.3
initialRenderingCachestring 页面初始渲染缓存配置,支持 static / dynamic2.11.1
stylestringdefault启用新版的组件样式2.10.2
singlePageObject单页模式相关配置2.12.0
restartStrategystringhomePage重新启动策略配置2.8.0

效果

取消顶部默认的导航栏

找到页面 json 文件添加 "navigationStyle":"custom",即可去掉默认导航栏

{
  "usingComponents": {
      
  },
  "navigationStyle":"custom"
}
Copy after login

添加自定义样式后可以达到如下效果

【相关学习推荐:小程序学习教程

The above is the detailed content of Summary of common functions for WeChat mini program development. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:jb51.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template