PHP:微信获取token,openid

————————————————–获取 token———————————————-

/**
 * 获得access_token
 * @return bool
 */
function getAccessToken(){
    $appid = C("APPID");
    $secret = C("APPSECRET");
    $token_file = $_SERVER['DOCUMENT_ROOT'].__ROOT__."/Public/access_token";
    //读取文件内容
    $content = json_decode(file_get_contents($token_file));
    //获得access_token的凭证有效时间
    $expires_in = $content->expires_in;
    if(time()-filemtime($token_file) < $expires_in){
        //保存的token有效,返回token值
        return $content->access_token;
    }else{
        //保存的token无效,重新修改文件的数据
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
        $str = file_get_contents($url);
        $json = json_decode($str);
        $token = $json->access_token;
        if($token){
            file_put_contents($token_file,$str);
            return $token;
        }return false;
    }
}

———————————————静默授权 获取OpenID———————————————

   /**
     * 通过授权获得用户唯一标识openid
     * @param string $parameter
     * @return mixed|null|void
     */
    protected function getOpenid($parameter = ''){
        if(session("openid")){
            return session("openid");
        }else{
            $appID = C('APPID');
            $appsecret = C('APPSECRET');
            //1,用户同意授权,获取code
            if (!isset($_GET['code'])){
                //触发微信返回code码
                $url = C("HOST").__ACTION__.$parameter;
                $url = urlencode($url);
                $authUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appID&redirect_uri=$url&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
                Header("Location: $authUrl");
            }else{
                //获取code码,以获取openid
                $code = $_GET['code'];
            }
            //2,获得网页授权access_token
            $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appID&secret=$appsecret&code=$code&grant_type=authorization_code";
            $data = file_get_contents($url);
            $data = json_decode($data);
            //获取用户openid;
            $openid = $data->openid;
            //存储openid
            session('openid', $openid);
            return $openid;
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值