Javascript Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 |
$(document).ready(function(){ google_app.init(); }); var googleUser = {}; function ginit(){ gapi.load('auth2', function() { /* Ready. Make a call to gapi.auth2.init or some other API */ auth2 = gapi.auth2.init({ client_id: '12345.apps.googleusercontent.com' }); attachSignin(document.getElementById('login_google')); attachSignin(document.getElementById('signup_google')); }); } function attachSignin(element) { auth2.attachClickHandler( element, {}, function(googleUser) { console.log(googleUser.getBasicProfile()); google_app.auto_login(googleUser.getBasicProfile()); }, function(error) { alert(JSON.stringify(error, undefined, 2)); } ); } var google_app = function(){ function auto_login(profile){ var data = { id: profile.getId(), name: profile.getName(), email: profile.getEmail() } login(data); } function login(data){ var params = data; /* Test data var params = { name: "RRR", email: "[email protected]", id: "102200000000000000" } */ $.ajax({ type: 'post', url: front_base + '/member/login_google_memebr', data: params, dataType: 'json', success: function(res){ if(typeof res.status == 'undefined'){ alert(res); }else if(res.status == 'fail'){ alert(res.message); }else{ //console.log(res); var data = res.data; alert('登入成功'); if(data == 'cart'){ window.location.href = front_base + '/cart/checkout/'; }else{ window.location.href = front_base + '/member/'; } } }, error: function(res){ console.log(res); } }); } return { auto_login: auto_login } }(); |
PHP (Laravel)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
public function login_google_memebr(Request $req){ $data = $req->input(); //logg($data); $member = MemberM::where('email', $data['email']) ->first(); if($member == false){ //自動註冊 $member = new MemberM; $member->google_id = $data['id']; $member->email = $data['email']; $member->name = $data['name']; $member->password = Hash::make($data['id']); $member->type = 3; $member->save(); $this->send_reg_email($member->id); }else{ $member->google_id = $data['id']; $member->password = Hash::make($data['id']); $member->type = 3; $member->save(); } $remember = true; $credentials = [ 'email' => $data['email'], 'password' => $data['id'] ]; //logg($credentials); //logg(Hash::make($password)); $result = $this->guard()->attempt($credentials, $remember); $cart = new Cart; if($cart->item_count() > 0){ return $this->success_response('cart'); }else{ return $this->success_response(true); } } |
Reference: