微信开发服务器配置和access_token——2018年6月1日

2018年06月02日 10:47:39阅读数:928博客 / 沈斌的博客 / 微信公众号开发

微信开发服务器配置和access_token

ngrok.exe http 80

启动内网穿透,外网可以访问内网服务器。access_token 访问次数有限,需要用到cache.服务器配置时,首次接入成功

返回exit($echostr)

application\index\controller\Weixin.php

实例

<?php
namespace app\index\controller;
use think\Controller;
use think\facade\Cache;
class Weixin extends Controller
{
    public function __construct(){
        parent::__construct();
        $this->model=model('Weixin');
    }
    public function index()
    {
        $valid=$this->model->valid();

        if(!$valid){
            exit('sigature error');
        }

        exit(input('get.echostr'));
    }

    public function get_access_token($iscache=true){
        $cache_key='access_token';
        if(!$iscache){
            Cache::rm($cache_key);
        }
        $data=Cache::get($cache_key);
        if($data && $iscache){
            return $data;
        }


        $appid=config('app.APPID');
        $appsecret=config('app.APPSECRET');
        $url='https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$appsecret;
        $res=http_Get($url);
        // dump($res);
        $res=json_decode($res,true);
        // dump($res);
        if(!isset($res[$cache_key])){
            return false;
        }
        Cache::set($cache_key,$res['access_token'],($res['expires_in']-600));

        return $res[$cache_key];
    }
}

运行实例 »

点击 "运行实例" 按钮查看在线实例

application\index\model\Weixin.php

实例

<?php
namespace app\index\model;
use think\Model;
use think\Db;
use think\facace\Cache;

class Weixin extends model
{
    public function valid()
    {
        $signature=input('get.signature');
        // $signature='c5052967c11f8d7e59c3b4011407b94c697b1ceb';
        // var_dump($signature);
        $timestamp=input('get.timestamp');
        // $timestamp='1527896867';

        $nonce=input('get.nonce');
        // $nonce='3010175004';

        $echostr=input('get.echostr');
        // $echostr='9044276551450221539';
        $token=config('app.token');

        file_put_contents('d://data.txt','signature='.$signature.' timestmp='.$timestamp.' nonce='.$nonce.' echostr='.$echostr);
        $tmpArr=array($timestamp,$nonce,$token);
        sort($tmpArr,SORT_STRING);

        // dump($tmpArr);
        $tmpStr=implode($tmpArr);
        // echo $tmpStr;
        // $tmpStr=sha1($tmpStr);
        //
        if(sha1($tmpStr) != $signature){
            // exit('error');
            return false;
        }
        // 首次接入成功需要输出$echostr
        // exit($echostr);

        return true;
    }
}

运行实例 »

点击 "运行实例" 按钮查看在线实例


批改状态:合格

老师批语:

版权申明:本博文版权归博主所有,转载请注明地址!如有侵权、违法,请联系admin@php.cn举报处理!

全部评论

文明上网理性发言,请遵守新闻评论服务协议

条评论
  • 博主信息
    沈斌的博客
    博文
    56
    粉丝
    3
    评论
    1
    访问量
    42424
    积分:0
    P豆:417