前提:企业认证的微信小程序
说明:微信小程序获取用户手机号需要用户授权允许,然后传递code、iv、encryptedData,后端解密。
已改好的laravel版阿里云网盘下载地址:
https://www.aliyundrive.com/s/4rKkDc3cT68
步骤实现:
一、后端:
1、Laravel后端:将下载好的sdk放在项目/app/Http/lib目录下wxBizDataCrypt,如下图所示:
2、加载扩展类文件,打开项目根目录下的composer.json文件,添加代码"app/Http/lib/wxBizDataCrypt"
部分如下
"autoload": { "psr-4": { "App\\": "app/" }, "classmap": [ "database/seeds", "database/factories", "app/Http/lib/wxBizDataCrypt" ] },
3、执行更新
composer dump-autoload
4、后端使用:use引入use App\Http\lib\wxBizDataCrypt\wxBizDataCrypt;
<?php namespace App\Http\Controllers\Api\WeappOfficial; use App\Http\Controllers\Api\Controller; use Illuminate\Http\Request; use App\Http\lib\wxBizDataCrypt\wxBizDataCrypt; class PhoneController extends Controller { //获取用户手机号 public function index(Request $request) { $appid = Env('WECHAT_MINI_PROGRAM_APPID'); $secret = Env('WECHAT_MINI_PROGRAM_SECRET'); $encryptedData = $request->encryptedData; //包括敏感数据在内的完整用户信息的加密数据 $jscode=$request->code; //用户登录授权获取到的code $iv=$request->iv; //用户登录授权获取到的iv //用code 获取sessionkey $access_token='https://api.weixin.qq.com/sns/jscode2session?appid='.$appid.'&secret='.$secret.'&js_code='.$jscode.'&grant_type=authorization_code'; $result = $this->curlOpen($access_token); $jsonarr = json_decode($result, true); $sessionKey = $jsonarr['session_key']; //获取手机号解密 $pc = new WXBizDataCrypt($appid, $sessionKey); $errCode = $pc->decryptData($encryptedData, $iv, $data ); if ($errCode == 0) { $js_data = json_decode($data,true); return response ()->json(['code'=>200,'msg'=>'success','data'=>$js_data['phoneNumber']]); }else{ return response ()->json(['code'=>$errCode,'msg'=>'error','data'=>'授权失败']); } } }
二、小程序前端方面:
1、放置按钮,用户调起授权获取手机号
<button class="btn_submit" open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber" type="primary">授权获取手机号</button>
2、代码获取及提交后端验证
//用户绑定手机号 getPhoneNumber (e) { var __that = this var iv = e.$wx.detail.iv; var encryptedData = e.$wx.detail.encryptedData; wx.login({ success:function(res){ const getUserPhones = await getUserPhone({ code: res.code, iv: iv, encryptedData: encryptedData, sharePhone: __that.sharePhone, }) console.log(getUserPhones) } }) },
文章评论(0)