最近在研究百度云的一些服务,处理api接口鉴权时花了不少时间,总结一下,方便大家对接:

  1. Signer.php:签名工具类,鉴权签名的核心方法都在这里
  2. Utils.php:封装的工具类,鉴权,返回json数据等都在这里
  3. Account.php:示例Controller,请求百度云接口

文章目录

  • 签名工具类
  • 封装的工具类,集成了常用的方法
  • 业务层controller:百度api在请求接口的同时做权限校验

使用的tp5框架,代码仅供参考,思路可以供大家借鉴,如有不当之处,欢迎指正

签名工具类

Signer.php

/*** Created by PhpStorm.* User: 王中阳* Date: 2021/3/07* Time: 9:45*/<?phpclass SignerException extends Exception
{function __construct($message){parent::__construct($message, 999);}
}class Signer
{private $ak;private $sk;private $version = "1";private $timestamp;private $expiration = 1800;private $method;private $uri;private $params = array();private $headers = array();private $needLog = false;function __construct($accessKey, $secretKey){$this->ak = $accessKey;$this->sk = $secretKey;$date = new DateTime('now');$date->setTimezone(new DateTimeZone('UTC'));$this->timestamp = $date->format('Y-m-d\TH:i:s\Z');}public function setVersion($version){$this->version = $version;}public function setExpiration($expiration){$this->expiration = $expiration;}public function setMethod($method){if (!empty($method)) {$this->method = strtoupper($method);}}public function setTimestamp($timestamp){$this->timestamp = $timestamp;}public function setUri($uri){$this->uri = $uri;}public function setParams($params){$this->params = $this->normalizeParam($params);}public function setSignHeaders($headers){$this->headers = $this->normalizeHeaders($headers);}public function beLog($needLog){$this->needLog = $needLog;}public function genAuthorization(){$signature = $this->genSignature();$authStr = "bce-auth-v" . $this->version . "/" .$this->ak . "/" . $this->timestamp . "/" .$this->expiration . "/" . $this->getSignedHeaderNames() . "/" . $signature;return $authStr;}public function genSignature(){if (empty($this->method)) {throw new SignerException("method is null or empty");}$signingKey = $this->genSigningKey();$this->signerLog("signingKey:" . $signingKey, __LINE__, __FILE__);$authStr = $this->method . "\n" .$this->getCanonicalURI() . "\n" .$this->getCanonicalParam() . "\n" .$this->getCanonicalHeaders();$this->signerLog("auth str:" . $authStr, __LINE__, __FILE__);return $this->sha256($signingKey, $authStr);}public function genSigningKey(){if (empty($this->ak)) {throw new SignerException("access key is null or empty");}if (empty($this->sk)) {throw new SignerException("secret key is null or empty");}if (empty($this->version)) {throw new SignerException("version is null or empty");}if (empty($this->timestamp)) {throw new SignerException("timestamp is null or empty");}if (empty($this->expiration)) {throw new SignerException("expiration is null or empty");}$authStr = "bce-auth-v" . $this->version . "/" . $this->ak . "/" .$this->timestamp . "/" . $this->expiration;return $this->sha256($this->sk, $authStr);}public function getCanonicalParam(){if (empty($this->params)) {return "";}$arryLen = count($this->params);$canonicalParams = "";foreach ($this->params as $key => $value) {if (is_array($value)) {$num = count($value);if (count($value) == 0) {$canonicalParams = $canonicalParams . $key . "=";} else {foreach ($value as $item) {$canonicalParams = $canonicalParams . $key . "=" . $item;if ($num > 1) {$canonicalParams = $canonicalParams . "&";$num--;}}}} else {$canonicalParams = $canonicalParams . $key . "=" . $value;}if ($arryLen > 1) {$canonicalParams = $canonicalParams . "&";$arryLen--;}}return $canonicalParams;}public function getCanonicalURI(){if (empty($this->uri)) {throw new SignerException("uri is null or empty");}$newUri = $this->dataEncode($this->uri, true);if (strpos($newUri, "/") === 0) {return $newUri;}return "/" . $newUri;}public function getCanonicalHeaders(){if (empty($this->headers) || !array_key_exists("host", $this->headers)) {throw new SignerException("host not in headers");}$canonicalHeaders = "";$strArry = array();foreach ($this->headers as $key => $value) {if (empty($value)) {continue;}$strArry[] = $this->dataEncode($key, false) . ":" . $value;}$arryLen = count($strArry);for ($i = 0; $i < $arryLen; $i++) {if ($i < $arryLen - 1) {$canonicalHeaders = $canonicalHeaders . $strArry[$i] . "\n";continue;}$canonicalHeaders = $canonicalHeaders . $strArry[$i];}return $canonicalHeaders;}private function sha256($key, $data){return hash_hmac('sha256', $data, $key);}private function dataEncode($data, $isPath){if (empty($data)) {return "";}$encode = mb_detect_encoding($data, array("ASCII", "UTF-8", "GB2312", "GBK", "BIG5"));if ($encode != "UTF-8") {$data = $code1 = mb_convert_encoding($data, 'utf-8', $encode);}$encodeStr = rawurlencode($data);if ($isPath) {$encodeStr = str_replace("%2F", "/", $encodeStr);}return $encodeStr;}private function normalizeHeaders($headers){$newArray = array();if (empty($headers)) {return $newArray;}foreach ($headers as $key => $value) {$newKey = strtolower($key);if (empty($newKey)) {continue;}$newArray[$newKey] = $this->dataEncode(trim($value), false);}ksort($newArray);return $newArray;}private function normalizeParam($params){$newArray = array();if (empty($params)) {return $newArray;}foreach ($params as $key => $value) {if (empty($key) || strtolower($key) == "authorization") {continue;}if (is_array($value)) {$newSubArray = array();foreach ($value as $item) {$newSubArray[] = $this->dataEncode($item, false);}sort($newSubArray);$newArray[$this->dataEncode($key, false)] = $newSubArray;} else {$newArray[$this->dataEncode($key, false)] = $this->dataEncode($value, false);}}ksort($newArray);return $newArray;}private function getSignedHeaderNames(){$arryLen = count($this->headers);$headerNames = "";foreach ($this->headers as $key => $value) {$headerNames = $headerNames . $key;if ($arryLen > 1) {$headerNames = $headerNames . ";";$arryLen--;}}return $headerNames;}private function signerLog($content, $line, $file){if ($this->needLog) {error_log($file . ":" . $line . ":[" . $content . "]\n", 3, "./signer_log");}}
}?>

