博客列表 >微信公众号开发之签名验证、获取access_token--2018年5月31日

微信公众号开发之签名验证、获取access_token--2018年5月31日

笨鸟先飞
笨鸟先飞原创
2018年06月02日 22:52:391531浏览

Weixin.php_controller:


实例

<?php 
namespace app\index\controller;

use think\Controller;


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'));
	}

	//获取access_token
	public function get_access_token()
	{
	   echo  $this->model->access_token();
	}
}

运行实例 »

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




Weixin.php_model:


实例

<?php 
namespace app\index\model;

use think\Model;
use think\facade\Cache;

class Weixin extends Model 
{
	//签名校验
	public function valid()
	{
		$signature = input('get.signature');
		$timestamp = input('get.timestamp');
		$nonce     = input('get.nonce');
		$echostr   = input('gey.echostr');
        $token     = config('app.weixintoken');

        // file_put_contents('filename', $data)第一个参数:保存文件的URL,第二个参数:保存的数据

        $tmpArr = array($timestamp,$nonce,$token);
        sort($tmpArr,SORT_STRING);
        $tmpStr = implode($tmpArr);
        $sign = sha1($tmpStr);

        if($sign != $signature){
        	return falae;
        }
        return true;
	}
    
    //获取access_token
	public function access_token($iscache=true)//参数默认缓存
	{
		$cache_key = 'access_token';
		//如果不缓存就删除
        if(!$iscache){
        	Cache::rm($cache_key);
        }
		$access_token = Cache::get($cache_key);//获取缓存的数据
		if($access_token && $iscache){
			return $access_token;
		}
		$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);//获取微信那边的json数据
		$res = json_decode($res,true);//解析微信那边发送过来的json数据
		//如果解析出来没有access_token就返回false
		if(!isset($res['access_token'])){
			return false;
		}
		Cache::set($cache_key,$res['access_token'],$res['expires_in']-300);//缓存 (key , 值,缓存时间)默认是永久
        return $res['access_token'];
	}
}

运行实例 »

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


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