Official.php 3.2 KB

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