从零开始系列-Laravel编写api服务接口:8.集成微信包-LaravelWechat的使用

Laravel框架
543
0
0
2022-04-12

LaravelWechat 的使用

简介

laravelwechat 是 easywechat 封装的一个包,用法比较简单

附链接:

laravel-wechat

easy-wechat

先简单介绍以下功能:

微信公众号

文档: 微信公众号

公众号授权登录(需要配置授权目录)

服务消息推送(需要配置推送链接)

微信推送 (通过 openid 进行推送)

安装

composer require "overtrue/laravel-wechat:^6.0"
// 创建配置文件
php artisan vendor:publish --provider="Overtrue\LaravelWeChat\ServiceProvider"
以下是用法:
// 授权登录公共方法fun_common.php
function wechat()
{
  $app = app('wechat.official_account');
  return $app;
}

// 公众号授权登录方法(这个方法会接收一个code,授权登录配置页面到前端,前端拿到code后访问此接口)
public function wechatLogin(LoginRequest $request) {
  $code = $request->input('code');
  if (blank($code)){
    dd('code不能为空');
  }
  $app = wechat();
  $user = $app->oauth->user();
  $wechat_user = $user->getOriginal();
  // 登录逻辑。。。
}

// 微信配置服务器地址路由到这个控制器
public function serve(Request $request)
{
  $this->wechat = wechat();
  if(isset($_GET['echostr']) && !empty($_GET['echostr'])){
    $this->wechat->server->push(function($message){
      return $message->echostr;// 第一次绑定要用这个
    });
  }else{
    $message = $server->getMessage();// 在闭包外调用$message
    $this->wechat->server->push(function($message){
    // $message['FromUserName'] // 用户的 openid
    // $message['MsgType'] // 消息类型:event, text....
      return '';// 什么都不返回
      return 'SUCCESS';// 或者什么都不返回
      return '你好啊'; // 或者返回文本消息
      return new Image('media-id'); // 或者返回图片消息
      $news = new NewsItem(...);
      return new News([$news]); // 或者返回多图文消息
      // or something else
    });
  }
  //return response.
  return $this->wechat->server->serve();
}

// 微信模板消息推送

$app->template_message->send([
    'touser' => 'user-openid',
    'template_id' => 'template-id',
    'url' => 'https://easywechat.org',
    'miniprogram' => [
        'appid' => 'xxxxxxx',
        'pagepath' => 'pages/xxx',
    ],
    'data' => [
      'key1' => 'VALUE',
      'key2' => 'VALUE2',
      ...
    ],
  ]);

微信开放平台

简介

微信文档官网 微信官方文档


微信开放平台文档 微信开放平台第三方平台(公众号小程序等)


// 公共方法
function platFormWithRedis($name = '')
{
  $openPlatform_with_redis = app('wechat.open_platform');
  $cache          = new RedisAdapter(app('redis')->connection()->client());
  $openPlatform_with_redis->rebind('cache', $cache);// 原本使用文件缓存,换成laravel缓存
  return $openPlatform_with_redis;
}
// 控制器class - 方法
$this->openPlatform = platFormWithRedis();
// 微信授权事件接收 测试是否授权了,其它也可以这么用,参考公众号事件
public function wx_post_open_platform(){
  Log::info("微信开放平台授权事件(什么都不做)");
  return $this->openPlatform->server->serve();
}

// 授权页面跳转
// 点击这个链接,扫码后跳转到授权页进行授权
public function get_wx_preAuthorizationUrl(){
  $url = $this->openPlatform->getPreAuthorizationUrl('http://'.$_SERVER['SERVER_NAME'].'/api-ih/api/get_wx_pre_authorization_url/callback');
  return view("platform_get_auth",[
    'url' => $url
  ]);
}

// 就是上面那个方法的回调地址处理授权,把一些信息记录到数据库
public function get_wx_preAuthorizationUrl_callback(){
  $auth_result = $this->openPlatform->handleAuthorize();

  // 获取扫码授权后的回调数据
  $data['platform_authorizer_appid'] = $auth_result['authorization_info']['authorizer_appid'];
  $data['platform_authorizer_access_token'] = $auth_result['authorization_info']['authorizer_access_token'];
  $data['platform_expires_in'] = $auth_result['authorization_info']['expires_in'];
  $data['platform_authorizer_refresh_token'] = $auth_result['authorization_info']['authorizer_refresh_token'];

  $info_result = $this->openPlatform->getAuthorizer($data['platform_authorizer_appid']);
  $data['platform_user_name'] = $info_result['authorizer_info']['user_name'];

  // 插入或者更新数据库的授权数据,以appid为主键
  if (!WxPlatform::where('platform_authorizer_appid', $data['platform_authorizer_appid'])->exists()) {
    $wx_platform = new WxPlatform($data);
    $wx_platform->save();
  }else{
    WxPlatform::where('platform_authorizer_appid', $data['platform_authorizer_appid'])->update([
      'platform_authorizer_access_token'=>$data['platform_authorizer_access_token'],
      'platform_authorizer_refresh_token'=>$data['platform_authorizer_refresh_token']
    ]);
  }

  return "授权成功,关闭页面即可";
}
// ...不解释了$appid表示开放平台变量有些业务在开放平台处理(事件等)
// 这个方法很奇怪
function wechat($name = '', $appid = '')
{
  $status = env('WECHAT_OFFICIAL_ACCOUNT_USED', false);
  if ($status && $appid == '') {
    // 开启服务器配置
    Log::info("初始化服务器配置");
    $name = empty($name) ? 'wechat.official_account' : 'wechat.official_account.' . $name;
    $app = app($name);
  } else {
    // 使用开放平台
    Log::info("初始化开放平台");
    $openPlatform_with_redis = app('wechat.open_platform');
    $cache          = new RedisAdapter(app('redis')->connection()->client());
    $openPlatform_with_redis->rebind('cache', $cache);// 给它一个缓存(原来使用php文件缓存)
    $openPlatform = $openPlatform_with_redis;
    $appid     = env('WECHAT_OFFICIAL_ACCOUNT_APPID', ''); // 获取后台绑定的公众号
    $appid_account = WxPlatform::where('platform_authorizer_appid', $appid)->first();  // 通过appid,获取公众号的refresh_token
    $app      = $openPlatform->officialAccount($appid, $appid_account['platform_authorizer_refresh_token']); // 代公众号实现业务
  }
  return $app;
}


// 改造后的serve

public function serve(Request $request)
{
  Log::channel('wechatLog')->info('环境:'.env('DB_DATABASE')."微信事件开始执行--------");
  if($request->has('appid')){ // 开放平台事件会携带这个参数。。。
    $appid = ltrim ($request->input('appid'),'/');
  }else{
    $appid = '';
  }
  if($appid == ''){
    $this->app = wechat();
  }else{
    $this->app = wechat($name = '',$appid);
  }
  if(isset($_GET['echostr']) && !empty($_GET['echostr'])){
   // 第一次绑定
   $this->wechat->push(function($message){
      return $message->echostr;
    });
  }else{
   // 处理消息
   $this->wechat->push(function($message){
      return '';
    });
  }
  //return response.
  return $this->app->server->serve();
}

到这里一些东西已经结束了,以后想到什么再补充