常用界面api及案例

常用界面API:wx.showToast()、wx.showLoading()、wx.hideLoading()、wx.setNavigationBarTitle()

获取用户信息

授权过程:https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/authorize.html

## 通过API获取用户信息

wx.getUserProfile({ })  获取用户信息

页面产生点击事件(例如 `button` 上 `bindtap` 的回调中)后才可调用,每次请求都会弹出授权窗口,用户同意后返回 `userInfo`。该接口用于替换 `wx.getUserInfo`

“`html
<button bindtap=”getUser”>获取用户信息</button>

<view>{{userInfo.nickName}}</view>
<image src=”{{userInfo.avatarUrl}}”></image>

“`

“`js
getUser() {
    // 限频接口  2pv
    wx.getUserProfile({
        desc: ‘完善资料’,
        success: res => {
            console.log(res);
            this.setData({
                userInfo: res.userInfo
            })

            // wx.setStorageSync(‘userInfo’, res.userInfo)

            wx.setStorage({
                key: “userInfo”,
                data: res.userInfo,
                encrypt:true,
                //success:res=>{
                    //     wx.getStorage({
                    //         key: “userInfo”,
                    //         encrypt: true, // 若开启加密存储,setStorage 和 getStorage 需要同时声明 encrypt 的值为 true
                    //         success(res) {
                    //           console.log(res.data)
                    //         }
                    //       })
                    // }
            })
        }
    })
},
    onShow: function () {
        let userInfo = wx.getStorageSync(‘userInfo’)

        

        if (userInfo == “”) {
            wx.showToast({
                title: “点击按钮获取用户信息”,
                icon: “none”
            })
        } else {
            this.setData({
                userInfo
            })
        }
    },
“`

**tips2**

获取用户手机号

https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/getPhoneNumber.html

(1)获取微信用户绑定的手机号,需先调用wx.login接口;
(2)需要用户主动触发才能发起获取手机号接口,该功能不由 API 来调用,需用 button 组件的点击来触发
(3)目前该接口针对==非个人开发者==,且完成了认证的小程序开放(不包含海外主体)

2.21.2更新前

