Model.php 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. <?php
  2. /**
  3. * 重庆赤晓店信息科技有限公司
  4. * https://www.chixiaodian.com
  5. * Copyright (c) 2023 赤店商城 All rights reserved.
  6. */
  7. namespace app\modules\admin\models\wechat_mp;
  8. use yii\base\Model as YModel;
  9. use app\models\Option;
  10. use app\constants\OptionSetting;
  11. use EasyWeChat\Factory;
  12. use app\utils\CurlHelper;
  13. class Model extends YModel
  14. {
  15. public $need_mp = true;
  16. public $wechat_mp;
  17. public function rules()
  18. {
  19. return [
  20. [['wechat_mp'], 'safe'],
  21. ];
  22. }
  23. public function wechatConf() {
  24. $conf = Option::get(OptionSetting::WECHAT_MP, 0, 'saas')['value'];
  25. if($conf){
  26. $conf = json_decode($conf, true);
  27. $conf['response_type'] = 'array';
  28. // $conf['log'] = [
  29. // 'default' => 'dev', // 默认使用的 channel,生产环境可以改为下面的 prod
  30. // 'channels' => [
  31. // // 测试环境
  32. // 'dev' => [
  33. // 'driver' => 'single',
  34. // 'path' => \Yii::$app->runtimePath . '/logs/easywechat1.log',
  35. // 'level' => 'debug',
  36. // ],
  37. // // 生产环境
  38. // 'prod' => [
  39. // 'driver' => 'daily',
  40. // 'path' => '/tmp/easywechat.log',
  41. // 'level' => 'info',
  42. // ],
  43. // ],
  44. // ];
  45. return $conf;
  46. }
  47. return [];
  48. }
  49. public function init() {
  50. parent::init();
  51. $config = $this->wechatConf();
  52. if($config){
  53. $this->wechat_mp = Factory::officialAccount($config);
  54. }
  55. }
  56. public function wxUploadImage($url)
  57. {
  58. $path = $this->saveTempImage($url);
  59. if ($this->wechat_mp) {
  60. $api = $this->wechat_mp->material;
  61. $res = $api->uploadImage($path);
  62. \Yii::error([__METHOD__, $res]);
  63. if($res['errcode']){
  64. return [
  65. 'code' => 1,
  66. 'msg' => $res['errmsg'],
  67. 'res' => $res,
  68. ];
  69. }
  70. return $res;
  71. } else {
  72. return [
  73. 'code' => 1,
  74. 'msg' => '需要配置微信信息'
  75. ];
  76. }
  77. }
  78. public function wxDelMaterial($media_ids)
  79. {
  80. $api = $this->wechat_mp->material;
  81. foreach ($media_ids as $media_id) {
  82. $res = $api->delete($media_id);
  83. \Yii::error([__METHOD__, $res]);
  84. }
  85. return $res;
  86. }
  87. //获取网络图片到临时目录
  88. public function saveTempImage($url)
  89. {
  90. if (strpos($url,'http') === false) {
  91. $url = 'http:'. trim($url);
  92. }
  93. if (!is_dir(\Yii::$app->runtimePath . '/image')) {
  94. mkdir(\Yii::$app->runtimePath . '/image');
  95. }
  96. $save_path = \Yii::$app->runtimePath . '/image/' . md5($url) . '.jpg';
  97. CurlHelper::download($url, $save_path);
  98. return $save_path;
  99. }
  100. }