1.先安装composer
https://docs.phpcomposer.com/00-intro.html#Installation-Windows
2.安装easywechat
使用命令行窗口,先执行一下composer,确保composer安装成功, 然后把镜像改为中国镜像
(https://pkg.phpcomposer.com/),执行
composer config -g repo.packagist composer https://packagist.phpcomposer.com
,然后(cd 命令)进入到项目public目录安装easywechat,执行
composer require "overtrue/wechat:^4.2" -vvv ,就安装好了
3.使用easywechat
1. 引用
use EasyWeChat\OpenPlatform\Server\Guard;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Messages\Text;
use EasyWeChat\Kernel\Messages\Image;
use EasyWeChat\Kernel\Messages\Video;
use EasyWeChat\Kernel\Messages\Voice;
use EasyWeChat\Kernel\Messages\News;
use EasyWeChat\Kernel\Messages\NewsItem;
use EasyWeChat\Kernel\Messages\Article;
2.配置
public $app;
public function initialize()
{
//微信公众号配置
$wechartconfig=array(
'app_id' =>Config('app.sys_appid'),
'secret' =>Config('app.sys_secret'),
'tocken'=>Config('app.sys_tocken'),//公众平台的tocken
'aes_key'=> Config('app.sys_aes_key'),//公众平台的aes_key
'response_type'=>'array',//消息类型
/**
* OAuth 配置
*
* scopes:公众平台(snsapi_userinfo / snsapi_base),开放平台:snsapi_login
* callback:OAuth授权完成后的回调页地址
*/
'oauth' => [
'scopes' => ['snsapi_userinfo'],
//'callback' => '/api/user/oauth_callback',
],
);
// echo '<pre>';
// print_r($wechartconfig);
$this->app=Factory::officialAccount($wechartconfig);
}
3.使用
public function wexin()
{
$this->app->server->push(function ($message) {
switch ($message['MsgType']) {
case 'event':
return $this->saveinfo($message);
break;
case 'text':
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 =$this->app->server->serve();
// 将响应输出
$response->send();
exit;
}
//事件
private function saveinfo($message)
{
$gzhopenid=$message['FromUserName'];
//关注
if($message['Event']=='subscribe')
{
$user=$this->app->user->get($gzhopenid);
$data=[];
$data['member_nickname']=$user['nickname'];
$data['gzhopenid']=$user['openid'];
$data['member_head_pic']=$user['headimgurl'];
$data['member_time']=$user['subscribe_time'];
$data['gzhisattention']=1;
$data['unionid']=$user['unionid'];
//查看是否已经保存会员
$info=$this->getmem($user['unionid']);
if(empty($info['unionid']))
{
DB::name('member')->insert($data);
}else{
DB::name('member')->where(['unionid'=>$user['unionid']])->update($data);
}
return '欢迎您的关注!';
}elseif($message['Event']=='unsubscribe')
{
$data=[];
$data['gzhisattention']=0;
DB::name('member')->where(['gzhopenid'=>$gzhopenid])->update($data);
}
}
//获取会员
private function getmem($unionid='')
{
$info=DB::name('member')->where(['unionid'=>$unionid])->find();
return $info;
}