微信小程序常用操作(获取openid,获取电话号码,模板消息)

  • 获取openid

è¿éåå¾çæè¿°

第一种使用wx.getUserInfo直接获取微信头像,昵称

wx.getUserInfo({
     success: function (res) {
      that.setData({
          nickName: res.userInfo.nickName,
          avatarUrl: res.userInfo.avatarUrl,
      })
      },
})

第二种 
我们在使用小程序wx.login API进行登录的时候,直接使用wx.getUserInfo是不能获取更多的信息的,如微信用户的openid。 
官方提示,需要发送获取到的code进行请求到微信的后端API,

根据文档,只需要进行一个get请求到如下地址即可:
https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&
js_code=JSCODE&grant_type=authorization_code

appid和secret在微信小程序后台可以看到,
js_code为使用wx.login登录时获取到的code参数数据,
grant_type这个不用改动。
 

JS 文件

 var openId = (wx.getStorageSync('openId'))
        if (openId) {
          wx.getUserInfo({
            success: function (res) {
              that.setData({
                nickName: res.userInfo.nickName,
                avatarUrl: res.userInfo.avatarUrl,
              })
            },
            fail: function () {
              // fail
              console.log("获取失败!")
            },
            complete: function () {
              // complete
              console.log("获取用户信息完成!")
            }
          })
        } else {
          wx.login({
            success: function (res) {
              console.log(res.code)
              if (res.code) {
                wx.getUserInfo({
                  withCredentials: true,
                  success: function (res_user) {
                    wx.request({
                     //后台接口地址
                      url: 'https://....com/wx/login',
                      data: {
                        code: res.code,
                        encryptedData: res_user.encryptedData,
                        iv: res_user.iv
                      },
                      method: 'GET',
                      header: {
                        'content-type': 'application/json'
                      },
                      success: function (res) {
                        // this.globalData.userInfo = JSON.parse(res.data);
                        that.setData({
                          nickName: res.data.nickName,
                          avatarUrl: res.data.avatarUrl,
                        })
                        wx.setStorageSync('openId', res.data.openId);

                      }
                    })
                  }, fail: function () {
                    wx.showModal({
                      title: '警告通知',
                      content: '您点击了拒绝授权,将无法正常显示个人信息,点击确定重新获取授权。',
                      success: function (res) {
                        if (res.confirm) {
                          wx.openSetting({
                            success: (res) => {
                              if (res.authSetting["scope.userInfo"]) {如果用户重新同意了授权登录
                                wx.login({
                                  success: function (res_login) {
                                    if (res_login.code) {
                                      wx.getUserInfo({
                                        withCredentials: true,
                                        success: function (res_user) {
                                          wx.request({
                                           url: 'https://....com/wx/login',
                                            data: {
                                              code: res_login.code,
                                              encryptedData: res_user.encryptedData,
                                              iv: res_user.iv
                                            },
                                            method: 'GET',
                                            header: {
                                              'content-type': 'application/json'
                                            },
                                            success: function (res) {
                                              that.setData({
                                                nickName: res.data.nickName,
                                                avatarUrl: res.data.avatarUrl,

                                              })
                                              wx.setStorageSync('openId', res.data.openId);
                                            }
                                          })
                                        }
                                      })
                                    }
                                  }
                                });
                              }
                            }, fail: function (res) {

                            }
                          })

                        }
                      }
                    })
                  }, complete: function (res) {


                  }
                })
              }
            }
          })

        }


  },
  globalData: {   
    userInfo: null
  }

官方文档: https://mp.weixin.qq.com/debug/wxadoc/dev/api/signature.html 微信官方提供了多种编程语言的示例代码(点击下载)。每种语言类型的接口名字均一致。调用方式可以参照示例。

 

  • 获取电话号码

两种(正常注册手机号码-密码+一键获取当前用户手机号码)

getPhoneNumber这个组件要通过button来实现。将button中的open-type=“getPhoneNumber”,并且绑定bindgetphonenumber事件获取回调。

