PHP 微信接口封装

这篇博客适合初学者,介绍了PHP对接微信接口的封装过程,帮助理解微信开发的基础概念。
摘要由CSDN通过智能技术生成

看看就好、初学者看看应该能懂个大概,会对微信开发有一个大概的概念

<?php
/**
 * Created by PhpStorm.
 * User: E450
 * Date: 2017/12/5
 * Time: 10:36
 */
namespace app\common\api\wechat;
use Couchbase\Exception;
use think\facade\Log;
use app\common\model\Account;
use app\common\model\Msg;
use think\facade\Cookie;


class Wechat{
    //微信openid
    private $openid;
    //微信appid
    private $appid;
    //微信appsecret
    private $appsecret;
    //微信accesstoken
    public $accessToken;
    //微信token
    private $token;
    //微信返回数据
    private $response;
    //账号id
    public $account_id;

    //构造函数常用数据初始化
    public function __construct($data = null)
    {
        $this->account_id = input('account_id');
        //数据初始化
        if($data != null){
            $this->token     = $data['token'];
            $this->appid     = $data['appid'];
            $this->appsecret = $data['app_secret'];
            //获取accessToken
            $this->accessToken = $this->getAccessToken();

        }
    }

    private function getAccessToken()
    {
//        Cookie::delete('AccessToken');exit;

        try{
            if(Cookie::get('AccessToken') != null){

                return Cookie::get('AccessToken');

            }else{
                $appid = $this->appid;
                $appsecret = $this->appsecret;

                $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . '&secret=' . $appsecret;
                $res = json_decode($this->https_request($url), true);

                if(!$res['access_token']){
                    throw new \Exception($res);
                }
                //保存token 避免接口上限
                Cookie::set('AccessToken',$res['access_token'],5000);
                return $res['access_token'];
            }
        }catch (\Exception $e){
            var_dump($e->getMessage());
        }


    }

    public function vaild()
    {
        if ($this->check()) {
            echo $_GET['echostr'];
            exit;
        }
    }

