微信小程序接口封装,带参跳转,使用手机号一键登录

一. 微信小程序接口封装

1.简单封装

1.在utils文件夹新建request.js,内容如下:

const app = getApp()

const host = '自己项目的线上接口地址' 

/*
* POST请求
* URL: 接口地址
* postData: 参数
* doSuccess: 成功的回调函数
* doFail: 失败的回调函数
* 请求头,参数类型,回调事件逻辑等根据自己的项目而定啦
* */
function request(url, postData, doSuccess, doFail) {
    wx.showLoading({
        title: '加载中'
    })
    wx.request({
        url: host + url,
        header: {
            "content-type": "application/x-www-form-urlencoded"
        },
        data: { postData },
        method: 'POST',
        success: function (res) {
            wx.hideLoading()
            doSuccess(res.data)
        },
        fail: function (error) {
            wx.hideLoading()
            wx.showModal({
                title: '提示',
                content: '请求失败'
            })
            doFail()
        }
    })
}

export { request }

2.在页面中使用
wxml:

 <view bindtap="searchOrder" >查询</view>

js:

import { request } from '../../utils/request'

Page({
  searchOrder(e) {
    const searchParams = { 
    // 参数根据后端接口而定哦
    "companyName": this.data.companyName,
     "searchName": this.data.orderNum, 
     }
    request('getXWGJDeliveryList.do',searchParams , this.success, this.fail)
  },
  success: function (res) {
    const _this = this;
    _this.setData({
      listData: res.data,
    })
  },
  fail: function () {
  },
})

2.项目中推荐的封装方法

1.在utils文件夹新建request.js,内容如下:

const app = getApp()

const host = '自己项目的线上接口地址'

const fetch = (params = {}) => {
    params.header = {
        'content-type': 'application/x-www-form-urlencoded',
        // 'token': app.globalData.token || ''
    }
    if (params.url.startsWith('/')) {
        params.url = host + params.url
    }
    return wx.request({...params}).then(({res: {code, message, data}}) =>{
        if (res.code === 200) {
            return Promise.resolve(data)
        }
        return Promise.reject(message)
    })
}

export { fetch }

新建一个api文件夹,与utils文件夹同级,根据自己模块新建对应的js文件,内容如下:

import { fetch } from '../utils/request'

export function postSearch(data) {
    return fetch({
        method: 'POST',
        url: '',
        data
    })
}

页面使用:
js:

import { postSearch } from '../../api/search'

Page({
 postSearch()
  .then(({ dataList }) => this.upData({ sysParamList: dataList }))
  .then(() => {
      this.upData({
          keyList,
          formData: { keys: keyList }
      })
})

二. 微信小程序页面之间的交互

1.页面跳转

  <view class="order_content" bindtap="jumpOder">
jumpOder(e){
    wx.navigateTo({
      url: '../order/order' 
    })
  },

2.页面带参数(字符串,对象,数组)跳转

1.字符串类型:

  <view class="order_content" bindtap="jumpOder" data-id="{{id}}">
jumpOder(e){
    wx.navigateTo({
      url: '../order/order?id='+ e.currentTarget.dataset.id
    })
  },

另一个页面接收数据:

 onLoad: function (options) {
    const _this = this
    _this.setData({
      id: options.id
    })
  },

2.对象,数组类型:

  <view class="order_content" bindtap="jumpOder" data-item="{{item}}">

需要先把对象或者数组转成json字符串

jumpOder(e){
 const item = JSON.stringify(e.currentTarget.dataset.item)
    wx.navigateTo({
      url: '../order/order?item ='+ item 
    })
  },

另一个页面接收数据:

 onLoad: function (options) {
    const _this = this
    _this.setData({
      item: JSON.parse(options.item)
    })
  },

三. 微信小程序使用官方api教程(以使用手机号一键登录为例)

这里重要的事情说三遍:一定要认真看文档!一定要认真看文档!!一定要认真看文档!!!
文档:https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/getPhoneNumber.html

1.准备工作

先要进行微信认证,不然没用权限
小程序首页 => 设置 => 基本设置 => 微信认证 详情

2. 在页面使用

在这里插入图片描述
前端只能获取到加密的数据,需要后端配合解密:

逻辑流程图(侵删):
在这里插入图片描述
实际使用:
wxml:

<button open-type="getPhoneNumber"  bindgetphonenumber="getPhoneNumber">获取用户手机号</button>

js:

 getPhoneNumber (e) {
    console.log('errMsg',e.detail.errMsg)
    console.log('iv',e.detail.iv)
    console.log('encryptedData',e.detail.encryptedData)
       /*登录*/
        wx.login({
          success: res => {
            console.log('code',res.code)
            const params = {
              code: res.code,
              encryptedData: e.detail.encryptedData,
              iv: e.detail.iv
            }
            request('接口地址', params, this.then, this.catch )
          },
          then (res) {
            // wx.setStorage({
            //   key: 'openid',
            //   data: res.data.openid
            // })
            // wx.setStorage({
            //   key: 'sessionKey',
            //   data: res.data.sessionKey
            // })
            // wx.setStorageSync( 'sessionKey', res.data.sessionKey)
            console.log('手机号:' ,res.data.phoneNumber)
          },
          catch () {}
        })
      }
  },
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值