wxml:
<button type="primary" open-type="getUserInfo" bind:tap="login">授權登錄</button>
wxjs: // 微信授權 login(evt){ var that=this; // wx.getUserProfile獲取用戶信息 wx.getUserProfile({ // desc 聲明獲取用戶個人信息后的用途,不超過30個字符 desc: 'desc', success:res=>{ if (res.userInfo) { /* wx.login 調用接口獲取登錄憑證(code)。通過憑證進而換取用戶登錄態信息,包括用戶在當前小程序的唯一標識(openid)、微信開放平台帳號下的唯一標識(unionid,若當前小程序已綁定到微信開放平台帳號)及本次登錄的會話密鑰(session_key)*/ wx.login({ success:ret=>{ // 獲取code var code=ret.code; // 獲取用戶昵稱 var nickName=res.userInfo.nickName; // 獲取用戶照片 var avatarUrl=res.userInfo.avatarUrl; // 發送至php后端 wx.request({ url: 'http://www.yan.com/api/xcx/login', //僅為示例,並非真實的接口地址 data: { code:code, nickName:nickName, avatarUrl:avatarUrl }, method:"POST", header: { 'content-type': 'application/json' // 默認值 }, // 數據返回json格式 success (res) { console.log(res.data.data); // console.log(re.data) // 將用戶id儲存於本地 wx.setStorageSync('userid', res.data.data.id); wx.switchTab({ // 跳轉至首頁 url: '/pages/good/good', }) } }) } }) }else{ console.log('用戶拒絕啦'); } } }) }
通過laravel7 api.php路由將數據發送至控制器,進行添加入庫:
Route::group(['namespace'=>'xcx'],function (){ // 授權 登錄 Route::post('xcx/login','LoginController@login'); });
控制器處理數據:
public function login(Request $request) { $params = $request->post(); // 獲取appid $appid = "wx64832aa6eaea82b0"; // 從微信公眾平台獲得secret $secret = "95e2acaf355dbcb443f5cd4748a152ed"; // 發送請求換取openid和sessionkey $url = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=" . $params['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['session_key'] = $res['session_key']; // 查看數據庫里是否有openid,有就修改,沒有就添加 $res = Wxuser::where('openid', $params['openid'])->first(); // 有就修改用戶的額openID if ($res) { Wxuser::where('openid', $params['openid'])->update($params); return ['code' => 201, 'meg' => '修改成功', 'data' => $res]; } else { // 沒有就添加新用戶 $add = Wxuser::create($params); return ['code' => 200, 'meg' => '添加成功', 'data' => $add]; } }
模型代碼:
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Wxuser extends Model { // protected $guarded=[]; public $timestamps=false; }
效果圖: