首頁 微信小程式 小程式開發 小程式下如何取得access_token(程式碼範例)

小程式下如何取得access_token(程式碼範例)

Oct 29, 2018 pm 04:44 PM

這篇文章帶給大家的內容是關於小程式下如何取得access_token(程式碼範例),有一定的參考價值,有需要的朋友可以參考一下,希望對你有幫助。



<button bindtap="token">获取token</button>
登入後複製
// pages/token/token.js
Page({
  data: {

  },
  token:function(){
    wx.request({
      url: &#39;xxxx&#39;,
      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(程式碼範例)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)