<?php /** * Description of HomeBase *前台基类 * @author xinjun */ namespace ControllerHome; use ControllerComBase; use FrameworkNetRequest; use ModelWxTokenModel; use ModelWxUserModel; class HomeBase extends Base { public static $appid = null; public static $secret = null; public static $access_token = null; public function __construct() { parent::__construct(); $tokenModel = new TokenModel(); //取基础access_token $data = $tokenModel->getAccessToken(array('id' => 1)); //赋值公众号的appid和secret self::$appid = $data['nf_appid']; self::$secret = $data['nf_appsecret']; //判断数据库里值是否为空 if (empty($data['nf_val'])) { //重新获取token $tokenData = $this->getAccessToken(self::$appid, self::$secret); $tokenData = json_decode($tokenData, 1); //存数据库 $result = $tokenModel->edit(array('nf_val' => $tokenData['access_token'], 'nf_time' => time()), array('id' => 1)); if ($result) { //赋值给变量 self::$access_token = $tokenData['access_token']; } else { return false; } } else { if (($data['nf_time'] + 6000) <= (time())) { //超过7000秒重新获取access_token $tokenData = $this->getAccessToken(self::$appid, self::$secret); $tokenData = json_decode($tokenData, 1); $result = $tokenModel->edit(array('nf_val' => $tokenData['access_token'], 'nf_time' => time()), array('id' => 1)); if ($result) { self::$access_token = $tokenData['access_token']; } else { return false; } } else { self::$access_token = $data['nf_val']; } } } /** * 获取基础access_token * @return type */ public function getAccessToken($appid, $secret) { $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $secret; $https = true; $method = 'get'; $data = null; $result = $this->request($url, $https, $method, $data); return $result; } } /** 1 获取access_token 并保存到数据库只要有人访问就判断此access_token是否有效, 如果失效就是超时了,就重新获得access_token保存数据库。 2 判断当前用户是从分享过来的,还是直接从微信公众号过来的。 如果是微信公众号过来的,即直接或的当前用户的openid(前端获得传给我)取出刚才的access_token 用get方式请求https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN 获取该用户的所有信息,保存到数据库 如果是通过分享过来的分享的时候传当前用户的id值。用户同意后前端获取当前用户的code,然后传给我 我get方式请求https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx4c71e5c3aad7f536&secret=710738e8528df03210e4002d570861f5&code=".$_GET['code']."&grant_type=authorization_code 获取当前用户的access_token(不是基础access_token)和他的openid,然后我拿着这两个值去请求https://api.weixin.qq.com/sns/userinfo?access_token=".$data['access_token']."&openid=".$data['openid']."&lang=zh_CN 获取当前用户的信息并保存。同时按照规定,如果当前用户 https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx4c71e5c3aad7f536&redirect_uri=http%3A%2F%2Fwx.nongfaziran.com%2FHome%2Ftest%2FgetOne&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect **/