WechatOpenPlatformService.php 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. namespace Modules\Channel\Services\WechatOpenPlatform;
  3. use EasyWeChat\OpenPlatform\Application;
  4. use EasyWeChat\OpenPlatform\Message;
  5. use Illuminate\Support\Facades\Cache;
  6. use Illuminate\Support\Facades\DB;
  7. use Modules\Common\Errors\Errors;
  8. use Modules\Common\Exceptions\CommonBusinessException;
  9. class WechatOpenPlatformService
  10. {
  11. public static function getComponentInfoByCompanyUid($companyUid) {
  12. $componentInfo = DB::table('wechat_open_platform_infos')
  13. ->where([
  14. 'company_uid' => $companyUid,
  15. 'is_enabled' => 1,
  16. ])->orderBy('id', 'desc')
  17. ->first();
  18. if(!$componentInfo) {
  19. CommonBusinessException::throwError(Errors::OPENPLATFORM_COMPANY_INFO_NOT_EXISTS);
  20. }
  21. return $componentInfo;
  22. }
  23. public static function getComponentInfoByAppid($componentAppid) {
  24. $componentInfo = DB::table('wechat_open_platform_infos')
  25. ->where([
  26. 'app_id' => $componentAppid,
  27. 'is_enabled' => 1,
  28. ])->orderBy('id', 'desc')
  29. ->first();
  30. if(!$componentInfo) {
  31. CommonBusinessException::throwError(Errors::OPENPLATFORM_COMPANY_INFO_NOT_EXISTS);
  32. }
  33. return $componentInfo;
  34. }
  35. /**
  36. * 构造app
  37. * @param $componentInfo
  38. * @return Application
  39. * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
  40. */
  41. public static function buildApplication($componentInfo) {
  42. $config = [
  43. 'app_id' => $componentInfo->app_id, // 开放平台账号的 appid
  44. 'secret' => $componentInfo->secret, // 开放平台账号的 secret
  45. 'token' => $componentInfo->token, // 开放平台账号的 token
  46. 'aes_key' => $componentInfo->aes_key, // 明文模式请勿填写 EncodingAESKey
  47. 'http' => [
  48. 'throw' => true, // 状态码非 200、300 时是否抛出异常,默认为开启
  49. 'timeout' => 5.0,
  50. 'retry' => true, // 使用默认重试配置
  51. ],
  52. ];
  53. $app = new Application($config);
  54. $app->setCache(Cache::store('redis'));
  55. return $app;
  56. }
  57. /**
  58. * 取消授权
  59. * @param Message $message
  60. */
  61. public static function handleUnauthorized($message) {
  62. $component_appid = $message['AppId'];
  63. $authorizer_appid = $message['AuthorizerAppid'];
  64. DB::table('wechat_authorization_infos')
  65. ->where([
  66. 'component_appid' => $component_appid,
  67. 'authorizer_appid' => $authorizer_appid,
  68. ])->delete();
  69. }
  70. }