>  기사  >  백엔드 개발  >  WeChat 공개 계정 development_php 기술을 위한 WeChat 공개 플랫폼 메시지 응답 클래스 예시

WeChat 공개 계정 development_php 기술을 위한 WeChat 공개 플랫폼 메시지 응답 클래스 예시

WBOY
WBOY원래의
2016-05-16 20:31:49950검색

이 기사의 예에서는 WeChat 공개 계정에서 개발된 WeChat 공개 플랫폼 메시지 응답 클래스에 대해 설명합니다. 참고할 수 있도록 모든 사람과 공유하세요. 세부 내용은 다음과 같습니다.

인터넷에서 위챗 공개 계정 개발 코드를 많이 봤는데, 사실 모두 같은 의미인데 공식 데모 파일을 참고해서 수정한 것입니다.

코드 복사 코드는 다음과 같습니다.

/**
* 위챗 공개 플랫폼 메시지 답장 수업
*
*
​*/
클래스 BBCweixin{
 
 비공개 $APPID="******";
 비공개 $APPSECRET="******";
 /*
  *文本消息回复
  *@param 배열 객체
  *@param 문자열 내용
  *@반환 문자열
  */
 공개 함수 resText($object,$content,$flag=0){
  $xmlText="
                 
                 
                  %s
                 
                  <콘텐츠>
                  %d
                 
";
     $resultStr=sprintf($xmlText,$object->FromUserName,$object->ToUserName,time(),$content,$flag);
  echo $resultStr;exit();
 }
 /*
  *사진消息回复
  *@param 배열 객체
  *@param 문자열 URL
  *@반환 문자열
  */
 공개 함수 resImage($object,$media_id){
  $xmlImage="";
  $xmlImage.="";
  $xmlImage.="";
  $xmlImage.="%s";
  $xmlImage.="";
  $xmlImage.="";
  $xmlImage.="
";
  $resultStr=sprintf($xmlImage,$object->FromUserName,$object->ToUserName,time(),$media_id);
  echo $resultStr;exit();
 }
 /*
  *图文消息回复
  *@param 배열 객체
  *@param 배열 newsData 2维数组 必须包含[제목][설명][PicUrl][Url]字段
  *@반환 문자열
  */
 공개 함수 resNews($object,$newsData=array()){
     $CreateTime=시간();
     $FuncFlag=0;
     $newTplHeader="
        FromUserName}]]>
        ToUserName}]]>
        {$CreateTime}
       
        <콘텐츠>
        %s";
     $newTplItem="<항목>
      <제목>
      <설명>
     
     
      ";
     $newTplFoot="

      %s
";
$Content='';
$itemsCount=count($newsData);
$itemsCount=$itemsCount<10?$itemsCount:10;//WeChat 공개 플랫폼은 사진과 텍스트를 포함하여 한 번에 최대 10개의 메시지에 답장할 수 있습니다
If($itemsCount){
foreach($newsData as $key=>$item){
If($key<=9){
$Content.=sprintf($newTplItem,$item['제목'],$item['설명'],$item['PicUrl'],$item['Url']);
}
}
}
$header=sprintf($newTplHeader,0,$itemsCount);
$footer=sprintf($newTplFoot,$FuncFlag);
echo $header.$Content.$footer;exit();
}

