Media.php 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. <?php
  2. namespace App\Http\Controllers\Wechat;
  3. use App\Models\Common\TokenModel;
  4. use Illuminate\Http\Request;
  5. use App\Http\Controllers\Controller;
  6. use Ixudra\Curl\Facades\Curl;
  7. class Media extends Controller
  8. {
  9. public static function uploadImg($imageUrl, string $public = null)
  10. {
  11. if (empty($public)) {
  12. $token = Base::getAccessToken();
  13. } else {
  14. $token = TokenModel::getToken($public);
  15. }
  16. $filename = storage_path() . '/app/' . uniqid() . '.png';
  17. \File::put($filename, Curl::to($imageUrl)->get());
  18. $http = 'https://api.weixin.qq.com/cgi-bin/media/upload?access_token=' . $token . '&type=image';
  19. $response = Curl::to($http)
  20. ->withData([
  21. 'media' => "@{$filename}"
  22. ])
  23. ->withFile('chat_' . uniqid(), $filename)
  24. ->post();
  25. \File::delete($filename);
  26. $result = json_decode($response, true);
  27. if (isset($result['errcode'])) {
  28. return ['code' => $result['errcode'], 'msg' => $result['errmsg']];
  29. } else {
  30. return ['code' => 0, 'msg' => 'OK', 'data' => $result];
  31. }
  32. }
  33. }