封装的工具类,集成了常用的方法

Utils.php

<?php/*** Created by PhpStorm.* User: 王中阳* Date: 2021/3/07* Time: 9:45*/
require 'Signer.php';
define('AK', "your ak");
define('SK', "your sk");
define('HOST', "sem.baidubce.com"); //按百度要求换内容
define('BASE_URL', "http://sem.baidubce.com/");//按百度要求换内容
define('HTTP_Method', "POST");//按百度要求换内容class Utils
{//公共header  注意:我对接的是百度信息流推广api,header应根据百度云各服务的要求进行修改static function Header(){return ['opUsername' => 'xxxxxxx','opPassword' => 'xxxxxxx','tgUsername' => 'xxxxxxx','tgPassword' => 'xxxxxxx','bceUser' => 'xxxxxxx',];}//请求百度static function curl_post($url, $body, $auth){//处理请求体$files = ['header' => self::Header(),'body' => $body];$files = json_encode($files, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);$ch = curl_init();curl_setopt($ch, CURLOPT_POST, 1);curl_setopt($ch, CURLOPT_URL, $url);curl_setopt($ch, CURLOPT_POSTFIELDS, $files);curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','host:sem.baidubce.com',  //改成你的数据'authorization:' . $auth,'accept-encoding:gzip, deflate','accept:*/*'));$response = curl_exec($ch);$request = curl_getinfo($ch, CURLINFO_HEADER_OUT);$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);self::result($httpCode, $response);}//校验权限static function gen_auth($uri = ""){$headers = array();$headers['host'] = HOST;$signer = new \Signer(AK, SK);$signer->setMethod(HTTP_Method);$signer->setUri($uri);$signer->setSignHeaders($headers);try {$signature = $signer->genAuthorization();return $signature;} catch (SignerException $e) {echo $e->getMessage();return;}}//返回结果static public function result($errno = 0, $data = ''){header("Content-type: application/json;charset=utf-8");$errno = intval($errno);//注意:这里可能不满足你的项目 根据百度返回结果做修改 或者不用我这种处理方式//json转数组$data = json_decode($data, true);if (isset($data['header']['failures'][0])) {$message = $data['header']['failures'][0]['message'];} else {$message = 'success';}$json = json_encode($data['body']['data'][0]);$result = array('errno' => 1,'message' => $message,'data' => json_encode($data['body']['data'][0]),//处理百度 返回结果);echo json_encode($result, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);exit;}/*** 时间 日期*/static public function ymd($time){return date("Y-m-d", $time);}
}

业务层controller:百度api在请求接口的同时做权限校验

Account.php

