如何在微信小程序中授权获取手机号码

小程序获取手机号码

1、获取手机号码前提条件

该小程序为非个人开发者,且完成了认证的小程序开放(不包含海外主体)。需谨慎使用,若用户举报较多或被发现在不必要场景下使用,微信有权永久回收该小程序的该接口权限

2、开发

需要将 button 组件 open-type 的值设置为 getPhoneNumber,当用户点击并同意之后,可以通过 bindgetphonenumber 事件回调获取到微信服务器返回的加密数据, 然后在第三方服务端结合 session_key 以及 app_id 进行解密获取手机号。
其中session_key通过wx.login来换取用户code,然后通过code到服务端换取用户唯一openid和session_key;
1、view部分
    <button open-type="getPhoneNumber" bindgetphonenumber="bindgetphonenumber"></button>
2、js部分
   bindgetphonenumber(e){
     
        //e里面的数据为加密,需要通过签名算法解密,详情见官方文档
        console.log(e.detail.errMsg)
        console.log(e.detail.iv)
        console.log(e.detail.encryptedData);
        //通过服务端解密
        wx.request({
     
            url:"自己服务端地址",
            method:"POST",
            data:{
     
                encryptedData: e.detail.encryptedData,
				errMsg: e.detail.encryptedData,
				iv: e.detail.iv,
				session_key:session_key //通过登录获得
            }success(resp){
     
               //后台解密成功返回的数据包
                /*
               {
                    "phoneNumber": "13580006666",
                    "purePhoneNumber": "13580006666",
                    "countryCode": "86",
                    "watermark":
                    {
                        "appid":"APPID",
                        "timestamp": TIMESTAMP
                    }
                }
               */
                ...
            }
        })
   }
3、服务端 php语言
     public  function decPhone(){
     
        	//seeionkey
    		$openid=input('?post.openid')?input('post.openid'):"";
    		$session_key=input("?post.session_key")?input("post.session_key"):"";
    		$encryptedData=input('?post.encryptedData')?input('post.encryptedData'):"";
    		$iv=input('?post.iv')?input('post.iv'):"";
    		if ($openid=='') return 
    		$wxdec=new \WXBizDataCrypt($this->appid,$session_key);
    		$errCode = $wxdec->decryptData($encryptedData, $iv, $data );
    		if ($errCode == 0) {
     
    			return ajaxErr(0,'获取',json_decode($data,true));
    		} else {
     
    			return ajaxErr(10001,'获取',$errCode);
    		}
    }

4、服务端 WXBizDataCrypt.php



/**
 * 对微信小程序用户加密数据的解密示例代码.
 *
 * @copyright Copyright (c) 1998-2014 Tencent Inc.
 */


include_once "errorCode.php";


class WXBizDataCrypt
{
     
    private $appid;
	private $sessionKey;

	/**
	 * 构造函数
	 * @param $sessionKey string 用户在小程序登录后获取的会话密钥
	 * @param $appid string 小程序的appid
	 */
	public function __construct( $appid, $sessionKey)
	{
     
		$this->sessionKey = $sessionKey;
		$this->appid = $appid;
	}


	/**
	 * 检验数据的真实性,并且获取解密后的明文.
	 * @param $encryptedData string 加密的用户数据
	 * @param $iv string 与用户数据一同返回的初始向量
	 * @param $data string 解密后的原文
     *
	 * @return int 成功0,失败返回对应的错误码
	 */
	public function decryptData( $encryptedData, $iv, &$data )
	{
     
		if (strlen($this->sessionKey) != 24) {
     
			return ErrorCode::$IllegalAesKey;
		}
		$aesKey=base64_decode($this->sessionKey);

        
		if (strlen($iv) != 24) {
     
			return ErrorCode::$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 ErrorCode::$IllegalBuffer;
		}
		if( $dataObj->watermark->appid != $this->appid )
		{
     
			return ErrorCode::$IllegalBuffer;
		}
		$data = $result;
		return ErrorCode::$OK;
	}

}

5、返回错误实例 errorCode.php



/**
 * error code 说明.
 * 
    *
  • -41001: encodingAesKey 非法
  • *
  • -41003: aes 解密失败
  • *
  • -41004: 解密后得到的buffer非法
  • *
  • -41005: base64加密失败
  • *
  • -41016: base64解密失败
  • *
*/
class ErrorCode { public static $OK = 0; public static $IllegalAesKey = -41001; public static $IllegalIv = -41002; public static $IllegalBuffer = -41003; public static $DecodeBase64Error = -41004; } ?>

到此微信小程序获取用户手机号码就结束了

你可能感兴趣的:(小程序,微信小程序)