如何在thinkPHP3.2项目中接入微信

发布时间:2021-02-05 16:19:59 作者:Leah
来源:亿速云 阅读:201

这篇文章将为大家详细讲解有关如何在thinkPHP3.2项目中接入微信,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

1.在con.fig文件里面配置TOKEN,APPID,APPSECRET值

2.控制器WeixinController代码:

<?php
/**
 * 微信父类控制器
 * @author Songle
 *
 */
namespace Weixin\Controller;
use Think\Controller;
class WeixinController extends Controller {
  private $last_time=null;
  private $appid=null;
  private $appsecret=null;
  function __construct(){
    parent::__construct();
    $token=C('TOKEN');
    $this->appid=C('APPID');
    $this->appsecret=C('APPSECRET');
    //获取微信服务器GET请求的4个参数
    $signature = I('signature');
    $timestamp = I('timestamp');
    $nonce = I('nonce');
    $echostr = I('echostr');
    if (! empty ( $echostr) && ! empty ( $signature ) && ! empty ($nonce )) {
      //定义一个数组,存储其中3个参数,分别是timestamp,nonce和token
      $tempArr = array($nonce,$timestamp,$token);
      //进行排序
      sort($tempArr,SORT_STRING);
      //将数组转换成字符串
      $tmpStr = implode($tempArr);
      //进行sha1加密算法
      $tmpStr = sha1($tmpStr);
      //判断请求是否来自微信服务器,对比$tmpStr和$signature
      if($tmpStr == $signature)
      {
        echo $echostr;
      }
      exit();
    }
  }
  /**
   * 获取tooken值
   */
  public function getTooken(){
    $this->last_time = 1448012924;
    $access_token = "填写上一次的token值"; //需要替换成自己的
    if(time() > ($this->last_time + 7200))
    {
      //GET请求的地址
      $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appid}&secret={$this->appsecret}";
      $access_token_Arr = $this->https_request($url);
      $this->last_time = time();
      return $access_token_Arr['access_token'];
    }
    return $access_token;
  }
  //https请求(支持GET和POST)
  public function https_request($url,$data = null)
  {
    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
    if(!empty($data))
    {
      curl_setopt($ch,CURLOPT_POST,1); //模拟POST
      curl_setopt($ch,CURLOPT_POSTFIELDS,$data); //POST内容
    }
    $outopt = curl_exec($ch);
    curl_close($ch);
    $outopt = json_decode($outopt,true);
    return $outopt;
  }
}

关于如何在thinkPHP3.2项目中接入微信就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

推荐阅读:
  1. 如何在python3项目中中eval函数
  2. vue项目怎么引入微信sdk接口

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

thinkphp

上一篇:如何在php中使用数组函数对现关联表进行编辑

下一篇:使用Codeigniter框架怎么实现一个student信息系统站点动态发布功能

相关阅读

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

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