小程序後端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

	}
}

 

整理不易,轉發請附原創地址,謝謝!!!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章