需要将 [button](https://developers.weixin.qq.com/miniprogram/dev/component/button.html) 组件 `open-type` 的值设置为 `getPhoneNumber`,当用户点击并同意之后,可以通过 `bindgetphonenumber` 事件回调获取到微信服务器返回的加密数据, 然后在第三方服务端结合 `session_key` 以及 `app_id` 进行解密获取手机号

2.21.2更新后:

需要将 [button](https://developers.weixin.qq.com/miniprogram/dev/component/button.html) 组件 `open-type` 的值设置为 `getPhoneNumber`,当用户点击并同意之后,可以通过 `bindgetphonenumber` 事件回调获取到动态令牌`code`,然后把`code`传到开发者后台,并在开发者后台调用微信后台提供的 [phonenumber.getPhoneNumber](https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/phonenumber/phonenumber.getPhoneNumber.html) 接口,消费`code`来换取用户手机号。每个`code`有效期为5分钟,且只能消费一次。

注:`getPhoneNumber` 返回的 `code` 与 `wx.login` 返回的 `code` 作用是不一样的,不能混用。

## 1.微信登录

“`
wx.login()  获取code 发给后台,后台可以用code向微信服务器换取sessionkey 然后解密
“`

## 2.开放数据检验与解密

小程序可以通过各种前端接口获取微信提供的开放数据,但是开发者服务端获取这些开放数据时,需要对发放数据进行解密;

## 3.获取手机号码

##### 准备环境–后端解密

nodeApi 文件夹 —执行指令 ,开启服务

“`
 node app.js
“`

注意:

“`
开发前,查看appid的权限,
    个人appid不能获取手机号,没有权限

     可以更换为测试账号!!!!!!!!!!
“`

##### 代码案例:

wxml

“`html
<button open-type=”getPhoneNumber” bindgetphonenumber=”getPhone”>
    获取手机号
</button>
“`

js

“`js
getPhone(e){
        console.log(e);
        let {iv,encryptedData} = e.detail
        // code
        wx.login({
         success:res=>{
             console.log(res);
             if(res.code){
                //  解密的请求
                wx.request({
                  url: ‘http://localhost:3000/v1/getPhoneNumber’,
                  data:{
                    iv,encryptedData,
                    code:res.code,
                    appid:’wx915c870ed8dc364e’,
                    secret:”6907714db25661c038318c26f1ee981b”
                  },
                  success:result=>{
                      console.log(result);
                  }
                })
             }
         }
        })

    },
“`

**tips3**

WeUI组件库

https://developers.weixin.qq.com/miniprogram/dev/platform-capabilities/extended/weui/

## 1.组件库概述

一套基于样式库weui-wxss开发的小程序扩展组件库,同微信原生视觉体验一致的UI组件库,由微信官方设计团队和小程序团队为微信小程序量身设计,令用户的使用感知更加统一。

## 2.安装构建使用

通过 [useExtendedLib 扩展库](https://developers.weixin.qq.com/miniprogram/dev/reference/configuration/app.html#useExtendedLib) 的方式引入,这种方式引入的组件将不会计入代码包大小。

app.json

“`JSON
 “usingComponents”: {
      “my-button”:”/components/my-button/my-button”,
      “my-sum”:”/components/my-sum/my-sum”,
     
      “mp-icon”: “weui-miniprogram/icon/icon”,
      “mp-navigation-bar”: “weui-miniprogram/navigation-bar/navigation-bar”
  },
  “useExtendedLib”: {
    “weui”:true
  }
“`

xx.json

“`json
{
  “usingComponents”: {},
  “navigationStyle”:”custom”,
  “navigationBarTextStyle”: “white”
}
“`

xx.wxml

“`html
<!–pages/weui/weui.wxml–>
<mp-navigation-bar back=”{{false}}” background=”#f00″ color=”#fff”>

    <view slot=”left” class=”left”>
        <text bindtap=”fun”>返回</text> | <text bindtap=”fun2″>首页</text>
    </view>

    <view slot=”center”>
        <mp-icon icon=”search” type=”field” color=”#fff”></mp-icon>订单查询
    </view>

</mp-navigation-bar>

<mp-icon icon=”like” type=”field” ></mp-icon>

“`

**tips**

云开发

## 1.概述

云开发为开发者提供完整的原生云端支持和微信服务支持,==弱化后端和运维概念,无需搭建服务器,使用平台提供的 API==进行核心业务开发,即可实现快速上线和迭代。提供了包括数据库、云函数、存储等基础能力

​     前端(小程序端)—》【接口】数据来源(服务端 php / java) –》 购买服务器,购买域名 安装mysql

​     前端(小程序端)—》 【api】 —》云开放( 存储空间,数据库、云函数 )

## 2.基础能力概述

“`
 存储空间,数据库、云函数
“`

## 3.新建云开发模板

“`
填写真实的appid
选择云开发
“`

## 4.开通云开发、创建环境

​         官方:  送俩套环境,每一套环境都有独立的数据库,存储空间,云函数

“`
点击开发者工具 云开发按钮开通环境即可
“`

## 5.初始化

“`js
// app.js
App({
    onLaunch: function () {
        if (!wx.cloud) {
            console.error(‘请使用 2.2.3 或以上的基础库以使用云能力’);
        } else {
            wx.cloud.init({
                // env 参数说明:
                //   env 参数决定接下来小程序发起的云开发调用(wx.cloud.xxx)会默认请求到哪个云环境的资源
                //   此处请填入环境 ID, 环境 ID 可打开云控制台查看
                //   如不填则使用默认环境(第一个创建的环境)

                env: ‘dev-wmunf’,  //修改=======填写自己的环境id
                traceUser: true,
            });
        }
    }
})
“`

**tips5**

## 6.云开发**tips5**

### miniprogram–小程序端代码:

index.wxml

“`html
<!–pages/index/index.wxml–>
<view class=”container”>
    <input type=”text” model:value=”{{phone}}” bindinput=”input” placeholder=”请输入账号”/>
    <input type=”text” model:value=”{{pass}}” bindinput=”input” placeholder=”请输入密码”/>

    <button bindtap=”add”>add</button>
    <button bindtap=”get”>get</button>
</view>

<view wx:for=”{{arr}}”>
    {{item.phone}}—<button size=”mini” bindtap=”getOne” data-id=”{{item._id}}”>详情</button>
</view>
 

“`

index.js

“`js
// pages/index/index.js
// 1)获取数据库的引用
let db = wx.cloud.database()
// console.log(db);

Page({

    /**
     * 页面的初始数据
     */
    data: {
        phone:””,
        pass:””,
        arr:[]
    },
    input(){},
    add(){
        // 获取输入值
        let phone = this.data.phone
        let pass = this.data.pass

        // 执行添加数据
        db.collection(‘a-c’).add({
            data:{
                // 字段名称:存储的数据
                phone:phone,
                pass:pass
            },
            success:res=>{
                console.log(res);
                if(res._id){
                    wx.showToast({
                      title: ‘添加成功’,
                    })
                }
            }
        })
    },
    get(){
        // 小程序端获取 数据最多只能返回20条
        // 云函数端获取 数据做多只能返回100条

        // 获取多条数据 {}
        db.collection(‘a-c’).where({}).get({
            success:res=>{
                console.log(res);
                this.setData({
                    arr:res.data
                })
            }
        })

    },
    getOne(e){
        // console.log(e);
        let id = e.target.dataset.id
        // doc _id
        db.collection(‘a-c’).doc(id).get({
            success:res=>{
                console.log(res);
                
            }
        })
    }
})


版权声明:本文为ILove_bugs原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/ILove_bugs/article/details/122243276