微信小程式wx.login登陸+php
阿新 • • 發佈:2018-12-14
wxml:
<button bindtap='login'>登入</button>
js:
//登入獲取code login: function () { wx.login({ success: function (res) { console.log(res) //傳送請求 wx.request({ url: 'http://localhost:8099/login.php', //介面地址 data: { code: res.code }, success: function (res) { if (res.statusCode == 200) { console.log(res.data) wx.setStorageSync('openid', res.data) } else { console.log(res.errMsg) } }, fail:function(e){ console.log(e) } }) } }) },
php:
<?php //宣告CODE,獲取小程式傳過來的CODE if(!isset($_GET["code"])){ echo json_encode(array("statusCode"=>0 , "data"=>null , "errMsg"=>"error")); exit; } $code = $_GET["code"]; //配置appid $appid = "wx8b7c8ec48bde6f27"; //配置appscret $secret = "91dcf8013656dd5335a4a6c820cbc9f7"; $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$appid.'&secret='.$secret.'&js_code='.$code.'&grant_type=authorization_code'; $info = file_get_contents($url);//get請求網址,獲取資料 $jsonObj = json_decode($info);//對json資料解碼 if(isset($jsonObj->errcode)){ echo json_encode(array("statusCode"=>0 , "data"=>null , "errMsg"=>$info)); exit; } $openid = $jsonObj->openid; $session_key = $jsonObj->session_key; echo json_encode(array("statusCode"=>0 , "data"=>$jsonObj , "errMsg"=>"success")); ?>