    public function check()
    {
        $signature = $_GET['signature'];
        $timestamp = $_GET['timestamp'];
        $nonce = $_GET['nonce'];
        //获取token
        $token = Account::get($this->account_id);
        $token =$token->token;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);
        if ($tmpStr == $signature) {
            return true;
        } else {
            return false;
        }
    }



    public function send()
    {
        $msgxml = file_get_contents("php://input");

        if (!empty($msgxml)) {
            $msgObj = simplexml_load_string($msgxml, 'SimpleXMLElement', LIBXML_NOCDATA);
            $this->openid = $msgObj->FromUserName;
            $type = $msgObj->MsgType;
            $this->response = $msgObj;
            $content ='';
            switch ($type) {
                case "event":
                    $content = $this->event();
                    break;
                case "text":
                    $content = $this->text($this->account_id);
                    break;
                case "image":
                    $content = $this->image();
                    break;
                case "voice":
                    $content = '我是语音消息';
                    break;
                case "video":
                    $content = '我是视屏消息';
                    break;
                case "shortvideo":
                    $content = "我是短视频";
                    break;
                case "link":
                    $content = "我是链接消息";
                    break;
            }
            echo $content;
            exit;
        }
    }

    //事件处理函数
    public function event()
    {
        $obj = $this->response;
        $fromusername = $obj->FromUserName;
        $tousername = $obj->ToUserName;
        $time = time();
        $content = '';
        switch ($obj->Event){
            case 'subscribe':
              $this->subscribe();
                break;
            case 'unsubscribe':
                $content = '成功取消关注';
                break;
            case 'LOCATION':
                $content = '今天天气不错!';
                break;
            case 'CLICK':
                $content = '今天天气不错!';
                break;
            default:
                $content = '··········';
        }

        $tpl = "<xml>
                        <ToUserName><![CDATA[%s]]></ToUserName>
                        <FromUserName><![CDATA[%s]]></FromUserName>
                        <CreateTime>%s</CreateTime>
                        <MsgType><![CDATA[text]]></MsgType>
                        <Content><![CDATA[%s]]></Content>
                    </xml>";
        $msg = sprintf($tpl, $fromusername, $tousername, $time, $content);
        return $msg;
    }

    public function subscribe(){
        $msg = new Msg();

        $res = $msg->where([['account_id','eq',$this->account_id],'msg_type','eq',1])->find();
        if(!$res){
            $content = '谢谢关注';
        }else{

            //文字消息处理
            if(!in_array($res['type'],array(2,3,4))){
                echo $this->text($res['content']);
            }else{
                //媒体类信息处理
                switch ($res['type']){
                    case 1:
                        $content =  $res['content'];break;
                    case 2:
                        $content =  '图文';break;
                    case 3:
                        $content = "图片";break;
                    case 4;
                        $content = "语音";break;
                    default:
                        $content = '··········';
                }
                echo $this->text('功能暂未开放');
            }
        }

    }

    /**
     * 文本处理函数
     * @parm $account_id  账户id
     */
    public function text($account_id)
    {
        $msg = new Msg();
        $obj = $this->response;
        $fromusername = $obj->FromUserName;
        $tousername = $obj->ToUserName;
        $time = time();
        $res = $msg->where([['account_id','eq',$account_id],['rec_type','eq',2]])->find();

        switch ($res['msg_type']){
            case 1:
              $tpl = "<xml>
                        <ToUserName><![CDATA[%s]]></ToUserName>
                        <FromUserName><![CDATA[%s]]></FromUserName>
                        <CreateTime>%s</CreateTime>
                        <MsgType><![CDATA[text]]></MsgType>
                        <Content><![CDATA[%s]]></Content>
                    </xml>";
                $msg = sprintf($tpl, $fromusername, $tousername, $time, $res['content']);
                return $msg;
            default:
               return false;
        }

    }


    /**
     * 图像处理
     */
    public function image()
    {
        $obj = $this->response;
        $fromusername = $obj->FromUserName;
        $tousername = $obj->ToUserName;
        $time = time();
        $content = '你发了图片过来';
        $tpl = "<xml>
                        <ToUserName><![CDATA[%s]]></ToUserName>
                        <FromUserName><![CDATA[%s]]></FromUserName>
                        <CreateTime>%s</CreateTime>
                        <MsgType><![CDATA[text]]></MsgType>
                        <Content><![CDATA[%s]]></Content>
                    </xml>";
        $msg = sprintf($tpl, $fromusername, $tousername, $time, $content);
        return $msg;
    }


    /**
     * 【上传永久】
     * @param $file string s文件路径
     */
    public function uploadImg($file){

        if (!file_exists($file) || !is_readable($file)) {
            throw new Exception("File does not exist, or the file is unreadable: '$file'");
        }
        $media =  [ 'media'=> new \CURLFile(realpath($file))];
        //永久素材上传
        $url = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token={$this->accessToken}&type=image";
        $data = $this->https_request($url,$media);
        return $this->dealRet($data);
    }

    /**
     * 获得素材
     * @param $type string sucai
     */
    public function getMaterial($type){
        $postInfo = array(
            "type"=>$type,
           "offset"=>0,
           "count"=>20
        );
        $url = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token={$this->accessToken}";

        $data = json_decode($this->https_request($url,json_encode($postInfo)),true);
        return $data;
    }

    /**
     * 删除素材
     * @param $media_id int 媒体id
     */
    public function delMaterial($media_id){
        $media = json_encode(['media_id'=>$media_id]);
        $url = "https://api.weixin.qq.com/cgi-bin/material/del_material?access_token={$this->accessToken}";
        return json_decode(($this->https_request($url,$media)),true);
    }

    /**
     * 上传图文
     * @param $content string 图文内容
     */
    public function uploadImgText($content){

        $url = "https://api.weixin.qq.com/cgi-bin/material/add_news?access_token={$this->accessToken}";
        $data = json_decode($this->https_request($url,$content),true);
        return $data;
    }

    /**
     * 关注得到用户信息
     * @param $openid string 用户openid
     */
    public function getinfo($openid)
    {
        if(!$openid){
            return false;
        }
        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$this->accessToken}&openid={$openid}";
        $data = json_decode($this->https_request($url), true);
        return $data;
    }


    /**
     *创建微信菜单
     * @param data 菜单数据
     */
    public function createMuen($menu)
    {
        $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token={$this->accessToken}";
        $res = $this->https_request($url, $menu);
        return $res;
    }

    /**
     *获取关注用户信息
     * @param data
     */
    public function getUserList(){

        $url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token={$this->accessToken}";
        $res = $this->https_request($url);

        return $res;
    }

    /**
     *群发接口
     * @param data
     */
    public function sendAllTextAndImg($media_id){
        if(empty($media_id)){
            return false;
        }

        $info = array(
            'filter'=>array('is_to_all'=>true),
            'mpnews'=>array('media_id'=>$media_id),
            'msgtype'=>'mpnews',
            'send_ignore_reprint'=>1
        );

        $url = "https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token={$this->accessToken}";
        $res = $this->https_request($url,json_encode($info));
        return $res;
    }

    /**
     * @param $url
     * @param null $data post数据
     * @return mixed*
     */
    protected function https_request($url, $data = null)
    {
        $curl = curl_init();

        curl_setopt($curl, CURLOPT_URL, $url);

        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }



    /**
     * 【处理结果】
     * @param $url
     * @param null $data post数据
     * @return mixed*
     */
    protected function dealRet($data){

        $data = json_decode($data,true);

        if(key_exists('errmsg',$data)){
            return [
                ' isSucess'=>false,
                'error'=>$data['errmsg']
            ];
        }else{
            return [
                'isSucess'=>true,
                'ret'=>$data
            ];
        }

    }
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值