手机号授权注册
小程序前台js里
getPhoneNumber (e) {
wx.login({
success:ret=>{
console.log(ret.code);
wx.request({
url: 'http://www.接口.com/api/phone',
data:{
code:ret.code,
iv:e.detail.iv,
encryptedData:e.detail.encryptedData,
},
success:res=>{
console.log(res);
if(res.data.error_code==0){
this.setData({
hasUserInfo:true
})
wx.setStorageSync('token', res.data.token)
wx.switchTab({
url: '/pages/user/user',
})
}
wx.showToast({
title: res.data.msg,
icon:'nonde',
duration:2000
})
}
})
},
})
}
后台接口 控制器
public function phone(Request $request)
{
$url=sprintf(config('wx.url'),config('wx.appid'),config('wx.secret'),$request['code']);
$data=getWx($url);
$str=(new Phone())->getPhone($data['session_key'],$request['encryptedData'],$request['iv']);
if (empty($str)){
return json(['error_code'=>1000,'data'=>'','msg'=>'授权失败']);
}
$arr=json_decode($str,true);
$id=User::getPhone($arr['purePhoneNumber'],$data['openid']);
$token=(new Token())->createToken($id);
if ($id){
return json(['error_code'=>0,'token'=>$token,'msg'=>'登录成功']);
}
return json(['error_code'=>1000,'data'=>'','msg'=>'授权失败']);
}
方法中的common.php
function getWx($url)
{
$curl = curl_init(); // 启动一个CURL会话
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
$tmpInfo = curl_exec($curl); //返回api的json对象
//关闭URL请求
curl_close($curl);
$result = json_decode($tmpInfo, true);
return $result;
}
创建一个server/phone.php的类 下载sdk后demo写进这个类里 其余的设置好命名空间
public function getPhone($sessionKey,$encryptedData,$iv)
{
$appid = config('wx.appid');
$pc = new WXBizDataCrypt($appid, $sessionKey);
$errCode = $pc->decryptData($encryptedData, $iv, $data );
if ($errCode == 0) {
return $data;
}
return $errCode;
}
model中
public static function getPhone($phone,$openid)
{
$id=self::where('openid',$openid)->value('id');
if (!$id){
$id=self::create(['openid'=>$openid,'phone'=>$phone])->value('id');
}
return $id;
}
库就创建好了
然后是验签
composer安装jwt
composer require firebase/php-jwt
<?php
namespace app\api\server;
use app\Request;
use \Firebase\JWT\JWT;
class Token
{
//生成验签
function createToken($uid){
$key='!@#$%*&'; //这里是自定义的一个随机字串,应该写在config文件中的,解密时也会用,相当 于加密中常用的 盐 salt
$token=array(
"iss"=>$key, //签发者 可以为空
"aud"=>'', //面象的用户,可以为空
"iat"=>time(), //签发时间
"nbf"=>time(), //在什么时候jwt开始生效 (这里表示生成100秒后才生效)
"exp"=> time()+7200, //token 过期时间
"data"=>[ //记录的userid的信息,这里是自已添加上去的,如果有其它信息,可以再添加数组的键值对
'uid'=>$uid,
]
);
// print_r($token);
$jwt = JWT::encode($token, $key, "HS256"); //根据参数生成了 token
return $jwt;
}
//验证token
function checkToken($token){
$key='!@#$%*&';
$status=array("code"=>2);
try {
JWT::$leeway = 60;//当前时间减去60,把时间留点余地
$decoded = JWT::decode($token, $key, array('HS256')); //HS256方式,这里要和签发的时候对应
$arr = (array)$decoded;
$res['code']=1;
$res['data']=$arr['data'];
return $res;
} catch(\Firebase\JWT\SignatureInvalidException $e) { //签名不正确
$status['msg']="签名不正确";
return $status;
}catch(\Firebase\JWT\BeforeValidException $e) { // 签名在某个时间点之后才能用
$status['msg']="token失效";
return $status;
}catch(\Firebase\JWT\ExpiredException $e) { // token过期
$status['msg']="token失效";
return $status;
}catch(\Exception $e) { //其他错误
$status['msg']="未知错误";
return $status;
}
}
}
生成中间件
php think make:middleware CheckToken
use app\api\server\Token as TokenServer;
public function handle($request, \Closure $next)
{
$token=$request->header('token');
$res=(new TokenServer())->checkToken($token);
if ($res['code'] != 1 ){
return json(['error_code'=>999,'msg'=>$res['msg'],'data'=>''],400);
}
$request->uid = $res['data']->uid;
return $next($request);
}
创建route/route.php
->middleware(\app\middleware\CheckToken::class)
之后的请求中
header:{
'token':wx.getStorageSync('token')
},
就好了
本文详细阐述了微信小程序如何通过前端js获取用户手机号并进行授权,以及后端接口如何接收并验证加密数据,确保安全登录。涉及到了JWT验证和API交互的关键步骤。

2069

被折叠的 条评论
为什么被折叠?



