Official.php 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. <?php
  2. namespace App\Servers\Wechat;
  3. use EasyWeChat\Factory;
  4. use App\Facades\Servers\Logs\Log;
  5. /**
  6. * 微信公众号
  7. *
  8. */
  9. class Official
  10. {
  11. // 工作列表
  12. protected \EasyWeChat\OfficialAccount\Application $app;
  13. // 构造函数
  14. public function __construct()
  15. {
  16. // 应用实例
  17. $this->app = $this->getApp();
  18. }
  19. /**
  20. * 获取应用实例
  21. *
  22. * @return \EasyWeChat\OfficialAccount\Application
  23. *
  24. */
  25. public function getApp()
  26. {
  27. // 获取配置
  28. $this->app = Factory::officialAccount(config('wechat.official', []));
  29. // 返回结果
  30. return $this->app;
  31. }
  32. /**
  33. * 获取user
  34. * @param string $code 通过 前端授权code获取用户openid
  35. *
  36. *
  37. */
  38. public function userFromCode($code)
  39. {
  40. // 获取手机号
  41. $result = $this->app->oauth->userFromCode($code);
  42. // 判断结果
  43. if (!empty($result['errcode'])) return ['error' => $result['errcode'] . '=>' . $result['errmsg']];
  44. // 获取不包含区号的手机号(因为绑定手机号字段会有国际区号)
  45. return $result;
  46. }
  47. /**
  48. * 获取JSSDK的配置数组
  49. * @return array
  50. */
  51. public function getJssdkConfig($url = '')
  52. {
  53. // 如果指定路径的话
  54. if ($url) $this->app->jssdk->setUrl($url);
  55. // 获取JSSDK的配置对象
  56. $config = $this->app->jssdk->buildConfig(['updateAppMessageShareData', 'updateTimelineShareData'], false, false, false);
  57. // 获取JSSDK的配置数组
  58. return $config;
  59. }
  60. /**
  61. * 发送一次性订阅消息
  62. * @param array $params
  63. *
  64. */
  65. public function sendSubscription($params)
  66. {
  67. try {
  68. $result = $this->app->template_message->sendSubscription([
  69. 'touser' => $params['openid'],
  70. 'template_id' => 'template-id',
  71. 'miniprogram' => $params['miniprogram'],
  72. 'scene' => 1000,
  73. 'data' => $params['data'],
  74. ]);
  75. // 判断结果
  76. if (!empty($result['errcode'])) return ['error' => $result['errcode'] . '=>' . $result['errmsg']];
  77. return $result;
  78. } catch (\Exception $e) {
  79. Log::info('wechat_subscribe_error', '订阅消息通知推送队列失败', ['data' => $params, 'error' => $e->getMessage()]);
  80. }
  81. }
  82. /**
  83. * 发送模板消息
  84. * @param array $params
  85. *
  86. */
  87. public function send($params)
  88. {
  89. $result = $this->app->template_message->send([
  90. 'touser' => $params['openid'],
  91. 'template_id' => 'template-id',
  92. 'url' => $params['url'],
  93. 'scene' => 1000,
  94. 'data' => $params['data'],
  95. ]);
  96. // 判断结果
  97. if (!empty($result['errcode'])) return ['error' => $result['errcode'] . '=>' . $result['errmsg']];
  98. return $result;
  99. }
  100. }