<button bindtap="login">登录</button>
login() {
wx.login({
success: (res) => {
app.base.request({
url: 'login',
data:{
code:res.code
},
sCallback: (res) => {
}
})
}
})
},
class Login{
function __construct()
{
$this->AppID = config('app_id');
$this->AppSecret = config('app_secret');
}
public function index($code){
$LoginUrl = sprintf(
config('login_url'),
$this->wxAppID,$this->wxAppSecret,$code);
$res_str = curl_get($LoginUrl);//获取openid
$wxResult = json_decode($res_str, true);
if (empty($wxResult)) {
return '获取openid和sessionkey失败';
} else {
$randChars = getRandChar(32);//生成一个32位的随机字符串,包含大小写字母和数字
$timestamp = $_SERVER['REQUEST_TIME'];//得到请求开始时的时间戳
$token = md5($randChars . $timestamp);
$result = cache($token, $wxResult, 3600);
if($result){
return 'token:'.$token;
}else{
return '获取token失败';
}
}
}
}
"https://api.weixin.qq.com/sns/jscode2session?" .
"appid=%s&secret=%s&js_code=%s&grant_type=authorization_code"
- 登录结果
- appid和secretkey也可以写死,不过不要因为太长而在编辑器中手动换行,不然登录不了
$LoginUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=wxb961920bdfabbccc&secret=f994680e2fd34956888477b7176ef79d&js_code=".$code."&grant_type=authorization_code";
$token = Request::header('token');
$vars = Cache::get($token);
if(!$vars){
return 'token无效';
}else{
return $vars;
}