微信小程序常用操作(獲取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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章