微信公众号主动推送消息

  • 2,340
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------
error_reporting(E_ERROR | E_PARSE );


function httpRequest($url, $method="GET", $postfields = null, $headers = array(), $debug = false) {
    $method = strtoupper($method);
    $ci = curl_init();
    /* Curl settings */
    curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
    curl_setopt($ci, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0");
    curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 60); /* 在发起连接前等待的时间,如果设置为0,则无限等待 */
    curl_setopt($ci, CURLOPT_TIMEOUT, 7); /* 设置cURL允许执行的最长秒数 */
    curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
    switch ($method) {
        case "POST":
            curl_setopt($ci, CURLOPT_POST, true);
            if (!empty($postfields)) {
                $tmpdatastr = is_array($postfields) ? http_build_query($postfields) : $postfields;
                curl_setopt($ci, CURLOPT_POSTFIELDS, $tmpdatastr);
            }
            break;
        default:
            curl_setopt($ci, CURLOPT_CUSTOMREQUEST, $method); /* //设置请求方式 */
            break;
    }
    $ssl = preg_match('/^https:\/\//i',$url) ? TRUE : FALSE;
    curl_setopt($ci, CURLOPT_URL, $url);
    if($ssl){
        curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
        curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, FALSE); // 不从证书中检查SSL加密算法是否存在
    }
    //curl_setopt($ci, CURLOPT_HEADER, true); /*启用时会将头文件的信息作为数据流输出*/
    curl_setopt($ci, CURLOPT_FOLLOWLOCATION, FALSE);
    curl_setopt($ci, CURLOPT_MAXREDIRS, 2);/*指定最多的HTTP重定向的数量,这个选项是和CURLOPT_FOLLOWLOCATION一起使用的*/
    curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ci, CURLINFO_HEADER_OUT, true);
    /*curl_setopt($ci, CURLOPT_COOKIE, $Cookiestr); * *COOKIE带过去** */
    $response = curl_exec($ci);
    $requestinfo = curl_getinfo($ci);
    $http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
    if ($debug) {
        echo "=====post data======\r\n";
        var_dump($postfields);
        echo "=====info===== \r\n";
        print_r($requestinfo);
        echo "=====response=====\r\n";
        print_r($response);
    }
    curl_close($ci);
    return $response;
	//return array($http_code, $response,$requestinfo);
}
<?PHP
namespace app\common\jssdk;//文件夹名称func
use Think\Controller;

Class getjsapiticket extends Controller{
 /**
  * 专门用来检查微信接口返回值的。
  */
 private function requestAndCheck($url, $method = 'GET', $fields = [])
 {
     $return = httpRequest($url, $method, $fields);
     if ($return === false) {
        $this->error('http请求出错!');
         return false;
     }
     $wxdata = json_decode($return, true);
    //  $this->debug && $this->logDebugFile(['url' => $url,'fields' => $fields,'wxdata' => $wxdata]);
     if (isset($wxdata['errcode']) && $wxdata['errcode'] != 0) {
         if ($wxdata['errcode'] == 40001) {
             \think\Db::name('wx_user')->where('id', 1)->update(['web_expires' => 0]);//token错误
         }
         $this->error('错误码'.$wxdata['errcode']);
         return false;
     }

     if (strtoupper($method) === 'GET' && empty($wxdata)) {
       $this->error('微信http请求返回为空!');

         return false;
     }

     return $wxdata;
 }

public function nihao(){

 //  \think\Cache::connect($options);
 //  $jsapi = \think\Cache::get('acc');
 //  echo $jsapi;exit;
   $wechat = \think\Db::name('wx_user')->where('id',1)->find();
   $expire_time = $wechat['web_expires'];
   if($expire_time > time()){
      return $wechat['web_access_token'];
   }


   $appid = $wechat['appid'];
   $appsecret = $wechat['appsecret'];
   $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret;

   $return = $this->requestAndCheck($url, 'GET');
   if ($return === false) {
       return false;
   }
   $web_expires = time() + 7000; // 提前200秒过期
   \think\Db::name('wx_user')->where('id', 1)->update(['web_access_token'=>$return['access_token'], 'web_expires'=>$web_expires]);
   // $this->config['web_access_token'] = $return['access_token'];
   // $this->config['web_expires'] = $web_expires;
   return $return['access_token'];

}
/*
 * 向用户推送消息
 */
public function push_msg($openid,$content){
    $access_token = $this->nihao();

    $url ="https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$access_token;

    $post_arr = array(
                    'touser'=>$openid,
                    'msgtype'=>'text',
                    'text'=>array(
                    'content'=>$content,
                        )
                    );
    $post_str = json_encode($post_arr,JSON_UNESCAPED_UNICODE);
    $return =  $this->requestAndCheck($url,'POST',$post_str);
    $return = json_decode($return,true);

}

 

weinxin
我的微信
这是我的微信扫一扫
开拓者博主
  • 本文由 发表于 2018年4月5日16:35:24
  • 转载请务必保留本文链接:https://www.150643.com/499.html
匿名

发表评论

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: