小程序后端PHP发送模板消息

这里是我分享的小程序后端php发送模板消息的接口,其中有许多要注意的地方. 

注意!注意!注意!重要的事情说三遍!获取access_token,是需要了解的

access_token 是全局唯一接口调用凭据,开发者调用各接口时都需使用 access_token,请妥善保存。access_token 的存储至少要保留512个字符空间。access_token 的有效期目前为2个小时,需定时刷新,重复获取将导致上次获取的 access_token 失效。

/**
     * 发送模板消息
     */
    public function TemplateMessage()
    {
        // Initialize Variable
        $pid = I('goodid');
        $touser = I('touser');//接收者openid
        $template_id = I('template_id');//模板id
        $page = I('page');//点击跳转页面,可带参数
        $form_id = I('form_id');//formId
        $keyword1 = I('keyword1');//商品名
        $keyword2 = I('keyword2');//商品原价
        $keyword3 = I('keyword3');//支付金额
        $keyword4 = I('keyword4');//温馨提示

        //获取access_token
        $this->miniapp_init();
        $sAccessToken = $this->AccessToken();

        // 模板消息内容
        $arrTemplateValue = [
            "keyword1" => ["value"=>$keyword1],
            "keyword2" => ["value"=>$keyword2],
            "keyword3" => ["value"=>$keyword3],
            "keyword4" => ["value"=>$keyword4],
        ];

        $sUrl    = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token='.$sAccessToken;
        $arrList = [
            'touser'      => $touser,
            'template_id' => $template_id,
            'page'        => $page,
            'form_id'     => $form_id,
            'data'        => $arrTemplateValue,
        ];

        $result = $this->https_curl_json($sUrl, $arrList, 'json');

        
        echo json_encode($result);

    }

    /**
     * 发送json格式的数据,到api接口 -xzz0704
     * @param $url
     * @param $data
     * @param $type
     * @return mixed
     */
    function https_curl_json($url, $data, $type)
    {
        if ($type == 'json') {
            $headers = array("Content-type: application/json;charset=UTF-8", "Accept: application/json", "Cache-Control: no-cache", "Pragma: no-cache");
            $data = json_encode($data);
        }
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        $output = curl_exec($curl);
        if (curl_errno($curl)) {
            echo 'Errno' . curl_error($curl);//捕抓异常
        }
        curl_close($curl);
        return $output;

    }// END https_curl_json

获取access_token,配置信息请自行配置,这里就不做过多解释

class PublicAction extends Action
{

     /*载入小程序接口配置*/
    public function miniapp_init() {
         import ( 'miniapp', APP_PATH . 'Common', '.class.php' );
         $config = M("admin")->where(array("id"=>1))->find();//我这里的appid和appsecret是存储数据库的
         $options = array(
                'appid' => $config ["appid"], 
                'appsecret' => $config ["appsecret"],
         );
        $weObj = new Miniapp ($options);
        return $weObj;
    }

     /*获取小程序accesstoken,统一缓存统一调用*/
     public function AccessToken()
     {
         $weObj     = $this->miniapp_init();
         $AccessToken = $weObj -> checkAuth();
         //dump($AccessToken);exit;
         return $AccessToken;
     }
}

这里是miniapp.class.php

<?php

class Miniapp {

	private $appid;

	private $appsecret;

	private $access_token;

	public $debug =  false;

	public $errCode = 40001;

	public $errMsg = "no access";

	public $logcallback;

	private $cachedir = '';

	public function __construct($options)

	{
		$this->appid = isset($options['appid'])?$options['appid']:'';

		$this->appsecret = isset($options['appsecret'])?$options['appsecret']:'';

		$this->debug = isset($options['debug'])?$options['debug']:false;

        $this->cachedir = isset($options['cachedir']) ? dirname($options['cachedir'].'/.cache') . '/' : 'cache/';

        if ($this->cachedir) $this->checkDir($this->cachedir);		

	}

	/**

	 * GET 请求

	 * @param string $url

	 */

	private function http_get($url){

		$oCurl = curl_init();

		if(stripos($url,"https://")!==FALSE){

			curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);

			curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);

			curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1

		}

		curl_setopt($oCurl, CURLOPT_URL, $url);

		curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );

		$sContent = curl_exec($oCurl);

		$aStatus = curl_getinfo($oCurl);

		curl_close($oCurl);

		if(intval($aStatus["http_code"])==200){

			return $sContent;

		}else{

			return false;

		}

	}



	/**

	 * POST 请求

	 * @param string $url

	 * @param array $param

	 * @param boolean $post_file 是否文件上传

	 * @return string content

	 */

	private function http_post($url,$param,$post_file=false){

		$oCurl = curl_init();

		if(stripos($url,"https://")!==FALSE){

			curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);

			curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);

			curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1

		}

		if (is_string($param) || $post_file) {

			$strPOST = $param;

		} else {

			$aPOST = array();

			foreach($param as $key=>$val){

				$aPOST[] = $key."=".urlencode($val);

			}

			$strPOST =  join("&", $aPOST);

		}

		curl_setopt($oCurl, CURLOPT_URL, $url);

		curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );

		curl_setopt($oCurl, CURLOPT_POST,true);

		curl_setopt($oCurl, CURLOPT_POSTFIELDS,$strPOST);

		$sContent = curl_exec($oCurl);

		$aStatus = curl_getinfo($oCurl);

		curl_close($oCurl);

		if(intval($aStatus["http_code"])==200){

			return $sContent;

		}else{

			return false;

		}

	}



	/**

	 * 设置缓存,按需重载

	 * @param string $cachename

	 * @param mixed $value

	 * @param int $expired

	 * @return boolean

	 */

	protected function setCache($cachename,$value,$expired=0){

        $file = $this->cachedir . $cachename . '.cache';

        $data = array(

                'value' => $value,

                'expired' => $expired ? time() + $expired : 0

        );

        return file_put_contents( $file, serialize($data) ) ? true : false;

	}



	/**

	 * 获取缓存,按需重载

	 * @param string $cachename

	 * @return mixed

	 */

	protected function getCache($cachename){

        $file = $this->cachedir . $cachename . '.cache';

        if (!is_file($file)) {

           return false;

        }else{

			$data = unserialize(file_get_contents( $file ));

			if (!is_array($data) || !isset($data['value']) || (!empty($data['value']) && $data['expired']<time())) {

				@unlink($file);

				return false;

			}else{

				return $data['value'];

			}

		}

	}



	/**

	 * 清除缓存,按需重载

	 * @param string $cachename

	 * @return boolean

	 */

	protected function removeCache($cachename){

        $file = $this->cachedir . $cachename . '.cache';

        if ( is_file($file) ) {

            @unlink($file);

        }

        return true;

	}

	

    protected function checkDir($dir, $mode=0777) {

        if (!$dir)  return false;

        if(!is_dir($dir)) {

            if (!file_exists($dir) && @mkdir($dir, $mode, true))

                return true;

            return false;

        }

        return true;

    }

	/**

	 * 获取access_token

	 * @param string $appid 如在类初始化时已提供,则可为空

	 * @param string $appsecret 如在类初始化时已提供,则可为空

	 * @param string $token 手动指定access_token,非必要情况不建议用

	 */

	public function checkAuth($appid='',$appsecret='',$token=''){  //

		if (!$appid || !$appsecret) {
			$appid = $this->appid;
			$appsecret = $this->appsecret;
		}

		$authname = 'miniapp_access_token'.$appid;

		$rs = $this->getCache($authname);

		if (!empty($rs)){
			$this->access_token = $rs;
			return $rs;
		}

		else{
			$result = $this->http_get('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$appsecret);

			if ($result)
			{

				$json = json_decode($result,true);

				if (!$json || isset($json['errcode'])) {

					$this->errCode = $json['errcode'];

					$this->errMsg = $json['errmsg'];

					return false;

				}

				$this->access_token = $json['access_token'];
				$expire = $json['expires_in'] ? intval($json['expires_in'])-200 : 7000;
				$this->setCache($authname,$this->access_token,$expire);
				return $this->access_token;
			}
		}
	}



	/**

	 * 删除验证数据

	 * @param string $appid

	 */

	public function resetAuth($appid=''){

		if (!$appid) $appid = $this->appid;

		$this->access_token = '';

		$authname = 'miniapp_access_token'.$appid;

		$this->removeCache($authname);

		return true;

	}




	/**

	 * 微信api不支持中文转义的json结构

	 * @param array $arr

	 */

	static function json_encode($arr) {

		$parts = array ();

		$is_list = false;

		//Find out if the given array is a numerical array

		$keys = array_keys ( $arr );

		$max_length = count ( $arr ) - 1;

		if (($keys [0] === 0) && ($keys [$max_length] === $max_length )) { //See if the first key is 0 and last key is length - 1

			$is_list = true;

			for($i = 0; $i < count ( $keys ); $i ++) { //See if each key correspondes to its position

				if ($i != $keys [$i]) { //A key fails at position check.

					$is_list = false; //It is an associative array.

					break;

				}

			}

		}

		foreach ( $arr as $key => $value ) {

			if (is_array ( $value )) { //Custom handling for arrays

				if ($is_list)

					$parts [] = self::json_encode ( $value ); /* :RECURSION: */

				else

					$parts [] = '"' . $key . '":' . self::json_encode ( $value ); /* :RECURSION: */

			} else {

				$str = '';

				if (! $is_list)

					$str = '"' . $key . '":';

				//Custom handling for multiple data types

				if (!is_string ( $value ) && is_numeric ( $value ) && $value<2000000000)

					$str .= $value; //Numbers

				elseif ($value === false)

				$str .= 'false'; //The booleans

				elseif ($value === true)

				$str .= 'true';

				else

					$str .= '"' . addslashes ( $value ) . '"'; //All other things

				// :TODO: Is there any more datatype we should be in the lookout for? (Object?)

				$parts [] = $str;

			}

		}

		$json = implode ( ',', $parts );

		if ($is_list)

			return '[' . $json . ']'; //Return numerical JSON

		return '{' . $json . '}'; //Return associative JSON

	}
}

 

整理不易,转发请附原创地址,谢谢!!!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值