/*
*음악 메시지 답장
*@param 배열 객체
*@param 배열 [제목][설명][MusicUrl][HQMusicUrl] 필드를 포함하는 musicContent 2차원 배열
*@반환 문자열
*/
공개 함수 resMusic($object,$musicContent=array()){
$xmlMusic="
~ > /사용자 이름>
~                                                                                 
~ ~   %s
~ > ;
~ <제목>
~ > >
~ > %s]]>
~ | HQMusicUrl>
~ ~        if(empty($musicContent[0]['HQMusicUrl'])){
$musicContent[0]['HQMusicUrl']=$musicContent[0]['MusicUrl'];
}
$resultStr=sprintf($xmlMusic,$object->FromUserName,$object->ToUserName,time(),$musicContent[0]['Title'],$musicContent[0]['Description'],$musicContent [0]['MusicUrl'],$musicContent[0]['HQMusicUrl']);
echo $resultStr;exit();
}
/*
*멀티미디어 파일 업로드를 위한 인터페이스
*@param
*@param 배열 mediaArr 파일 이름, 파일 길이, 콘텐츠 유형
*@반품대상
*/
공개 함수 uploadMedia($accessToken,$type='image',$mediaArr){
$url="http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=".$accessToken."&type=".$type;
$doPost=self::curlPost($mediaArr,$url);
$doPost 반환
}
/*
*GPS, Google 좌표를 바이두 좌표로 변환
*@param lnt
*@param lat
*@return 배열
*/
공개 함수 mapApi($lng,$lat,$type){
$map=배열();
if($type=='gps'){
$url="http://map.yanue.net/gpsApi.php?lat=".$lat."&lng=".$lng;
$res=json_decode(file_get_contents($url));
$map['lng']=$res->baidu->lng;
$map['lat']=$res->baidu->lat;
}
if($type=='google'){
$url="http://api.map.baidu.com/ag/coord/convert?from=2&to=4&mode=1&x=".$lng."&y=".$lat;
$res=json_decode(file_get_contents($url));
$map['lng']=base64_decode($res[0]->x);
   $map['lat']=base64_decode($res[0]->y);
  }
  $map 반환;
 }
 
 /**************************************************** * **********
*
* 특정 함수를 사용하여 배열의 모든 요소를 ​​처리합니다
* @param string &$array 처리할 문자열
* @param string $function 실행할 함수
* @return boolean $apply_to_keys_ also 키에도 적용할지 여부
* @접속공개
*
************************************************** * ***********/
 공용 함수 arrayRecursive(&$array, $function, $apply_to_keys_ also = false)
 {
  정적 $recursive_counter = 0;
  if ( $recursive_counter > 1000) {
   die('심층 재귀 공격 가능');
  }
  foreach($array as $key => $value) {
   if (is_array($value)) {
    self::arrayRecursive($array[$key], $function, $apply_to_keys_ also);
   } 그 밖의 {
    $array[$key] = $function($value);
   }
 
   if ($apply_to_keys_ also && is_string($key)) {
    $new_key = $function($key);
    if ($new_key != $key) {
     $array[$new_key] = $array[$key];
     unset($array[$key]);
    }
   }
  }
  $recursive_counter--;
 }
 
 /**************************************************** * **********
*
* 배열을 JSON 문자열로 변환(중국어 호환)
* @param array $array 변환할 배열
* @return string 변환된 json 문자열
* @접속공개
*
************************************************** * ***********/
 공개 함수 JSON($array) {
  self::arrayRecursive($array, 'urlencode', true);
  $json = json_encode($array);
  urldecode($json)를 반환합니다.
 }
 /*
  *创建菜单
  *
  */
 공개 함수 creatMenu($shop_id,$data){
  $jsonArray=self::JSON($data);
  $AccessToken=self::accessToken($weiXin[0]['key'],$weiXin[0]['secret']);
  $MENU_URL="https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$AccessToken;
  return self::curlPost($jsonArray,$MENU_URL);
 }
 /*
  *客服消息回复
  *@param 배열 jsonArray 배열 {"touser":"OPENID","msgtype":"text","text":{"content":"Hello World"}}
  *@반환 문자열
  */
 
  공용 함수 customService($jsonArray,$hash){
  if(비어 있음($jsonArray)){
   거짓을 반환;
  }
  $db=M();
  $sql="select * from bbc_wechats where hash='".$hash."'";
  $weChast=$db->query($sql);
  $AccessToken=self::accessToken($weChast[0]['key'],$weChast[0]['secret']);
  $TokenUrl="https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$AccessToken;
     $CustomRes=self::curlPost($jsonArray,$TokenUrl);
  $CustomRes 반환;
  }
  /*
 
   *접속_토큰
   *@return objectStr
   */
  공용 함수 accessToken($appid,$secret){
   $access_token=BBCcache::getCache('accesstoken'.$appid);
   if($access_token){
    $AccessTokenRet=$access_token;
   }그밖에{
    $TookenUrl="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}";
    $AccessTokenRes=@file_get_contents($TookenUrl);
    $AccessToken=json_decode($AccessTokenRes);
    $AccessTokenRet=$AccessToken->access_token;
    BBCcache::setCache('accesstoken'.$appid,$AccessToken->access_token,3600);
   }
   $AccessTokenRet 반환;
  }
  /*
   *向远程接口POST数据
   *@data 배열 {"touser":"OPENID","msgtype":"text","text":{"content":"Hello World"}}
   *@return objectArray
   */
  공개 함수 컬포스트($data,$url){
    $ch = 컬_init();
 
   컬_setopt($ch, CURLOPT_URL, $url);
   컬_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
   컬_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
   컬_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
   cur_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (호환; MSIE 5.01; Windows NT 5.0)');
   컬_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
   컬_setopt($ch, CURLOPT_AUTOREFERER, 1);
   컬_setopt($ch, CURLOPT_POSTFIELDS, $data);
   컬_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 
   $info = 컬_exec($ch);
 
   if (curl_errno($ch)) {
    echo 'Errno'.curl_error($ch);
   }
 
   컬_닫기($ch);
   return json_decode($info);
  }
 //根据经纬島计算距离 와 方向
 함수 getRadian($d){
  $d * M_PI / 180을 반환합니다.
 }
 
 함수 getDistance($lat1, $lng1, $lat2, $lng2){
  $EARTH_RADIUS=6378.137;//지역정보
  $lat1 =getRadian($lat1);
  $lat2 = getRadian($lat2);
 
  $a = $lat1 - $lat2;
  $b = getRadian($lng1) - getRadian($lng2);
 
  $v = 2 * asin(sqrt(pow(sin($a/2),2) cos($lat1) * cos($lat2) * pow(sin($b/2),2)));
 
  $v = 라운드($EARTH_RADIUS * $v * 10000) / 10000;
 
  $v 반환;
 }
}
?>

希望本文所述对大家基于PHP의 微信公众号开发有所帮助。

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.