Ocr.php 2.2 KB

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