微信小程序开放能力

Posted yw00yw

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了微信小程序开放能力相关的知识,希望对你有一定的参考价值。

open-data

代码:

<open-data type="groupName"></open-data>
<view>
  昵称:<open-data type="userNickName"></open-data>
</view>
<view>
  头像:<open-data type="userAvatarUrl" style="display: block; width: 100px;"></open-data>
</view>
<view>
  性别:<open-data type="userGender" lang="zh_CN"></open-data>
</view>
<view>
  地址:
  <open-data type="userCountry" lang="zh_CN"></open-data>
  <open-data type="userProvince" lang="zh_CN"></open-data>
  <open-data type="userCity" lang="zh_CN"></open-data>
  <open-data type="userCity"></open-data>
</view>
<view>
  语言:
  <open-data type="userLanguage"></open-data>
</view>

效果


授权获取用户信息

代码

<view>
    <block wx:if="avatarUrl">
        <image style="display: block" src="avatarUrl" />
        <text>nickName</text>
    </block>
      
    <button wx:if="!avatarUrl" open-type="getUserInfo" bindgetuserinfo="bindgetuserinfo">授权登录</button>
</view>
// pages/my/my.js
Page(
  /**
   * 页面的初始数据
   */
  data: 
    avatarUrl: '',
    nickName: ''
  ,
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) 
    wx.getSetting(
      complete: (res) => 
        if (res.authSetting['scope.userInfo']) 
          // 已经授权,可以直接调用 getUserInfo 获取头像昵称
          wx.getUserInfo(
            success: (res) => 
              console.log("已授权", res.userInfo)
              let  avatarUrl, nickName  = res.userInfo;
              this.setData(
                avatarUrl,
                nickName
              );
            
          )
         else 
          console.log("未授权");
        
      ,
    )
  ,
  /**
   * 点击授权按钮
   */
  bindgetuserinfo(e) 
    console.log(e.detail.userInfo);
    let  avatarUrl, nickName  = e.detail.userInfo;
    this.setData(
      avatarUrl,
      nickName
    );
  
)

效果


页面分享

/**
 * 分享
 */
onShareAppMessage() 
  return 
    title: '我的页面分享',
    path: 'pages/my/my'
  
,
  • 页面右上角三个点分享,对应页面无分享代码,则不能分享
  • 分享图可以设置,没设置为当前页面截图

获取收货地址

/**
 * 获取地址
 */
handleAddress() 
  wx.chooseAddress(
    complete: (res) => 
      console.log("res", res);
      // "errMsg":"chooseAddress:ok","userName":"张三","nationalCode":"510000","telNumber":"020-81167888","postalCode":"510000","provinceName":"广东省","cityName":"广州市","countyName":"海珠区","detailInfo":"新港中路397号"
    ,
  )


打开地图选择位置

handleLocation() 
  wx.chooseLocation(
    complete: (res) => 
      console.log("res", res);
    ,
  )
,


直接获取位置信息

handleGetLocation() 
    wx.getLocation(
      type: 'wgs84',
      success (res) 
        console.log("res", res);
        const latitude = res.latitude;
        const longitude = res.longitude;
        const speed = res.speed;
        const accuracy = res.accuracy;
        wx.openLocation(
          latitude,
          longitude,
          scale: 18
        )
      
    )
  

获取地址完整版

utils/asyncWx.js

/**
 * promise 形式的 getSetting
 */
export const getSetting = () => 
  return new Promise((resolve, reject) => 
    wx.getSetting(
      success: res => 
        resolve(res);
      ,
      fail: (err) => 
        resolve(err);
      
    );
  );

/**
 * promise 形式的 chooseAddress
 */
 export const chooseAddress = () => 
  return new Promise((resolve, reject) => 
    wx.chooseAddress(
      success: res => 
        resolve(res);
      ,
      fail: (err) => 
        resolve(err);
      
    );
  );

/**
 * promise 形式的 openSetting
 */
 export const openSetting = () => 
  return new Promise((resolve, reject) => 
    wx.openSetting(
      success: res => 
        resolve(res);
      ,
      fail: (err) => 
        resolve(err);
      
    );
  );

address.js

import 
  getSetting,
  chooseAddress,
  openSetting
 from "../../utils/asyncWx";
