微信小程序获取手机号
wxml 代码: <!-- 授权 --> <button type="primary" open-type="getUserInfo" bind:tap="getUserProfile">授权登录</button> <!-- 获取用户手机号 --> <button open-type="getPhoneNumber" bindgetphonenumber="getphone">获取手机号</button> <!-- 展示手机号 --> <view>您的手机号:{{phone}}</view>
wxjs:代码
// 授权登录 getUserProfile(e) { // 获取用户信息 wx.getUserProfile({ desc: '用于完善会员资料', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写 success: (res) => { // 头像 let avatarUrl=res.userInfo.avatarUrl; // 昵称 let nickName=res.userInfo.nickName; wx.login({ success:res=>{ // 获取code let code=res.code; wx.request({ url: 'http://www.yan.com/api/xcx/getLogin', data: { code:code, avatarUrl:avatarUrl, nickName:nickName, }, method:"POST", header: { 'content-type': 'application/json' // 默认值 }, // 数据返回json格式 success (res) { console.log(res); // 存储openid 用户获取手机号 wx.setStorageSync('openid', res.data.data.openid ); // 存储session_key用于获取手机号 wx.setStorageSync('sessionKey', res.data.data.sessionKey); // 存储用户id wx.setStorageSync('userid',res.data.data.uid); } }) } }) } }) },
将用户信息发送后台
/*获取用户信息的路由*/ Route::post('xcx/getLogin','xcx\LoginController@getLogin');
控制器代码:
public function getLogin(Request $request){ // 接受code $code=$request->post('code'); // 接受头像 $avatarUrl=$request->post('avatarUrl'); // 接受昵称 $nickName=$request->post('nickName'); // 获取appid $appid = "wx64832aa6eaea82b0"; // 从微信公众平台获得secret $secret = "95e2acaf355dbcb443f5cd4748a152ed"; // 发送请求换取openid和sessionkey $url = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=" . $code. "&grant_type=authorization_code"; // 暂使用file_get_contents()发送请求,你可以使用CURL扩展的形式实现,获取opid和session_key $res = json_decode(file_get_contents($url), true); // 给$params追加openid $params['openid'] = $res['openid']; // 给$params追加session_key $params['sessionKey'] = $res['session_key']; // 查看数据库里是否有openid,有就修改,没有就添加 $user = Wxuser::where('openid', $params['openid'])->first(); $params['uid']=$user['id']; // 有就修改用户的额openID if ($user) { // 将sessionKey 发送至小程序缓冲用于获取手机号 Wxuser::where('openid', $params['openid'])->update(['sessionKey'=>$params['sessionKey']]); return ['code' => 201, 'meg' => '修改成功', 'data' => $params]; } else { // 没有就添加新用户 $add = Wxuser::create($params); return ['code' => 200, 'meg' => '添加成功', 'data' => $res]; } }
小程序点击获取手机号按钮
<!-- 获取用户手机号 --> <button type="primary" open-type="getPhoneNumber" bindgetphonenumber="getphone">获取手机号</button>
wx.js代码
需要将 button 组件 open-type 的值设置为 getPhoneNumber,当用户点击并同意之后,可以通过 bindgetphonenumber 事件回调获取到微信服务器返回的加密数据, 然后在第三方服务端结合 session_key 以及 app_id 进行解密获取手机号。
// 获取手机号 getphone(e){ // open-type="getPhoneNumber" bindgetphonenumber="getphone" 获取encryptedData var encryptedData =e.detail.encryptedData; var iv =e.detail.iv; // 取出授权登录的openid let openid= wx.getStorageSync('openid') // 取出授权登录的sessionKey let sessionKey= wx.getStorageSync('sessionKey') // 取出用户id var userid= wx.getStorageSync('userid') wx.request({ url: 'http://www.yan.com/api/xcx/send', data: { encryptedData:encryptedData, iv:iv, openid:openid, sessionKey:sessionKey, userid:userid }, method:"POST", header: { 'content-type': 'application/json' // 默认值 }, // 数据返回json格式 success :res=> { console.log(res); if (res) { this.setData({ phone:res.data.data }) } } }) }
laravel 路由
/*获取手机号*/ Route::post('xcx/send','xcx\LoginController@send');
laravel控制器
//获取手机号 public function send(Request $request){ $encryptedData = $request->post('encryptedData'); $iv = $request->post('iv'); $sessionKey = $request->post('sessionKey'); $id=$request->post('userid'); $appid = 'wx64832aa6eaea82b0'; $pc = new WXBizDataCrypt($appid, $sessionKey); $errCode = $pc->decryptData($encryptedData, $iv, $data ); if ($errCode == 0) { $phone = json_decode($data, true)['phoneNumber']; //根据用户id 将手机号添加到数据表里面 Wxuser::where('id','=',$id)->update(['phone' => $phone]); return ['code' => 200, 'meg' => 'success', 'data' => $phone]; } else { return ['code' => 500, 'meg' => 'error', 'data' => $errCode]; }
模型代码
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Wxuser extends Model { // protected $guarded=[]; public $timestamps=false; }
解密官方文档:
https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/signature.html
下载php
将文件放入开发的项目中,并修改文件名称和修改命名空间
demo.php
<?php namespace App\Service\PHP; use App\Service\PHP\wxBizDataCrypt; //include_once "WXBizDataCrypt.php"; $appid = 'wx4f4bc4dec97d474b'; $sessionKey = 'tiihtNczf5v6AKRyjwEUhQ=='; $encryptedData="CiyLU1Aw2KjvrjMdj8YKliAjtP4gsMZM QmRzooG2xrDcvSnxIMXFufNstNGTyaGS 9uT5geRa0W4oTOb1WT7fJlAC+oNPdbB+ 3hVbJSRgv+4lGOETKUQz6OYStslQ142d NCuabNPGBzlooOmB231qMM85d2/fV6Ch evvXvQP8Hkue1poOFtnEtpyxVLW1zAo6 /1Xx1COxFvrc2d7UL/lmHInNlxuacJXw u0fjpXfz/YqYzBIBzD6WUfTIF9GRHpOn /Hz7saL8xz+W//FRAUid1OksQaQx4CMs 8LOddcQhULW4ucetDf96JcR3g0gfRK4P C7E/r7Z6xNrXd2UIeorGj5Ef7b1pJAYB 6Y5anaHqZ9J6nKEBvB4DnNLIVWSgARns /8wR2SiRS7MNACwTyrGvt9ts8p12PKFd lqYTopNHR1Vf7XjfhQlVsAJdNiKdYmYV oKlaRv85IfVunYzO0IKXsyl7JCUjCpoG 20f0a04COwfneQAGGwd5oa+T8yO5hzuy Db/XcxxmK01EpqOyuxINew=="; $iv = 'r7BXXKkLb8qrSNn05n0qiA=='; $pc = new WXBizDataCrypt($appid, $sessionKey); $errCode = $pc->decryptData($encryptedData, $iv, $data ); if ($errCode == 0) { print($data . "\n"); } else { print($errCode . "\n"); }
ErrorCode.php
<?php namespace App\Service\PHP; /** * error code 说明. * <ul> * <li>-41001: encodingAesKey 非法</li> * <li>-41003: aes 解密失败</li> * <li>-41004: 解密后得到的buffer非法</li> * <li>-41005: base64加密失败</li> * <li>-41016: base64解密失败</li> * </ul> */ class ErrorCode { public static $OK = 0; public static $IllegalAesKey = -41001; public static $IllegalIv = -41002; public static $IllegalBuffer = -41003; public static $DecodeBase64Error = -41004; } ?>
WXBizDataCrypt.php
<?php namespace App\Service\PHP; use App\Service\PHP\errorCode; 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; } }
tp框架获取手机号的代码,参看以下链接
https://blog.csdn.net/guanj0623/article/details/121139157?spm=1001.2014.3001.5501