百度DOC php,PHP对接百度文档服务DOC
生成认证字符串需要用到的工具类
namespace App\Service;
class HttpUtil
{
// 根据RFC 3986,除了:
// 1.大小写英文字符
// 2.阿拉伯数字
// 3.点'.'、波浪线'~'、减号'-'以及下划线'_'
// 以外都要编码
public static $PERCENT_ENCODED_STRINGS;
//填充编码数组
public static function __init()
{
HttpUtil::$PERCENT_ENCODED_STRINGS = array();
for ($i = 0; $i < 256; ++$i) {
HttpUtil::$PERCENT_ENCODED_STRINGS[$i] = sprintf("%%%02X", $i);
}
//a-z不编码
foreach (range('a', 'z') as $ch) {
HttpUtil::$PERCENT_ENCODED_STRINGS[ord($ch)] = $ch;
}
//A-Z不编码
foreach (range('A', 'Z') as $ch) {
HttpUtil::$PERCENT_ENCODED_STRINGS[ord($ch)] = $ch;
}
//0-9不编码
foreach (range('0', '9') as $ch) {
HttpUtil::$PERCENT_ENCODED_STRINGS[ord($ch)] = $ch;
}
//以下4个字符不编码
HttpUtil::$PERCENT_ENCODED_STRINGS[ord('-')] = '-';
HttpUtil::$PERCENT_ENCODED_STRINGS[ord('.')] = '.';
HttpUtil::$PERCENT_ENCODED_STRINGS[ord('_')] = '_';
HttpUtil::$PERCENT_ENCODED_STRINGS[ord('~')] = '~';
}
//在uri编码中不能对'/'编码
public static function urlEncodeExceptSlash($path)
{
return str_replace("%2F", "/", HttpUtil::urlEncode($path));
}
//使用编码数组编码
public static function urlEncode($value)
{
$result = '';
for ($i = 0; $i < strlen($value); ++$i) {
$result .= HttpUtil::$PERCENT_ENCODED_STRINGS[ord($value[$i])];
}
return $result;
}
//生成标准化QueryString
public static function getCanonicalQueryString(array $parameters)
{
//没有参数,直接返回空串
if (count($parameters) == 0) {
return '';
}
$parameterStrings = array();
foreach ($parameters as $k => $v) {
//跳过Authorization字段
if (strcasecmp('Authorization', $k) == 0) {
continue;
}
if (!isset($k)) {
throw new \InvalidArgumentException(
"parameter key should not be null"
);
}
if (isset($v)) {
//对于有值的,编码后放在=号两边
$parameterStrings[] = HttpUtil::urlEncode($k)
. '=' . HttpUtil::urlEncode((string) $v);
} else {
//对于没有值的,只将key编码后放在=号的左边,右边留空
$parameterStrings[] = HttpUtil::urlEncode($k) . '=';
}
}
//按照字典序排序
sort($parameterStrings);
//使用'&'符号连接它们
return implode('&', $parameterStrings);
}
//生成标准化uri
public static function getCanonicalURIPath($path)
{
//空路径设置为'/'
if (empty($path)) {
return '/';
} else {
//所有的uri必须以'/'开头
if ($path[0] == '/') {
return HttpUtil::urlEncodeExceptSlash($path);
} else {
return '/' . HttpUtil::urlEncodeExceptSlash($path);
}
}
}
//生成标准化http请求头串
public static function getCanonicalHeaders($headers)
{
//如果没有headers,则返回空串
if (count($headers) == 0) {
return '';
}
$headerStrings = array();
foreach ($headers as $k => $v) {
//跳过key为null的
if ($k === null) {
continue;
}
//如果value为null,则赋值为空串
if ($v === null) {
$v = '';
}
//trim后再encode,之后使用':'号连接起来
$headerStrings[] = HttpUtil::urlEncode(strtolower(trim($k))) . ':' . HttpUtil::urlEncode(trim($v));
}
//字典序排序
sort($headerStrings);
//用'\n'把它们连接起来
return implode("\n", $headerStrings);
}
}
对接百度文档服务接口, 这里写了注册文档和阅读文档两个例子
namespace App\Service;
use GuzzleHttp\Client;
class BaiduDoc
{
protected $credentials = ['ak' => '', 'sk' => ''];
protected $host = 'doc.bj.baidubce.com';
protected $timestamp;
protected $expirationInSeconds = 60;
public function __construct()
{
HttpUtil::__init();
date_default_timezone_get('UTC');
$this->timestamp = new \DateTime();
}
/**
* 注册文档
* @return array|\Psr\Http\Message\StreamInterface
*/
public function register()
{
// >> first: get authorization
$method = 'POST';
$uri = '/v2/document' ;
$params = ['register' => ''];
$authorization = $this->getAuthorization($method, $this->host, $uri, $params, $this->timestamp, $this->expirationInSeconds);
// >> second: create header and body information for http request
$url = "https://{$this->host}{$uri}?register";
$timeStr = $this->timestamp->format("Y-m-d\TH:i:s\Z");
$head = [
"Content-Type" => "application/json",
"Authorization" => $authorization,
"x-bce-date" => $timeStr,
];
$body = [
'title' => '123',
'format' => 'doc',
];
$client = new Client();
$response = $client->request($method, $url, [
'body' => json_encode($body),
'headers' => $head
]);
$body = $response->getBody();
return $body;
}
/**
* 阅读文档
* @return array|\Psr\Http\Message\StreamInterface
*/
public function read()
{
// >> first: get authorization
$method = 'GET';
$documentId = 'doc-icukvvnfq6ixnat';
$uri = '/v2/document/'. $documentId;
$params = ['read' => ''];
$this->expirationInSeconds = 3600;
$authorization = $this->getAuthorization($method, $this->host, $uri, $params, $this->timestamp, $this->expirationInSeconds);
// >> second: create header and body information for http request
$url = "http://{$this->host}{$uri}?read";
$timeStr = $this->timestamp->format("Y-m-d\TH:i:s\Z");
$head = [
"Content-Type" => "application/json",
"Authorization" => $authorization,
"x-bce-date" => $timeStr,
];
$client = new Client();
$response = $client->request($method, $url, [
'headers' => $head
]);
$body = $response->getBody();
return $body;
}
// 获取认证字符串
protected function getAuthorization($method, $host, $uri, $params, $timestamp, $expirationInSeconds)
{
$timeStr = $timestamp->format("Y-m-d\TH:i:s\Z");
$authStringPrefix = "bce-auth-v1/{$this->credentials['ak']}/{$timeStr}/{$expirationInSeconds}";
$signingKey = hash_hmac('SHA256', $authStringPrefix, $this->credentials['sk']);
$canonicalHeader1 = "host;x-bce-date";
$canonicalHeader2 = "host:{$host}\n" . "x-bce-date:" . urlencode($timeStr);
$httpUtil = new HttpUtil();
$canonicalString = $httpUtil->getCanonicalQueryString($params);
$canonicalUri = $httpUtil->getCanonicalURIPath($uri);
$method = strtoupper($method);
$canonicalRequest = "{$method}\n{$canonicalUri}\n{$canonicalString}\n{$canonicalHeader2}";
$signature = hash_hmac('SHA256', $canonicalRequest, $signingKey);
$authorization = "bce-auth-v1/{$this->credentials['ak']}/{$timeStr}/{$expirationInSeconds}/{$canonicalHeader1}/{$signature}";
return $authorization;
}
}
百度DOC php,PHP对接百度文档服务DOC相关推荐
- R语言使用compareGroups包compareGroups函数生成表统计表、createTable函数创建二元表、并导出结果到文档(doc、csv、xlsx、pdf)
R语言使用compareGroups包compareGroups函数生成表统计表.createTable函数创建二元表.并导出结果到文档(doc.csv.xlsx.pdf) 目录 R语言使用compa ...
- 张洪斌 html css,网页设计与制作教学课件作者HTML+CSS+JavaScript张洪斌教学资源KC11120100008_设计文档课件.doc...
网页设计与制作教学课件作者HTML+CSS+JavaScript张洪斌教学资源KC11120100008_设计文档课件.doc <课程案例 --案例 图3-1 网站div结构布局示意图 3.2界 ...
- here文档 here doc EOF重定向
here文档 here doc EOF重定向 http://www.cnblogs.com/xiangzi888/archive/2012/03/24/2415077.html 在shell脚本程序 ...
- Java DOC 转换给 PDF 格式文档的代码
工作过程,把写代码过程经常用的代码片段备份一次,下面的代码段是关于Java DOC 转换给 PDF 格式文档的代码,应该对码农们有所用. import java.io.File; import jav ...
- 关于java代码中的注释问题。(类中方法的注释,我们一般都要写上这个方法的文档(doc),方法的参数也要有它的文档)
比如 /** * 显示人员信息列表 * @param userId 用户ID * @return return 返回用户列表 */ 这里面的汉子信息,也就是文档(doc)都不应该缺少,否则, ...
- python word转pdf linux_Linux下使用LibreOffice+python将doc/docx/wps格式的文档转成html/txt/docx等格式...
Linux下的word文档格式转换工具 最近接到一个需求,要将所有不同格式的文档(包括.doc/.docx/.wps)转成统一格式,如都转为.docx,或直接转为.html 或.txt.经调研后,发现 ...
- Discuz!x1.5实现在线文档(doc、ppt、pdf)播放
实现在线文档(doc.ppt.pdf).视频等全攻略 一直在弄个中医教学方面的网站,有很多资料想用于教学,有些资料又不想学员下载.于是一直关注如何实现在线文档的功能,在论坛里学习了一段时间,加上自己 ...
- Free Spire.Doc组件C# 读取Word文档中的文本内容
C# 读取Word文档中的文本内容 这篇文章将介绍如何使用C#和Free Spire.Doc组件读取Word文档中的文本内容.Free Spire.Doc提供了两种方法来读取Word文档中的内容,一种 ...
- Eolink征文活动---Eolink API文档服务的天才产品
实际上我并不是因为这次活动才知道Eolink,早在几年前,我就成为了Eolink的使用者,所以,这次征文活动我势在必行!本篇文章将会围绕我如何利用Eolink去解决项目问题进行展开讨论,大致分为以下内 ...
最新文章
- 13.最为经典的动态规划入门
- 移动**21*设置无法接通_七大新增时刻传奇!外服率先体验而国服暂时无法推出的粉传盘点+21赛季移动端首批精选上架!...
- Linux知识点复习
- Couldn‘t connect to session bus: Did not receive a reply. Possible causes include: the remote applic
- Java-二分查找算法
- java11模块化开发_【JDK 11】关于 Java 模块系统,看这一篇就够了
- 为什么我那么努力,模电还是学不懂?
- Debian下RPM包安装
- 【MATLAB技巧】——求解符号方程
- asp.net常见问题收集
- scrapy FormRequest
- 为什么中国企业海外营销都选择Facebook?
- avd已创建模拟手机 点击开始没反应_佳能微单开始降价,索尼、 尼康、 富士稳中有升……...
- 委托/事件/线程传参简单理解
- 【转】VMware虚拟机三种网络模式超详解
- python 宏定义_「Rust笔记」Rust之自定义宏写法
- Brother-MFC系列打印机 PDF双面打印设置
- 基于8086的16位键盘操作系统仿真设计-基于8086LCD1602显示仿真设计-基于8086的LED中文显示屏显示设计-基于8086方波锯齿波三角波发生器-基于8086的LED点阵汉字流水显示设计
- 云锁linux宝塔安装,宝塔面板安装云锁
- 微信小程序基础(一) 文件结构配置项