Page(
  async handleChooseAddress() 
    try 
      // 1. 获取 权限状态
      const res1 = await getSetting();
      const scopeAddress = res1.authSetting["scope.address"];
      // 2. 判断 权限状态
      if (scopeAddress === false) 
        // 3. 先诱导用户打开授权界面
        await openSetting();
      
      // 4. 调用获取收获地址的 api
      // scopeAddress === true || scopeAddress === undefined
      const res2 = await chooseAddress();
      console.log(res2)
     catch (error) 
      console.log(error)
    
  
)

支付流程

payOrder.wxml

<view>
  <button bindtap="handlePayOrder">支付</button>
</view>

payOrder.js

// pages/payOrder/payOrder.js
Page(
  // 点击支付
  async handlePayOrder() 
    try 
      // 1. 判断缓存中有没有token
      const token = wx.getStorageSync('token');
      // 2. 判断权限
      if (!token) 
        wx.navigateTo(
          url: '/pages/auth/auth'
        );
        return;
      
      // 3. 创建订单
      // 3.1 准备 请求头参数
      const header = 
        Authorization: token
      ;
      // 3.2 准备 请求体参数
      const order_price = this.data.totalPrice;
      const consignee_addr = this.data.address.all;
      const goods = this.data.goods;
      // 4. 准备发送请求 创建订单
      const 
        order_number
       = await request(
        url: "/my/orders/create",
        method: "POST",
        header,
        data: 
          order_price,
          consignee_addr,
          goods
        
      );
      // 5 发起 预支付接口
      const 
        pay
       = await request(
        url: "/my/orders/req_unifiedorder",
        method: "POST",
        header,
        data: 
          order_number // 订单编号
        
      );
      //  6. 发起微信支付
      const 
        timeStamp,
        nonceStr,
        package,
        paySign
       = pay;
      await wx.requestPayment(
        timeStamp: 'timeStamp', //时间戳从1970年1月1日00:00:00至今的秒数,即当前的时间,
        nonceStr: 'nonceStr', //随机字符串,长度为32个字符以下,
        package: 'package', //统一下单接口返回的 prepay_id 参数值,提交格式如:prepay_id=*,
        paySign: 'paySign', //签名,具体签名方案参见小程序支付接口文档,
        success: res => ,
        fail: () => ,
        complete: () => 
      );
      // 7. 查询后台 订单状态
      const res = await request(
        url: "/my/orders/chkOrder",
        method: "POST",
        header,
        data: 
          order_number
        
      );

      await wx.showToast(
        title: '支付成功'
      );
      // 8. 支付成功了,跳转到订单页面
      wx.navigateTo( url: '/pages/order/order' );
     catch (error) 
      await wx.showToast(
        title: '支付失败'
      );
    
  
)

auth.wxml

<view>
  <button
    bindtap="handlePayOrder"
    type="primary"
    plain="true"
    open-type="getUserInfo"
    bindgetuserinfo="handleGetUserInfo"
  >支付</button>
</view>

auth.js

// pages/auth/auth.js
Page(
  // 1. 获取用户信息 可以通过封装promise简化代码
  handleGetUserInfo(e) 
    try 
      const  encryptedData, iv, signature, rawData  = e.detail;
    // 2. 获取小程序登录后的code
    wx.login(
      success: res => 
        const  code  = res;
        // 3. 发送请求,获取用户的token
        const loginParams = 
          encryptedData,
          rawData,
          iv,
          signature,
          code
        ;
        wx.request(
          url: '/users/wxlogin', //开发者服务器接口地址",
          data: loginParams, //请求的参数",
          method: 'POST',
          complete: (result) => 
            console.log(result);
            // 假如成功
            if (true) 
              // 4. 把token存入缓存中,同时跳转回上一个页面
              const  token  =  token: "ZDFAW3ERSDFSD"  || result;
              wx.setStorageSync('token',token);
              wx.navigateBack(
                delta: 1 //返回的页面数,如果 delta 大于现有页面数,则返回到首页,
              );
            
          
        );
      
    );
     catch (error) 
      console.log(error);
    
  
)

以上是关于微信小程序开放能力的主要内容,如果未能解决你的问题,请参考以下文章

微信小程序开放能力

微信小程序开放能力

注册微信小程序

重磅App内可直接打开微信小程序,新增内容安全接口等

微信小程序再添能力:搜一搜增加小程序入口

微信小程序社交立减金正式开放!一篇文章看懂它(开通微信免充值代金券)