/*** Created by PhpStorm.* User: 王中阳* Date: 2021/3/07* Time: 9:45*/<?php
namespace app\index\controller;require 'Utils.php';class Account
{/*** 获得账号信息*/public function info(){$uri = "v1/feed/cloud/AccountFeedService/getAccountFeed";$auth = \Utils::gen_auth($uri);$url = BASE_URL . $uri;$body = ['accountFeedFields' => ['userId','balance','budget','balancePackage','userStat','uaStatus','validFlows',],];//返回数据集成在Utils中\Utils::curl_post($url, $body, $auth);}

思路仅供参考。如有更好的处理方式,欢迎赐教。

百度智能云 API鉴权总结相关推荐

  1. 【python】调用百度智能云API实现手写文字识别

    注:本文系湛江市第十七中学星火创客团队及岭南师范学院物联网俱乐部原创部分参赛项目,转载请保留声明 文章目录 调用百度智能云API实现python识别手写文字 一.准备工具 电脑端准备: 1.pytho ...

  2. 调用百度智能云 api --新手入门教程

    登录或者注册用户 百度找到官网链接: 点击控制台: 登录上去,没有百度账户的可以先注册: 点击产品服务,找到人工智能,然后点击文字识别(下面的图片是老版的智能云): 点击创建应用 随便填自己的想要的名 ...

  3. Python调用百度智能云API进行文本情感分析

    Python调用百度智能云API进行文本情感分析 安装SDK 在调用前首先需要通过 pip 安装百度智能云 SDK. 可参考官方文档:https://cloud.baidu.com/doc/OCR/s ...

  4. 基于百度智能云api识别验证码

    基于百度智能云api识别验证码 通过调用百度智能云api接口进行验证码识别并输出. 使用baidu-aip模块进行模拟client登录,client.basicgeneral()函数识别图片文字并返回 ...

  5. python -百度智能云API -语言处理技术中的语句情感倾向分析

    python 百度智能云API 语言处理技术中的语句情感倾向分析 背景 实现 获取 access_token 请求情感分析接口 读取文本操作 背景 我姐的毕业论文中,要用到情感分析,他已经利用爬虫软件 ...

  6. python:ocr图文识别(百度智能云API文字识别)

    文章目录 前言 一.创建账号和应用 二.具体步骤 1.第一种方式: 2.第二种方式 总结 前言 说道OCR图文识别,其实python也有在自己的库(以下是我了解,应该还有很多): 第一个 tesser ...

  7. 识别验证码之百度智能云Api识别

    郑重声明: 本项目的所有代码和相关文章,仅用于经验技术交流分享,禁止将相关技术应用到不正当途径,因为滥用技术产生的风险与本人无关. 文章仅源自个人兴趣爱好,不涉及他用,侵权联系删 之前写过关于使用自动 ...

  8. 用Python提取图片中的文字——百度智能云API

    百度智能云有很多功能,直接接入接口就可以调用函数使用,这里我们使用简单的方式,直接调用,不适用OpenCV.TensorFlow啥的..毕竟我不是大佬... 安装库 首先安装Python库,使用pip ...

  9. 调用百度智能云API,实现身份证智能识别并转语音 | Python

    一.百度云新建应用.获取权限和额度 1. 登录百度智能云,产品服务-->人工智能-->图像识别 2. 应用列表-->创建应用,用于身份证照的信息识别 3. 应用创建完成,得到APP_ ...

最新文章

  1. 8.0强行转换后变成了7_【自学C#】|| 笔记 12 数据类型转换
  2. 玩具租赁到底在解决用户什么痛点?
  3. c++无继承情况下的对象构造
  4. java编译时多态和运行时多态_运行时多态、编译时多态和重载、重写的关系(不区分Java和C#,保证能看懂!)...
  5. 【转】Android开发之数据库SQL
  6. CodeForces 1610H Squid Game(延迟贪心 + 构造 + 树状数组)
  7. 计算机的数学发展史论文,数学简史论文范文
  8. android 面向对象,android 面向对象六大原则
  9. 肯普纳级数收敛性的证明
  10. scala.的Enumeration枚举示例(转)
  11. asp编程实例:通过表单创建word的一个例子
  12. Http 理论基础-请求与响应、响应状态码汇总
  13. 问题解决之--无法识别的属性“targetFramework”。请注意属性名称区分大小写。
  14. 嵌入式软件测试参考书籍
  15. 高斯过程回归预测 C++代码实现
  16. MATLAB机器人可视化运动仿真
  17. OJ 2306 Problem C Banana
  18. 搭建自己的V Rising自建服务器,以及常见的V Rising服务器问题解决方案
  19. 建设一个SaaS平台需要知道什么,做什么(附多图)
  20. ai修复图片 python_百度AI攻略:拉伸图像恢复

热门文章

  1. JS——日期的横杠、斜杠相互替换
  2. Git命令全解析-前端备忘录
  3. P9:最大池化的使用
  4. matplotlib交互式数据光标实现——mplcursors
  5. U3D游戏开发工程师正确入行姿势指南
  6. 帆软bi 观远bi_与电源bi一起加入
  7. 数学图形(2.2)N叶结
  8. intern()详解
  9. 使用Feign实现Form表单提交
  10. 基因编辑最新研究进展(2022年3月)