


Summary of common functions for WeChat mini program development
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.
[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.
Type | Default value | Required | Description | |
---|---|---|---|---|
string | en | No | Language for displaying user information | |
string | is | declares the purpose of obtaining the user’s personal information, which shall not exceed 30 characters | ||
function | No | Callback function for successful interface call | ||
function | No | Callback function that fails to call the interface | ||
function | No | The callback function at the end of the interface call (will be executed if the call is successful or failed) |
wx.getUserProfile({ desc: '用于完善用户基本资料', // 声明获取用户个人信息后的用途,不超过30个字符 success: (res) => { console.log(res.userInfo)); } })
{ "nickName": "秋梓", // 微信昵称 "gender": 0, "language": "zh_CN", "city": "", "province": "", "country": "", "avatarUrl": "https://thirdwx.qlogo.cn/mmopen/vi_32/qrSYVbDbBhunywgP5HTx4mhT8HVNzhmlibd8pfYo4guPJ5w/132" // 头像 }
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.
code returned by
getPhoneNumber has different functions from the
code returned by
wx.login and cannot be Mix it up.
<button open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber"></button>
Type | Description | Minimum version | |
---|---|---|---|
String | Dynamic 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) } })
Request parameters
Type | Default value | Required | Description | ##access_token / cloudbase_access_token |
---|---|---|---|---|
is the | interface call credential | code | ||
is the | mobile phone number to obtain the voucher |
Description | errcode | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Error code | errmsg | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Error message | phone_info | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
User phone number information |
属性 | 类型 | 默认值 | 必填 | 说明 |
---|---|---|---|---|
timeStamp | string | 是 | 时间戳,从 1970 年 1 月 1 日 00:00:00 至今的秒数,即当前的时间 | |
nonceStr | string | 是 | 随机字符串,长度为32个字符以下 | |
package | string | 是 | 统一下单接口返回的 prepay_id 参数值,提交格式如:prepay_id=*** | |
signType | string | MD5 仅在 v2 版本接口适用 | 否 | 签名算法,应与后台下单时的值一致 |
HMAC-SHA256 仅在 v2 版本接口适用 | ||||
RSA 仅在 v3 版本接口适用 | ||||
paySign | string | 是 | 签名,具体见微信支付文档 | |
success | function | 否 | 接口调用成功的回调函数 | |
fail | function | 否 | 接口调用失败的回调函数 | |
complete | function | 否 | 接口调用结束的回调函数(调用成功、失败都会执行) |
/** * 微信支付方法 * @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 + '', "nonceStr": payInfo.nonceStr, "package": payInfo.package, "signType": "RSA", "paySign": payInfo.paySign, "success": function (res) { console.log(res, 'success'); // 支付成功 resolve(res) }, "fail": function (err) { // 支付失败 reject(err) }, "complete": function (res) { wx.hideLoading() } }) }) }) }
添加分享功能
在需要分享的分享的页面中添加 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", // 分享地址路径 } } })
添加完成后点击右上角胶囊按钮会分享图标会亮起
带参分享
上面的分享是不带参数的,我们可以直接在路径中动态添加参数,分享后用户点击时会触发 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] // 获取商品封面图 } }
动态获取分享图片和标题后我们每次分享时会出现不同内容
全局分享
除此之外我们也可以添加全局分享功能
首先要在每个页面中添加 onShareAppMessage
函数,函数体内容可以为空,如果函数体内容为空,则会使用我们在 app.js
中定义的默认分享方法,如果该函数返回了一个 object 则使用我们自定义的分享功能
在需要被分享的页面添加如下代码
Page({ /** * 用户点击右上角分享 */ onShareAppMessage: function () { // 函数体内容为空即可 } })
接着在 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: '分享标题', path: "/pages/index/index" //分享页面地址 }; } } } }) },
然后在 onLaunch
函数中调用该方法
onLaunch() { this.overShare() }
分享按钮
在开发中我们也会碰到点击分享按钮实现分享功能,实现代码如下
首先在 html
中添加 button
按钮。其中 open-typ
要等于 share
,表示点击这个按钮注定触发分享函数
<!-- 分享按钮 --> <van-button type="primary" icon="share" round class="search" open-type="share" size="small"> 分享 </van-button>
之后要确保我们在 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) } })
参数说明
属性 | 类型 | 说明 |
---|---|---|
userName | string | 收货人姓名 |
postalCode | string | 邮编 |
provinceName | string | 国标收货地址第一级地址 |
cityName | string | 国标收货地址第二级地址 |
countyName | string | 国标收货地址第三级地址 |
streetName | string | 国标收货地址第四级地址 |
detailInfo | string | 详细收货地址信息(包括街道地址) |
detailInfoNew | string | 新选择器详细收货地址信息 |
nationalCode | string | 收货地址国家码 |
telNumber | string | 收货人手机号码 |
errMsg | string | 错误信息 |
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.
Attribute | Type | Default value | Required | Description | Minimum version |
---|---|---|---|---|---|
urls | Array. | is a list of image links that | needs to be previewed . Cloud file ID is supported starting from 2.2.3. | ||
showmenu | boolean | true | No | Whether 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 |
current | string | The first picture of urls | No | The link of the currently displayed picture | |
referrerPolicy | string | no-referrer | No | origin : 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 |
success | function | No | Callback function for successful interface call | ||
fail | function | No | Callback function for failed interface call | ||
complete | function | No | The callback function at the end of the interface call (will be executed if the call is successful or failed) |
示例代码
wx.previewImage({ current: '', // 当前显示图片的http链接 urls: [] // 需要预览的图片http链接列表 })
页面跳转
跳转普通页面
wx.navigateTo({ url: '', })
保留当前页面,跳转到应用内的某个页面。但是不能跳到 tabbar 页面。使用 wx.navigateBack 可以返回到原页面。小程序中页面栈最多十层
跳转tabBar 页面
跳转到 tabBar 页面,并关闭其他所有非 tabBar 页面
wx.switchTab({ url: '/index' })
自定义组件
在小程序中的组件和普通页面的 js
结构有很大差异,结构如下
// pages/TestComponent/test.js Component({ /** * 组件的属性列表 */ properties: { userName:"" }, * 组件的初始数据 data: { * 组件的方法列表 methods: { // 获取父组件传递过来的参数 getPropName(){ console.log(this.data.userName); } } })
其中我们在 properties
对象中定义组件组件的属性列表
然后再组件中添加触发 getPropName
的方法
<button bind:tap="getPropName">获取名称</button>
在我们需要引入这个组件的页面去声明这个组件的名称和地址,找到后缀为 json
的文件,添加如下代码
{ "usingComponents": { "test-component":"../TestComponent/test" } }
之后我们在页面中像使用普通标签一样使用这个组件,并且给组件传递数据
<test-component userName="张三"></test-component>
传递数据后我们即可实现点击组件中的按钮获取父组件传递过来的值
定义全局组件
我们定义完组件后想要在全局使用,我们可以将这个组件定义为全局组件
首先找到项目中的 app.json
文件,找到 usingComponents
添加组件地址
{ ......省略其他代码 "usingComponents": { "test-component":"./pages/TestComponent/test" } }
声明完成后我们即可在全局像使用标签的方式使用该组件
设置默认顶部导航栏样式
在 app.json
中添加如下代码
{ "window": { "backgroundTextStyle": "light", "navigationBarBackgroundColor": "#22a381", "navigationBarTitleText": "乐福健康", "navigationBarTextStyle": "white" } }
全部参数列表
属性 | 类型 | 默认值 | 描述 | 最低版本 |
---|---|---|---|---|
navigationBarBackgroundColor | HexColor | #000000 | 导航栏背景颜色,如 #000000 | |
navigationBarTextStyle | string | white | 导航栏标题颜色,仅支持 black / white | |
navigationBarTitleText | string | 导航栏标题文字内容 | ||
navigationStyle | string | default | 导航栏样式,仅支持以下值: default 默认样式 custom 自定义导航栏,只保留右上角胶囊按钮。 | iOS/Android 微信客户端 7.0.0,Windows 微信客户端不支持 |
backgroundColor | HexColor | #ffffff | 窗口的背景色 | |
backgroundTextStyle | string | dark | 下拉 loading 的样式,仅支持 dark / light | |
backgroundColorTop | string | #ffffff | 顶部窗口的背景色,仅 iOS 支持 | 微信客户端 6.5.16 |
backgroundColorBottom | string | #ffffff | 底部窗口的背景色,仅 iOS 支持 | 微信客户端 6.5.16 |
enablePullDownRefresh | boolean | false | 是否开启当前页面下拉刷新。 详见 Page.onPullDownRefresh | |
onReachBottomDistance | number | 50 | 页面上拉触底事件触发时距页面底部距离,单位为px。 详见 Page.onReachBottom | |
pageOrientation | string | portrait | 屏幕旋转设置,支持 auto / portrait / landscape 详见 响应显示区域变化 | 2.4.0 (auto) / 2.5.0(landscape) |
disableScroll | boolean | false | 设置为 true 则页面整体不能上下滚动。 只在页面配置中有效,无法在 app.json 中设置 | |
usingComponents | Object | 否 | 页面自定义组件配置 | 1.6.3 |
initialRenderingCache | string | 页面初始渲染缓存配置,支持 static / dynamic | 2.11.1 | |
style | string | default | 启用新版的组件样式 | 2.10.2 |
singlePage | Object | 否 | 单页模式相关配置 | 2.12.0 |
restartStrategy | string | homePage | 重新启动策略配置 | 2.8.0 |
效果
取消顶部默认的导航栏
找到页面 json
文件添加 "navigationStyle":"custom"
,即可去掉默认导航栏
{ "usingComponents": { }, "navigationStyle":"custom" }
添加自定义样式后可以达到如下效果
【相关学习推荐:小程序学习教程】
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Xianyu's official WeChat mini program has quietly been launched. In the mini program, you can post private messages to communicate with buyers/sellers, view personal information and orders, search for items, etc. If you are curious about what the Xianyu WeChat mini program is called, take a look now. What is the name of the Xianyu WeChat applet? Answer: Xianyu, idle transactions, second-hand sales, valuations and recycling. 1. In the mini program, you can post idle messages, communicate with buyers/sellers via private messages, view personal information and orders, search for specified items, etc.; 2. On the mini program page, there are homepage, nearby, post idle, messages, and mine. 5 functions; 3. If you want to use it, you must activate WeChat payment before you can purchase it;

WeChat applet implements picture upload function With the development of mobile Internet, WeChat applet has become an indispensable part of people's lives. WeChat mini programs not only provide a wealth of application scenarios, but also support developer-defined functions, including image upload functions. This article will introduce how to implement the image upload function in the WeChat applet and provide specific code examples. 1. Preparatory work Before starting to write code, we need to download and install the WeChat developer tools and register as a WeChat developer. At the same time, you also need to understand WeChat

To implement the drop-down menu effect in WeChat Mini Programs, specific code examples are required. With the popularity of mobile Internet, WeChat Mini Programs have become an important part of Internet development, and more and more people have begun to pay attention to and use WeChat Mini Programs. The development of WeChat mini programs is simpler and faster than traditional APP development, but it also requires mastering certain development skills. In the development of WeChat mini programs, drop-down menus are a common UI component, achieving a better user experience. This article will introduce in detail how to implement the drop-down menu effect in the WeChat applet and provide practical

Implementing picture filter effects in WeChat mini programs With the popularity of social media applications, people are increasingly fond of applying filter effects to photos to enhance the artistic effect and attractiveness of the photos. Picture filter effects can also be implemented in WeChat mini programs, providing users with more interesting and creative photo editing functions. This article will introduce how to implement image filter effects in WeChat mini programs and provide specific code examples. First, we need to use the canvas component in the WeChat applet to load and edit images. The canvas component can be used on the page

Use the WeChat applet to achieve the carousel switching effect. The WeChat applet is a lightweight application that is simple and efficient to develop and use. In WeChat mini programs, it is a common requirement to achieve carousel switching effects. This article will introduce how to use the WeChat applet to achieve the carousel switching effect, and give specific code examples. First, add a carousel component to the page file of the WeChat applet. For example, you can use the <swiper> tag to achieve the switching effect of the carousel. In this component, you can pass b

The official WeChat mini program of Xianyu has been quietly launched. It provides users with a convenient platform that allows you to easily publish and trade idle items. In the mini program, you can communicate with buyers or sellers via private messages, view personal information and orders, and search for the items you want. So what exactly is Xianyu called in the WeChat mini program? This tutorial guide will introduce it to you in detail. Users who want to know, please follow this article and continue reading! What is the name of the Xianyu WeChat applet? Answer: Xianyu, idle transactions, second-hand sales, valuations and recycling. 1. In the mini program, you can post idle messages, communicate with buyers/sellers via private messages, view personal information and orders, search for specified items, etc.; 2. On the mini program page, there are homepage, nearby, post idle, messages, and mine. 5 functions; 3.

Implementing the sliding delete function in WeChat mini programs requires specific code examples. With the popularity of WeChat mini programs, developers often encounter problems in implementing some common functions during the development process. Among them, the sliding delete function is a common and commonly used functional requirement. This article will introduce in detail how to implement the sliding delete function in the WeChat applet and give specific code examples. 1. Requirements analysis In the WeChat mini program, the implementation of the sliding deletion function involves the following points: List display: To display a list that can be slid and deleted, each list item needs to include

To implement the picture rotation effect in WeChat Mini Program, specific code examples are required. WeChat Mini Program is a lightweight application that provides users with rich functions and a good user experience. In mini programs, developers can use various components and APIs to achieve various effects. Among them, the picture rotation effect is a common animation effect that can add interest and visual effects to the mini program. To achieve image rotation effects in WeChat mini programs, you need to use the animation API provided by the mini program. The following is a specific code example that shows how to