在使用这个组件之前必须先调用 login 接口

然后传递code,iv,encryptedData参数到后台,后台解密
代码:

<button open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber"
 hover-class="none">一键自动注册</button>

  getPhoneNumber: function (e) {
      console.log(e.detail.errMsg)
      if (e.detail.errMsg == 'getPhoneNumber:fail user deny') {
        wx.showModal({
          title: '提示',
          showCancel: false,
          content: '未授权',
          success: function (res) { }
        })
      } else {
        wx.login({
          success: function (res) {
            var code = res.code;
            if (res.code) {
              //发起网络请求  
              console.log(res.code)
            } else {
              console.log('获取用户登录态失败!' + res.errMsg)
            }
            wx.showModal({
              title: '提示',
              showCancel: false,
              content: '同意授权',
              success: function (res) {
                var that = this;
                console.log(123)
                wx.request({
                  url: '/wxapplet/wx/wechat/phone',
                  data: {
                    code: code,
                    iv: e.detail.iv,
                    encryptedData: e.detail.encryptedData
                  },
                  method: 'GET',
                  header: {
                    'content-type': 'application/json'
                  },
                  success: function (res) {
                    wx.setStorageSync('user', res.data.data);
                    if(res.data.code == "200"){
                      console.log(res.data.data)
                      wx.showToast({
                        title: '一键绑定成功',
                        icon: 'success',
                        duration: 2000,
                        success: function(){
                          wx.switchTab({ url: '../user-center/index' });
                        }
                      })
                    }else{
                      wx.showModal({
                        title: '提示',
                        content: '一键绑定失败,请重新尝试',
                        success: function (res) {
                          if (res.confirm) {
                            console.log('用户点击确定')
                          } else if (res.cancel) {
                            console.log('用户点击取消')
                          }
                        }
                      })
                    }                    
                  },
                });
              }
            })
          }
        });        
      }

 

  • 模板消息

formId 或 prepay_id:

  1. 用户必须得提交了表单或进行了支付才能推送模板消息,
  2. 表单提交后能得到 formId,
  3. 支付完成能得到 prepay_id,
  4. 而且一个 formId 或 prepay_id 只能推送一条消息。

openID:推送给谁的用户标识符

template_id:模板消息的模板编号,小程序的后台申请

模板消息的模板编号,小程序的后台申请
1
access_token:

  1. access_token 是全局唯一接口调用凭据,开发者调用各接口时都需使用 access_token,
  2. access_token 的有效期目前为2个小时,
  3. 需定时刷新,重复获取将导致上次获取的 access_token 失效。

后台

/**
 * SendTemplate 触发模板通知
 *
 * @return reposne
 */
public function SendTemplate($openId,$formId,$product,$activity)
{
    $tempalte_id = 'lv9T-PcgWn-Rkhq-1MxwaxvotO2VU3prc-wk1';
    $date_time = date('Y-m-d h:i:s', time());
    $data=array(
            'keyword1'  => array('value'=>$activity,'color'=>'#000000'),
            'keyword2'  => array('value'=>$product,'color'=>'#000000'),
            'keyword3'  => array('value'=>$date_time,'color'=>'#000000'),
            'keyword4'  => array('value'=>'15901419475','color'=>'#000000'),
    );

    $template = array(
        'touser' => $openId,
        'template_id' => $tempalte_id,
        'url' => 'pages/index/index',
        'form_id'=>$formId,
        'topcolor' =>'#7B68EE',
        'data' => $data,
    );

    $appid  =  "*****"
    $secret =   "*****
    $url ="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";

    $access_token=$this->httpGet($url);

    $access_token=JSON_decode($access_token)->access_token;

    $url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=$access_token";

    $template =  json_encode($template);

    $result = $this->httpPost($url,$template,'json');

    return $result;

}

官方文档:http://t.cn/RmvjgtF

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值