模式切换
高级特性
开放能力
微信登录 wx.login
获取用户的临时登录凭证,用于后端交换 openid 和 session_key。
javascript
// 小程序端
Page({
onLoad: function() {
this.wxLogin()
},
wxLogin: function() {
// 1. 调用 wx.login 获取 code
wx.login({
success: (res) => {
if (res.code) {
console.log('登录code:', res.code)
// 2. 将 code 发送到开发者服务器
this.sendCodeToServer(res.code)
} else {
console.error('登录失败:', res.errMsg)
}
},
fail: (err) => {
console.error('wx.login 调用失败:', err)
}
})
},
sendCodeToServer: function(code) {
// 3. 调用云函数或自己的服务器交换 openid
wx.cloud.callFunction({
name: 'login',
data: { code: code },
success: (res) => {
console.log('登录成功:', res.result)
// 4. 保存登录状态
wx.setStorageSync('token', res.result.token)
wx.setStorageSync('userInfo', res.result.userInfo)
},
fail: (err) => {
console.error('服务器登录失败:', err)
}
})
}
})
javascript
// 云函数端 cloud/functions/login/index.js
const cloud = require('wx-server-sdk')
cloud.init()
exports.main = async (event) => {
const { code } = event
const wxContext = cloud.getWXContext()
// 这里可以:
// 1. 用 code 换取 openid (如果需要的话)
// 2. 生成自定义登录态
// 3. 返回用户信息
return {
openid: wxContext.OPENID,
appid: wxContext.APPID,
unionid: wxContext.UNIONID,
token: generateToken(), // 生成自定义 token
userInfo: event.userInfo
}
}
function generateToken() {
// 生成 JWT token 的逻辑
return 'your-generated-token'
}
微信支付(结合云函数使用)
javascript
// 小程序端
Page({
createOrder: function() {
// 1. 创建订单(调用云函数)
wx.cloud.callFunction({
name: 'createPayment',
data: {
productId: '123',
quantity: 1
},
success: (res) => {
// 2. 获取支付参数
const paymentData = res.result.paymentData
// 3. 调用微信支付
wx.requestPayment({
timeStamp: paymentData.timeStamp,
nonceStr: paymentData.nonceStr,
package: paymentData.package,
signType: paymentData.signType,
paySign: paymentData.paySign,
success: (res) => {
console.log('支付成功', res)
wx.showToast({ title: '支付成功' })
// 更新订单状态
this.updateOrderStatus('paid')
},
fail: (err) => {
console.error('支付失败', err)
wx.showToast({ title: '支付取消', icon: 'none' })
}
})
},
fail: (err) => {
console.error('创建订单失败', err)
}
})
}
})
javascript
// 云函数端 cloud/functions/createPayment/index.js
const cloud = require('wx-server-sdk')
cloud.init()
// 引入支付 SDK
const tenpay = require('tenpay')
exports.main = async (event) => {
const { productId, quantity } = event
const wxContext = cloud.getWXContext()
// 1. 查询商品信息
const db = cloud.database()
const product = await db.collection('products').doc(productId).get()
// 2. 创建订单记录
const order = await db.collection('orders').add({
data: {
_openid: wxContext.OPENID,
productId: productId,
quantity: quantity,
totalFee: product.data.price * quantity,
status: 'pending',
created: db.serverDate()
}
})
// 3. 调用微信支付统一下单 API
const config = {
appid: wxContext.APPID,
mchid: 'your-mchid',
partnerKey: 'your-partner-key',
notify_url: 'https://your-domain.com/pay/notify'
}
const api = tenpay.init(config)
const result = await api.getPayParams({
out_trade_no: order._id, // 商户订单号
body: product.data.name, // 商品描述
total_fee: product.data.price * quantity, // 金额(分)
openid: wxContext.OPENID // 用户openid
})
return {
paymentData: result
}
}
分享 onShareAppMessage
javascript
Page({
data: {
product: {
id: '123',
name: '测试商品',
price: 100,
image: '/images/product.jpg'
}
},
// 点击右上角分享按钮时触发
onShareAppMessage: function() {
return {
title: this.data.product.name,
path: `/pages/product/detail?id=${this.data.product.id}`,
imageUrl: this.data.product.image,
success: (res) => {
console.log('分享成功', res)
// 可以记录分享行为
this.recordShare()
},
fail: (err) => {
console.error('分享失败', err)
}
}
},
// 自定义按钮分享
onShareToFriend: function() {
wx.shareAppMessage({
title: '我发现了一个好商品,快来看看!',
path: `/pages/product/detail?id=${this.data.product.id}`,
imageUrl: this.data.product.image
})
},
// 分享到朋友圈
onShareTimeline: function() {
return {
title: this.data.product.name,
imageUrl: this.data.product.image
}
}
})
html
<!-- 自定义分享按钮 -->
<button open-type="share" class="share-btn">
<image src="/icons/share.png"></image>
分享给好友
</button>
订阅消息
取代旧的模板消息,需要用户主动订阅。
javascript
Page({
// 请求用户订阅消息
subscribeMessage: function() {
// 1. 获取订阅消息模板 ID(需要在后台配置)
const templateId = 'your-template-id'
// 2. 请求用户授权
wx.requestSubscribeMessage({
tmplIds: [templateId],
success: (res) => {
if (res[templateId] === 'accept') {
console.log('用户同意订阅')
this.saveSubscription(templateId)
} else {
console.log('用户拒绝订阅', res[templateId])
wx.showToast({
title: '需要授权才能接收重要通知',
icon: 'none'
})
}
},
fail: (err) => {
console.error('订阅失败', err)
}
})
},
// 发送订阅消息(通过云函数)
sendSubscribeMessage: function() {
wx.cloud.callFunction({
name: 'sendSubscribeMessage',
data: {
templateId: 'your-template-id',
page: 'pages/index/index',
data: {
thing1: { value: '订单提醒' },
amount2: { value: '100.00' },
thing3: { value: '请及时处理' }
}
},
success: (res) => {
console.log('消息发送成功', res)
}
})
}
})
javascript
// 云函数端发送订阅消息
// cloud/functions/sendSubscribeMessage/index.js
const cloud = require('wx-server-sdk')
cloud.init()
exports.main = async (event) => {
try {
const { templateId, page, data } = event
const result = await cloud.openapi.subscribeMessage.send({
touser: cloud.getWXContext().OPENID, // 接收者openid
templateId: templateId,
page: page,
data: data,
miniprogramState: 'formal' // 跳转小程序类型
})
return { success: true, result: result }
} catch (err) {
return { success: false, error: err }
}
}
动画:使用 wx.createAnimation
小程序提供了专门的动画 API,性能优于直接使用 CSS3 动画。
基础动画
javascript
Page({
data: {
animationData: {}
},
onReady: function() {
this.animation = wx.createAnimation({
duration: 1000,
timingFunction: 'ease',
delay: 0,
transformOrigin: '50% 50%'
})
},
// 旋转动画
rotateAnimation: function() {
this.animation.rotate(45).step()
this.setData({
animationData: this.animation.export()
})
},
// 组合动画
complexAnimation: function() {
this.animation
.translate(100, 0) // 平移
.rotate(180) // 旋转
.scale(1.5) // 缩放
.step({ duration: 2000 })
.translate(0, 100)
.rotate(-180)
.scale(1)
.step({ duration: 1000 })
this.setData({
animationData: this.animation.export()
})
},
// 循环动画
loopAnimation: function() {
this.animation
.scale(0.5)
.step({ duration: 500 })
.scale(1)
.step({ duration: 500 })
this.setData({
animationData: this.animation.export()
})
// 循环执行
setTimeout(() => {
this.loopAnimation()
}, 1000)
}
})
html
<!-- 应用动画 -->
<view class="animated-box" animation="{{animationData}}"></view>
<button bindtap="rotateAnimation">旋转</button>
<button bindtap="complexAnimation">组合动画</button>
<button bindtap="loopAnimation">循环动画</button>
高级动画示例
javascript
// 更复杂的动画管理
class AnimationManager {
constructor(context) {
this.context = context
this.animations = new Map()
}
create(name, options = {}) {
const animation = wx.createAnimation(options)
this.animations.set(name, animation)
return animation
}
get(name) {
return this.animations.get(name)
}
exportAll() {
const result = {}
for (let [name, animation] of this.animations) {
result[name] = animation.export()
}
return result
}
}
// 在页面中使用
Page({
onReady: function() {
this.animationManager = new AnimationManager(this)
// 创建多个动画
this.boxAnimation = this.animationManager.create('box', {
duration: 1000,
timingFunction: 'ease-in-out'
})
this.textAnimation = this.animationManager.create('text', {
duration: 500,
timingFunction: 'linear'
})
},
playAnimations: function() {
// 同时执行多个动画
this.boxAnimation.translateX(100).rotate(360).step()
this.textAnimation.opacity(0.5).scale(1.2).step()
this.setData(this.animationManager.exportAll())
}
})