使用EasyWeChat写客服消息回复的接口

使用EasyWeChat写客服消息回复的接口

thinkphp 使用easywechat 写客服回复的接口

引入EasyWechat 到框架中

使用composer 安装
$ composer require overtrue/wechat:~4.0 -vvv

微信公众号或小程序的appid 和 secret

use EasyWeChat\Factory;

$config = [
    'app_id' => '',
    'secret' => '',

    // 指定 API 调用返回结果的类型:array(default)/collection/object/raw/自定义类名
    'response_type' => 'array',

    //...
];
$app = Factory::officialAccount($config);公众号

$app = Factory::miniProgram($config);小程序
 $app->customer_service->message($message)->to($openId)->send(); 小程序发送


具体代码的实现

use EasyWeChat\Factory;
use EasyWeChat\Kernel\Messages\Text;
use EasyWeChat\Kernel\Messages\Image;
use EasyWeChat\Kernel\Messages\Raw;
public function replyWxContent()
{
    $config = config('account.easywechat');
    $app = Factory::miniProgram($config);
    $app->server->push(function ($message) use ($app) {
        switch ($message['MsgType']) {
            case 'event':
                return '收到事件消息';
                break;
            case 'text':
                $serverReplyModel = new ServerReply();
                $fileModel = new File();
                //查找客服回复的对应内容
                $result = $serverReplyModel->where('reply_key_word', 'like', '%' . $message['Content'] . '%')->find();
                if ($result) {
                    switch ($result['type']) {
                        case 1:
                            //回复一条文本消息
                            $content = new Text($result['reply_content']);
                            $app->customer_service->message($content)->to($message['FromUserName'])->send();
                            break;
                        case 2:
                            //回复一张图片消息
                            $image_url = $fileModel->getPath($result['reply_content']);
                            $media_id = $this->getMediaId($image_url);
                            $content = new Image($media_id);
                            $app->customer_service->message($content)->to($message['FromUserName'])->send();
                            break;
                        case 3:
                            //回复一条链接消息
                            $data = [];
                            $data['touser']= $message['FromUserName'] ;
                            $data['msgtype'] = 'link';
                            $data['link']= [
                                'title'=>$result['title'],
                                'description'=>$result['description'],
                                'url'=>$result['url'],
                                'thumb_url'=>$fileModel->getPath($result['image_id'])
                            ];
                            $content = new Raw(json_encode($data));
                            $app->customer_service->message($content)->to($message['FromUserName'])->send();
                            break;
                    }
                } else {
                    $app->customer_service->message('查询不到匹配的内容')->to($message['FromUserName'])->send();
                }
                // return '收到文字消息';
                break;
            case 'miniprogrampage':
                // return '收到卡包消息';
                break;
            case 'image':
                // return '收到图片消息';
                break;
            case 'voice':
                // return '收到语音消息';
                break;
            case 'video':
                // return '收到视频消息';
                break;
            case 'location':
                // return '收到坐标消息';
                break;
            case 'link':
                // return '收到链接消息';
                break;
            case 'file':
                // return '收到文件消息';
                // ... 其它消息
            default:
                // return '收到其它消息';
                break;
        }
    });
    $response = $app->server->serve();
    $response->send();
}

上传图片到微信服务器

public function getMediaId($url = '')
    {
        if (!empty($url)) {
            $cache_key = 'get_media_id_' . $url;
            $media_id = cache($cache_key);
            if ($media_id === false) {
                $config = config('account.easywechat');
                $app = Factory::miniProgram($config);;
                $imagePath = $this->downloadImage($url);
                $data = [
                    'midia' => realpath('.' . $imagePath),
                ];
                try {
                    $result = $app->media->uploadImage($data['midia']);
                    if ($result['media_id']) {
                        $media_id = $result['media_id'];
                        cache($cache_key, $media_id, 60 * 60 * 48);
                    }
                } catch (\Exception $e) {
                    model('Common/DebugLog')->addLog($e->getMessage(), 'error');
                }

            }
            return $media_id;
        }
        return false;
    }

    public function downloadImage($url)
    {
        set_time_limit(0);
        $saveDir = '/uploads/' . date('Ymd');
        if (!is_dir("." . $saveDir)) {
            mkdir("." . $saveDir, 0777, true);
        }
        $saveSrc = $saveDir . '/' . md5($url) . ".jpg";
        try {
            $res = file_get_contents($url);
            if (false === $res) {
                return '';
            }
            file_put_contents("." . $saveSrc, $res);
            return $saveSrc;
        } catch (\Exception $e) {
            return '';
        }
    }

其中回复链接消息,easywechat 不支持,使用自定义Raw()方法

raw()需要传入的是json的数据格式
可以使用raw 创建想要发送的数据类型,具体需要的数据字段参考微信的官方文档

参考文档

https://www.easywechat.com/docs/4.1/official-account/server //easywechat
https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/customer-message/customerServiceMessage.send.html

你可能感兴趣的:(微信客服消息,php,小程序)