博客列表 >写出对接微信服务器时 需要的数字签名程序,即生成signature-2018年5月31日

写出对接微信服务器时 需要的数字签名程序,即生成signature-2018年5月31日

往昔流逝的博客
往昔流逝的博客原创
2018年06月01日 14:38:101215浏览
  1. 首先使用ngrok:

    在本地项目 目录下输入:

    把ngrok.exe放在项目根目录下,然后:
    1.ngrok authtoken 验证码(如果你关闭了ngrok,这个验证码就会变)
    2.ngrok http 80

  2. 然后在项目里写入连接代码:

    在模型里的代码:

    <?php
    namespace app\index\model;
    use think\Model;
    use think\facade\Cache;
    use think\Db;
    class Weixin extends Model{
       // 签名校验
       public function valid(){
           $signature = input('get.signature');
           $timestamp = input('get.timestamp');
           $nonce = input('get.nonce');
           $token = config('app.weixintoken');

           $tmpArr = array($timestamp,$nonce,$token);
           sort($tmpArr, SORT_STRING);
           $str = implode($tmpArr);
           if(sha1($str) != $signature){
               return false;
           }
           return true;
       }

      public function access_token($iscache = true){
         $key = 'access_token';
           if(!$iscache){
               Cache::rm($key);
           }
         $data = Cache::get($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);
          $res = json_decode($res,true);
          if(!isset($res['access_token'])){
             return false;
          }
          Cache::set($key,$res['access_token'],($res['expires_in']-100));
          return $res['access_token'];
      }
    }

    在控制器中的代码:

    <?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('signature error');
           }
           exit(input('get.echostr'));
       }
    }

  3. 然后再微信里进行配置:

    先在基本配置里进行配置:

    捕获.PNG

    然后在开发者工具里选择公众平台测试账号里配置:

    捕获1.PNG

上一条:假链接下一条:HTML的base标签小知识
声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议