Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Working with WeChat Mini Program APIs

Tech May 15 1

Network APIs

WeChat Mini Programs inetract with backend servers to fetch or submit data using built-in or third-party APIs. The primary method for network communication is wx.request().

Making HTTP Requests

The following example demonstrates fetching HTML content from Baidu:

// page.js
Page({
  data: { content: '' },
  fetchBaidu() {
    wx.request({
      url: 'https://www.baidu.com',
      header: { 'Content-Type': 'application/json' },
      success: (res) => {
        this.setData({ content: res.data });
      }
    });
  }
});
<!-- page.wxml -->
<button bindtap="fetchBaidu">Fetch HTML</button>
<textarea value="{{content}}" auto-height />

Another example uses a POST request to query address details by postal code via Juhe API:

Page({
  data: { code: '', locations: [], error: '' },
  onInput(e) {
    this.setData({ code: e.detail.value });
  },
  searchAddress() {
    const { code } = this.data;
    if (!code) return;

    wx.showToast({ title: 'Searching...', icon: 'loading', duration: 10000 });
    wx.request({
      url: 'https://v.juhe.cn/postcode/query',
      method: 'POST',
      data: {
        postcode: code,
        key: '0ff9bfccdf147476e067de994eb5496e'
      },
      header: { 'Content-Type': 'application/x-www-form-urlencoded' },
      success: (res) => {
        wx.hideToast();
        if (res.data.error_code === 0) {
          this.setData({ locations: res.data.result.list, error: '' });
        } else {
          this.setData({ error: res.data.reason || 'Unknown error' });
        }
      }
    });
  }
});
<view>Postal Code:</view>
<input bindinput="onInput" placeholder="6-digit code" />
<button bindtap="searchAddress">Search</button>
<block wx:for="{{locations}}">
  <block wx:for="{{item}}">
    <text>{{item}}</text>
  </block>
</block>

File Upload

Use wx.uploadFile() to send local files to a server:

Page({
  data: { preview: null },
  upload() {
    wx.chooseImage({
      success: (res) => {
        const path = res.tempFilePaths[0];
        wx.showToast({ title: 'Uploading...', icon: 'loading' });
        wx.uploadFile({
          url: 'http://localhost/upload',
          filePath: path,
          name: 'file',
          success: (resp) => {
            if (resp.statusCode !== 200) {
              wx.showModal({ title: 'Error', content: 'Upload failed', showCancel: false });
              return;
            }
            this.setData({ preview: path });
          },
          fail: () => {
            wx.showModal({ title: 'Error', content: 'Upload failed', showCancel: false });
          },
          complete: () => wx.hideToast()
        });
      }
    });
  }
});

File Download

Download files using wx.downloadFile():

Page({
  data: { image: null },
  download() {
    wx.downloadFile({
      url: 'http://localhost/photo.jpg',
      success: (res) => {
        this.setData({ image: res.tempFilePath });
      }
    });
  }
});

Multimedia APIs

These APIs handle images, audio recording, and playback.

Image Handling

  • Select or capture image: wx.chooseImage()
  • Preview images: wx.previewImage({ urls: [...], current: '...' })
  • Get image metadata: wx.getImageInfo({ src: '...' })
  • Save to album: Requires scope.writePhotosAlbum permission via wx.saveImageToPhotosAlbum()

Audio Recording

Record audio with wx.startRecord() and stop with wx.stopRecord(). Note: These are deprecated in newer versiosn; use wx.getRecorderManager() instead.

Voice Playback

Play, pause, or stop short audio clips:

  • wx.playVoice({ filePath: '...' })
  • wx.pauseVoice()
  • wx.stopVoice()

Background Music

Control background music playback:

  • wx.playBackgroundAudio({ dataUrl, title, coverImgUrl })
  • wx.getBackgroundAudioPlayerState()
  • wx.seekBackgroundAudio({ position })
  • wx.pauseBackgroundAudio(), wx.stopBackgroundAudio()
  • Event listeners: wx.onBackgroundAudioPlay(), wx.onBackgroundAudioPause(), wx.onBackgroundAudioStop()

File System APIs

Manage persistent local files beyond temporary storage.

  • Save file: wx.saveFile({ tempFilePath })
  • List saved files: wx.getSavedFileList()
  • Get file info: wx.getSavedFileInfo({ filePath })
  • Delete file: wx.removeSavedFile({ filePath })
  • Open document: wx.openDocument({ filePath }) (supports PDF, DOCX, etc.)

Local Storage APIs

Store key-value data persistently (up to 10MB). Both async and sync methods available.

  • Set: wx.setStorage({ key, data }) or wx.setStorageSync(key, data)
  • Get: wx.getStorage({ key }) or wx.getStorageSync(key)
  • Remove: wx.removeStorage({ key }) or wx.removeStorageSync(key)
  • Clear all: wx.clearStorage() or wx.clearStorageSync()

Location APIs

Access geolocation using WGS84 (global) or GCJ02 (China-encrypted) coordinates.

  • Get current location: wx.getLocation({ type: 'wgs84' })
  • Choose location from map: wx.chooseLocation()
  • Open location in map: wx.openLocation({ latitude, longitude, name, address })

Device APIs

Access device capabilities:

  • System info: wx.getSystemInfo() or wx.getSystemInfoSync()
  • Network type: wx.getNetworkType()
  • Monitor network changes: wx.onNetworkStatusChange(callback)
  • Make phone call: wx.makePhoneCall({ phoneNumber: '10086' })
  • Scan QR code: wx.scanCode({ onlyFromCamera: false })

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.