小程序下获取access_token的案例

发布时间:2020-12-21 11:28:50 作者:小新
来源:亿速云 阅读:292

这篇文章主要介绍了小程序下获取access_token的案例,具有一定借鉴价值,需要的朋友可以参考下。希望大家阅读完这篇文章后大有收获。下面让小编带着大家一起了解一下。

<button bindtap="token">获取token</button>
// pages/token/token.js
Page({
  data: {

  },
  token:function(){
    wx.request({
      url: 'xxxx',
      data:{},
      success:function(res){
        console.log(res.data);
        //这里我是用的新浪云的sae,所以存在读写权限问题,打印出来的信息会存在告警
      }
    });
  }
})
<?php exit();?>
{"access_token":"","expire_time":0}
<?php
  //验证
  function getToken(){
    $timestamp = $_GET["timestamp"];
    $nonce =$_GET["nonce"];
    $token="hello hqtoken";
    $signature=$_GET["signature"];
    $array=array($timestamp,$nonce,$token);
    sort($array);
    $tmpstr=implode("",$array);
    $tmpstr=sha1($tmpstr);
    if($tmpstr == $signature){
      echo $_GET["echostr"];
      exit;
    }
  }
  //获取AccessToken
  function getAccessToken(){
    $appid="你的appid";
    $appsecret = "你的appsecret";
    //文件存储
    $data=json_decode(get_php_file("access_token.php"));
    if($data->expire_time<time()){
      $url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret;
      $res=json_decode(httpGet($url));
      $access_token=$res->access_token;
      if($access_token){
        $data->expire_time=time()+7000;
        $data->access_token=$access_token;
        set_php_file("access_token.php",json_encode($data));
      }
    }else{
      $access_token=$data->access_token;
    }
    return $access_token;
  }
  //公共的curl方法
  function httpGet($url){
    $curl = curl_init();
    curl_setopt($curl,CURLOPT_URL,$url);
    curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
    //如果用的是https,ssl安全验证
    curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,false);
    curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,false);
    $res =curl_exec($curl);
    curl_close($curl);
    return $res;
  }
  function get_php_file($filename){
    return trim(substr(file_get_contents($filename),15));
  }
  function set_php_file($filename,$content){
    $fp=fopen($filename,"w");
    fwrite($fp,"<?php exit();?>".$content);
    fclose($fp);
  }
  echo getAccessToken();
?>

感谢你能够认真阅读完这篇文章,希望小编分享小程序下获取access_token的案例内容对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,遇到问题就找亿速云,详细的解决方法等着你来学习!

推荐阅读:
  1. 微信公众平台怎么获取access_token
  2. 微信开发之如何获取access_token

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

access_token 小程序 ce

上一篇:怎么实现小程序动画

下一篇:微信小程序中渲染html内容的案例

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》