优化示例代码 (#777)

* Remove escape character

移除此处多余的转义符

* Optimize sample code

Object.assign 方法本身会改变 object,没有必要再赋值

* Optimize sample code

* Update docs/misc/sign/wbi.md

Co-authored-by: ud2 <sjx233@qq.com>

---------

Co-authored-by: ud2 <sjx233@qq.com>
This commit is contained in:
188102836 2023-08-13 20:31:31 +08:00 committed by GitHub
parent 64c653a6c1
commit 542359a54f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -192,7 +192,7 @@ bar=514&baz=1919810&foo=114&wts=1684746387&w_rid=d3cbd2a2316089117134038bf4caf44
### JavaScript ### JavaScript
需要`axios`、`md5`依赖 需要 `axios`、`md5` 依赖
```javascript ```javascript
import md5 from 'md5' import md5 from 'md5'
@ -218,16 +218,16 @@ function getMixinKey(orig) {
function encWbi(params, img_key, sub_key) { function encWbi(params, img_key, sub_key) {
const mixin_key = getMixinKey(img_key + sub_key), const mixin_key = getMixinKey(img_key + sub_key),
curr_time = Math.round(Date.now() / 1000), curr_time = Math.round(Date.now() / 1000),
chr_filter = /[!'\(\)*]/g chr_filter = /[!'()*]/g
let query = [] let query = []
params = Object.assign(params, {wts: curr_time}) // 添加 wts 字段 Object.assign(params, { wts: curr_time }) // 添加 wts 字段
// 按照 key 重排参数 // 按照 key 重排参数
Object.keys(params).sort().forEach((key) => { Object.keys(params).sort().forEach((key) => {
query.push( query.push(
encodeURIComponent(key) + `${encodeURIComponent(key)}=${encodeURIComponent(
'=' + // 过滤 value 中的 "!'()*" 字符
// 过滤 value 中的 "!'()*" 字符 params[key].toString().replace(chr_filter, '')
encodeURIComponent(('' + params[key]).replace(chr_filter, '')) )}`
) )
}) })
query = query.join('&') query = query.join('&')
@ -245,24 +245,31 @@ async function getWbiKeys() {
json_content = resp.data, json_content = resp.data,
img_url = json_content.data.wbi_img.img_url, img_url = json_content.data.wbi_img.img_url,
sub_url = json_content.data.wbi_img.sub_url sub_url = json_content.data.wbi_img.sub_url
return { return {
img_key: img_url.substring(img_url.lastIndexOf('/') + 1, img_url.length).split('.')[0], img_key: img_url.slice(
sub_key: sub_url.substring(sub_url.lastIndexOf('/') + 1, sub_url.length).split('.')[0] img_url.lastIndexOf('/') + 1,
img_url.lastIndexOf('.')
),
sub_key: sub_url.slice(
sub_url.lastIndexOf('/') + 1,
sub_url.lastIndexOf('.')
)
} }
} }
const wbi_keys = await getWbiKeys() getWbiKeys().then((wbi_keys) => {
const query = encWbi(
const query = encWbi( {
{ foo: '114',
foo: '114', bar: '514',
bar: '514', baz: 1919810
baz: 1919810 },
}, wbi_keys.img_key,
wbi_keys.img_key, wbi_keys.sub_key
wbi_keys.sub_key )
) console.log(query)
console.log(query) })
``` ```
输出内容为进行 Wbi 签名的后参数的 url query 形式 输出内容为进行 Wbi 签名的后参数的 url query 形式
@ -592,4 +599,4 @@ public class WbiTest {
System.out.println(finalParam); System.out.println(finalParam);
} }
} }
``` ```