这里是用小程序测试号写的示例 /** * 微信小程序授权登录 控制器 */ public function login(Request $request){ $code = $request->post("code"); $nickname = $request->post("nickName"); $appid = " 小程序ID "; $secret = " 小程序密钥 "; $url = "https://api.weixin.qq.com/sns/jscode2session? appid=$appid&secret=$secret&js_code=$code&grant_type=authorization_code"; $res = json_decode(file_get_contents($url),true); $info = [ //'nickname' => $nickname, 'openid' => $res['openid'], 'sessionkey' => $res['session_key'] ]; $open = Wx::where('openid',$res['openid'])->first(); $token = JWT::encodeJwt($open['openid']); if($res){ return Apiadmin::on(['message'=>'用户已存 在在','token'=>$token,'openid'=>$open['openid']]); }else{ return Apiadmin::ok(['message'=>'用户不存在添加入库','token'=>$token,'openid'=>$open['openid']]); DB::table('表名')->insert($info); } }
// 路由
Route::any('wxlogin',[\App\Http\Controllers\WxController::class,'login']);
//微信开发者工具
login:function(){
wx.getUserProfile({
desc: '正在授权',
success(res){
let nickName=res.userInfo.nickName;
wx.login({
timeout: 1000,
success(ress){
let code =ress.code
wx.request({
url: 'http:// 域名',
data: {code:code,nickName:nickName},
header: {'content-type':'application/json'},
method: 'post',
success: (result)=>{
console.log(result)
let token=result.data.date.token;
let openid=result.data.date.openid;
wx.setStorageSync('token',token)
wx.setStorageSync('openid', openid)
wx.showToast({
title: '授权成功',
icon: 'none',
success: (result)=>{
wx.navigateTo({
url: '/pages/show/show',
})
},
fail: ()=>{},
complete: ()=>{}
});
},
fail: ()=>{},
complete: ()=>{}
});
}
})
},
fail:function(err){
console.log("获取失败",err)
}
})
},
//授权登录的按钮
<view><button open-type="getUserProfile" bindtap="login">授权登录</button></view>