Ocr.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. namespace app\admin\common;
  3. use think\facade\Cache;
  4. class Ocr
  5. {
  6. private $name="hw98795781";
  7. private $id="0b5f3e336280f3c91f09c01ad29e253e";
  8. private $password="wyhtQazwsx12";
  9. public $region="cn-north-4";
  10. public $project_id ="0b5f50097c80f2722fd7c01af96659ce";
  11. private $auth_api="https://iam.cn-north-4.myhuaweicloud.com/v3/auth/tokens?nocatalog=1";
  12. public $token="";
  13. public function GetToken(){
  14. $params=[
  15. "auth"=>[
  16. "identity"=>[
  17. "methods"=>["password"],
  18. "password"=>[
  19. "user"=>[
  20. "domain"=>["name"=>$this->name],
  21. "name"=>$this->name,
  22. "password"=>$this->password
  23. ]
  24. ]
  25. ],
  26. "scope"=>[
  27. "project"=>["name"=>$this->region,"id"=>$this->project_id]
  28. ]
  29. ]
  30. ];
  31. $this->token=Cache::get("x-auth-token");
  32. if($this->token==""){
  33. $result = post($this->auth_api,json_encode($params));
  34. $data =explode("\r\n",$result);
  35. array_walk($data,function (&$val,$key){
  36. $temp = explode(":",$val);
  37. if(count($temp)>1){
  38. $val=[$temp[0]=>$temp[1]];
  39. }
  40. });
  41. $token=array_column($data,"X-Subject-Token");
  42. $this->token= $token[0];
  43. Cache::set("x-auth-token",$token[0],23*3600);
  44. }
  45. }
  46. public function query($img="",$url=""){
  47. if($img==""&&$url==""){
  48. return ["code"=>1003,"msg"=>"图片识别失败"];
  49. }
  50. $this->GetToken();
  51. $header=["x-auth-token:" .$this->token,"Content-Type:application/json;charset=UTF-8"];
  52. $urlc ="https://ocr.cn-north-4.myhuaweicloud.com/v2/".$this->project_id."/ocr/business-license";
  53. $param=["url"=>$url,"image"=>$img];
  54. $key = post2($urlc,json_encode($param),$header);
  55. if($key==false){
  56. $return = ["code"=>1003,"msg"=>"图片识别失败"];
  57. }else{
  58. $return = ["code"=>0,"msg"=>"图片识别成功","data"=>json_decode($key,true)];
  59. }
  60. return $return;
  61. }
  62. }