作者 何书鹏

用户授权获取手机号

... ... @@ -5,8 +5,8 @@ namespace app\api\controller;
use app\api\model\Tax;
use app\api\model\UserAddress;
use app\api\model\UserCoupon;
use app\api\model\UserInvitation;
use app\common\controller\Api;
use EasyWeChat\Factory;
use fast\Http;
use think\Config;
use think\Db;
... ... @@ -16,7 +16,7 @@ use think\Db;
*/
class User extends Api
{
protected $noNeedLogin = ['third','joinUs'];
protected $noNeedLogin = ['third','joinUs','getPhoneNumber'];
protected $noNeedRight = '*';
public function _initialize()
... ... @@ -132,33 +132,47 @@ class User extends Api
}
}
/**
* 获取微信手机号
*
* @ApiMethod (POST)
* @param string $token token
* @param string $code Code码
* @ApiTitle (用户授权获取手机号)
* @ApiMethod (POST)
* @ApiParams (name="sessionKey", type="string", required=true, description="小程序sessionKey")
* @ApiParams (name="iv", type="string", required=true, description="小程序iv")
* @ApiParams (name="encryptedData", type="string", required=true, description="小程序encryptedData")
* @ApiReturn ({
'code':'1',
'msg':'返回成功',
"data": {
"mobile": "13580006666", //没有区号的手机号
}
})
*/
public function thirdMobile()
public function getPhoneNumber()
{
$code = $this->request->post('code');
if (!$code){
$this->error('后台所需参数缺失请完善参数');
$param = $this->request->param();
$validate = new \think\Validate([
'sessionKey' => 'require',
'iv' => 'require',
'encryptedData' => 'require',
]);
$validate->message([
'sessionKey.require' => 'sessionKey参数错误!',
'iv.require' => 'iv参数错误!',
'encryptedData.require' => 'encryptData参数错误!',
]);
if (!$validate->check($param)) {
$this->error($validate->getError());
}
$token = $this->getToken();
$param = [];
$param['code'] = $code;
$param = json_encode($param);
$wxapi = Http::post('https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token='.$token,$param);
$wxapi = json_decode($wxapi,true);
if ($wxapi['errcode'] != 0){
$this->error($wxapi['errmsg']);
}
$mobile = $wxapi['phone_info']['purePhoneNumber'];
// 获取小程序配置
$app = Factory::miniProgram([
'app_id' => Config::get('site.appid'),
'secret' => Config::get('site.secret'),
]);
$res = $app->encryptor->decryptData($param['sessionKey'], $param['iv'], $param['encryptedData']);
// 更新手机号
$user = $this->auth->getUser();
$user->mobile = $mobile;
$user->isUpdate()->save();
$user->mobile = $res['purePhoneNumber'];
$user->save();
$this->success('授权成功',['mobile' => $res['purePhoneNumber']]);
}
/**
... ...