微信公众号开发【一】 菜单获取与设置

首先一点点准备工作,

本地开发时,需要将本地ip 写攻到白名单中,不然无法获取token.

知道自己的appid 和appSecret

微信的助手类。提供获取token 向api 请求等功能封装。用法示例如下。

//获取token 值   
$this->access_token = WxHelper::getAccessToken(0 , $this->app_id , $this->secret );

//向api 请求。
 $url = "https://sz.api.weixin.qq.com/cgi-bin/menu/create?access_token=" .$token;
 $response = WxHelper::accessapi($url,'POST',$xml, 1, $this->app_id, $this->secret);

/**
 * Class WHelper
 * @description 一些基础微信用ifc
 */
class WHelper extends CComponent{


    //获取token
    public static function getAccessToken($update = 0, $appid='', $secret='')
    {
        if (!$appid){
            $appid = WAPP_ID;
        }
        if (!$secret){
            $secret = APP_SECRET;
        }
        $time = time();
        $token_file = COMMON_FOLDER.'/logs/'.$appid.'.token';
        if(is_file($token_file)){
            $token = file_get_contents($token_file);
            $obj = json_decode($token);
            if ($obj->expires_in < $time || $update==1) {
                $obj=self::getToken1($time, $appid, $secret);
                if(!$obj){return false;}
                file_put_contents($token_file, json_encode($obj));

            }
        }else{
            $obj=self::getToken1($time, $appid, $secret);
            if(!$obj){return false;}
            file_put_contents($token_file, json_encode($obj),777);
        }
        return $obj->access_token;
    }

    private  static function getToken1($time, $appid, $secret){
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . $secret;
        $obj=self::accessapi($url,'POST', '', 1, $appid, $secret);

        if (!isset($obj->expires_in)) {
            Yii::log( "getToken_error". print_r($obj,1), CLogger::LEVEL_ERROR ,'log_error'); //异常时,日志记录。
            return false;
        }
        $obj->expires_in = $time + $obj->expires_in - 30;
        return $obj;
    }


    static function accessapi($url,$method='POST',$jsonData='',$repeat=1, $appid='', $secret=''){
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $tmpInfo = curl_exec($ch);

        if (curl_errno($ch)) {
            echo 'Errno:' . curl_error($ch);
            exit;
        }
        curl_close($ch);
        $obj=json_decode($tmpInfo);
        if(!is_object($obj)){
            return $tmpInfo;
        }
        if(isset($obj->errcode)){
            if($obj->errcode == 40001 && $repeat==1){
                $arr=parse_url($url);
                $arr1=explode('&',$arr['query']);
                $query='';
                if(count($arr1)>0 && $arr['query']){
                    $i=0;
                    foreach($arr1 as $arr2){
                        $arr3=explode("=",$arr2);
                        if($arr3[0]=='access_token'){
                            $token=self::getAccessToken(1, $appid, $secret);
                            $arr2=$arr3[0].'='.$token;
                        }
                        if($i>0){
                            $query.='&'.$arr2;
                        }else{
                            $query.=$arr2;
                        }
                        $i++;
                    }
                }
                $url=$arr['scheme'].'://'.$arr['host'].$arr['path'].'?'.$query;
                return self::accessapi($url,$method,$jsonData,0);
            }
        }
        return $obj;
    }


}


业务处理类。

<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/6
 * Time: 15:06
 */


class WHandle extends CComponent{

    public $app_id;
    public $secret;
    public $access_token;

    /**
     * @param $app_id
     * @param $secret
     * @description 构建函数,创建handle 时,同时拉取access_token
     */
    public function __construct($app_id , $secret){  //
        $this->app_id = $app_id;
        $this->secret = $secret;
        $this->access_token = WHelper::getAccessToken(0 , $this->app_id , $this->secret );
    }



    /**
     * @return string json 字符串
     */
    public function getMenu(){  //
        $token =  $this->access_token;
        $url = "https://sz.api.weixin.qq.com/cgi-bin/menu/get?access_token=" . $token;
        $obj = WxHelper::accessapi($url,'GET','', 1, $this->app_id, $this->secret);
        return $obj;
     //   return json_encode($obj);
    }

    /**
     * @param $json
     * @return string json 字符串
     */
    public function setMenu( $json){
        $token =  $this->access_token;
        $url = "https://sz.api.weixin.qq.com/cgi-bin/menu/create?access_token=" .$token;
        return WxHelper::accessapi($url,'POST',$json, 1, $this->app_id, $this->secret);
    }

}

调用示例: 获取菜单数据

//获取菜单配置。  
$app_id = "xxx";
$app_secret = "yyy";

        $handle = new WHandle($app_id , $app_secret);
        $menus = $handle->getMenu();   //返回一个json 对象。
        print_r( $menus );x结


调用示例: 设置菜单数据

//获取菜单配置。  
$app_id = "xxx";
$app_secret = "yyy";
$handle = new WHandle($app_id , $app_secret);
$data =array("button"=> array( array( "type"=>"click" , "name" => "事件1" , "key" => "123456" ), array( "type"=>"click" , "name" => "事件2" , "key" => "123456" ), array( "name"=>"最新活动", "sub_button" => array( array("type"=> "view" , "name"=>"百度" , "url"=> "http://www.baidu.com"), array("type"=> "view" , "name"=>"凤凰网" , "url"=> "http://ifeng.com"), array("type"=> "view" , "name"=>"qq" , "url"=> "http://www.qq.com"), array("type"=> "view" , "name"=>"网易" , "url"=> "http://163.com"), ) ) )); // echo json_encode( $data , JSON_UNESCAPED_UNICODE ); $r = $handle->setMenu(json_encode($data , JSON_UNESCAPED_UNICODE)); pr( $r );


得到的返回。



这样,基础的读和写就ok了,存入数据库中,再做个crud 就可以包装为服务供运营小伙伴使用了。


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值