Home  >  Article  >  WeChat Applet  >  How to get the mobile phone number in the mini program (thinkphp3.2.3 framework)

How to get the mobile phone number in the mini program (thinkphp3.2.3 framework)

不言
不言Original
2018-08-14 17:12:504608browse

The content of this article is about how to obtain a mobile phone number through a small program (thinkphp3.2.3 framework). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. Directly upload the code php

namespace Home\Controller;
use Think\Controller;
class ApiController extends Controller {
    /**
 * error code 说明.
 * <ul>

 *    <li>-41001: encodingAesKey 非法</li>
 *    <li>-41003: aes 解密失败</li>
 *    <li>-41004: 解密后得到的buffer非法</li>
 *    <li>-41005: base64加密失败</li>
 *    <li>-41016: base64解密失败</li>
 * </ul>
 */
    public static $OK = 0;
    public static $IllegalAesKey = -41001;
    public static $IllegalIv = -41002;
    public static $IllegalBuffer = -41003;
    public static $DecodeBase64Error = -41004;
    // 小程序
    public static $appid = &#39;XXX&#39;;  //小程序appid
    public static $secret = &#39;XXX&#39;; //小程序秘钥   

public $sessionKey =&#39;&#39;;

    // 获取openId session-key 等
    public function getopenId($value=&#39;&#39;)
    {   

        $code = I(&#39;post.code&#39;);
        $appid = self::$appid;
        $secret = self::$secret;
        $url = &#39;https://api.weixin.qq.com/sns/jscode2session?appid=&#39;. $appid.&#39;&secret=&#39;.$secret.&#39;&js_code=&#39;.$code.&#39;&grant_type=authorization_code&#39;;
        $result = httpGet($url);
        $res = json_decode($result);
        // session([&#39;sessionKey&#39;=>$res,&#39;expire&#39;=>7200]);
        $this->ajaxReturn($res);

        
    }

    // 获取小程序手机号api 接口,对应下面小程序 js
    public function getPhoneNumber($value=&#39;&#39;)
    {   

       $encryptedData = I(&#39;get.encryptedData&#39;);
       $iv = I(&#39;get.iv&#39;);
       $this->sessionKey=I(&#39;get.session_key&#39;);
       $res = $this->decryptData($encryptedData, $iv);
       // $res = json_decode($res);
       if($res->phoneNumber){
            // $res->phoneNumbe 就是手机号可以 写入数据库或者做其他操作
       }
       
       $this->ajaxReturn([&#39;msg&#39;=>$res,&#39;status&#39;=>&#39;1&#39;]); //把手机号返回
        
    }

    // 小程序解密
   public function decryptData($encryptedData, $iv)
    {
        if (strlen($this->sessionKey) != 24) {
            return self::$IllegalAesKey;
        }
        $aesKey=base64_decode($this->sessionKey);

        
        if (strlen($iv) != 24) {
            return self::$IllegalIv;
        }
        $aesIV=base64_decode($iv);

        $aesCipher=base64_decode($encryptedData);

        $result=openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);

        $dataObj=json_decode( $result );
        if( $dataObj  == NULL )
        {
            return self::$IllegalBuffer;
        }
        if( $dataObj->watermark->appid != self::$appid )
        {
            return self::$IllegalBuffer;
        }

        return  $dataObj;
        // return self::$OK;
    }


function httpGet($url) {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_TIMEOUT, 500);
    // 为保证第三方服务器与微信服务器之间数据传输的安全性,所有微信接口采用https方式调用,必须使用下面2行代码打开ssl安全校验。
    // 如果在部署过程中代码在此处验证失败,请到 http://curl.haxx.se/ca/cacert.pem 下载新的证书判别文件。
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($curl, CURLOPT_URL, $url);

    $res = curl_exec($curl);
    curl_close($curl);

    return $res;
}


}

//2. Mini program

2.1 Log in first on the app.js startup page

// 登录
    // if (!wx.getStorageSync(&#39;session_key&#39;) || wx.getStorageSync(&#39;time&#39;) < Date.parse(new Date())){ // 判断session_key是不是存在获者过期
      wx.login({
        success: res => {
          console.log(res)
          // 发送 res.code 到后台换取 openId, sessionKey, unionId
          wx.request({
            url: &#39;https://www.zhixiaobing.com/index.php?m=&c=api&a=getopenId&#39;,
            header: { "Content-Type": "application/x-www-form-urlencoded" },
            method: &#39;post&#39;,
            data: { code: res.code },
            success: function (res) {
              console.log(res.data);
              wx.setStorageSync(&#39;openid&#39;, res.data.openid)
              wx.setStorageSync(&#39;session_key&#39;, res.data.session_key)
              wx.setStorageSync(&#39;time&#39;, parseInt(Date.parse(new Date())) + 7200)
            }
          })
          
        }
      })

//2.2 Write components in the mini program template

<button open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber" >//这是官方的组件点击会弹出授权页面

Write the following function in js

getPhoneNumber: function (e) {
    var that =this;

    var session_key = wx.getStorageSync(&#39;session_key&#39;)
    if (e.detail.errMsg == &#39;getPhoneNumber:fail user deny&#39;) {
      wx.showModal({
        title: &#39;提示&#39;,
        showCancel: false,
        content: &#39;未授权&#39;,
        success: function (res) { }
      })
    } else {//确认授权
      wx.request({
        url: &#39;https://www.showoow.com/index.php?m=mini&c=api&a=getPhoneNumber&openid=&#39; + wx.getStorageSync(&#39;openid&#39;), //openid是app.js 已经存的
        header: {"Content-Type": "application/x-www-form-urlencoded" },
        method: "get",
        data: {
          encryptedData: e.detail.encryptedData, iv: e.detail.iv, session_key:session_key
        },
        success:function(res){
          if (res.data.msg.phoneNumber){
            console.log(res);
            wx.showModal({
              title: &#39;提示&#39;,
              showCancel: false,
              content: &#39;授权成功&#39;,
              success: function () {
                wx.setStorageSync(&#39;phoneNumber&#39;, res.data.msg.phoneNumber);
                var time = Date.parse(new Date()) + 60 * 60 * 24 * 2
                wx.setStorageSync(&#39;exp&#39;, time );
              }
            })
            setTimeout(function(){
              wx.navigateTo({
                url: &#39;/pages/form/form&#39;,
              })
            },1500);
            that.setData({
              show:&#39;show&#39;,
              hiden:&#39;&#39;
            })
          }else{
            wx.showToast({
              title: &#39;授权失败&#39;,
              icon:&#39;loading&#39;
            })
          }
        
        },
        fail:function(){
          wx.showToast({
            title: &#39;授权失败&#39;,
            icon: &#39;loading&#39;
          })
        }
      })
     
    }
  },

This is the end of the mini program to obtain the mobile phone number. I wrote a mini program in the company. You can Get the mobile phone number normally

Related recommendations:

How to pass parameters and receive data in the WeChat applet

The page in the applet is compatible with h5 Parsing of tags

The above is the detailed content of How to get the mobile phone number in the mini program (thinkphp3.2.3 framework). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn