# 签名算法

&#x20;签名生成的通用步骤如下：

* 设所有发送或者接收到的数据为集合M，将集合M内非空参数值的参数按照参数名ASCII码从小到大排序（字典序），使用URL键值对的格式（即key1=value1\&key2=value2…）拼接成字符串stringA。
* 在stringA最后拼接上\&key={{app\_key}}得到stringSignTemp字符串，并对stringSignTemp进行MD5运算，得到sign值

特别注意以下重要规则：

* 参数名 ASCII 码从小到大排序（字典序）
* 参数名区分大小写

#### Demo

例如传递的参数如下：

```
app_id: 12345
amount_total: 1
out_trade_no: 123123123123

```

* 第一步：对参数按照key=value的格式，并按照参数名ASCII字典序排序如下

> app\_id=12345\&out\_trade\_no=123123123123\&amount\_total=1

* 第二步：对上一步中的字符串拼接\&key=密钥

> app\_id=12345\&out\_trade\_no=123123123123\&amount\_total=1\&key=xxxxxxxxx

* 第三步：对上一步中字符串取MD5值

> $sign = md5('app\_id=12345\&out\_trade\_no=123123123123\&amount\_total=1\&key=xxxxxxxxx');

#### 代码示例

php

```
// 签名方法
function sign(array $data, $key) {
    ksort($data);
    $sign = md5(urldecode(http_build_query($data)).'&key='.$key);
    return $sign;
}

// 用法示例
$data = [
    'app_id' => '12345',
    'amount_total' => 1,
    'out_trade_no' => '123123123123',
];

// 面包多支付 app_key
$key = 'xxxxxxxxxxx';

$sign = sign($data, $key);
```

python

```
# !/usr/bin/env Python3
# -*- coding: utf-8 -*-

import hashlib
from urllib.parse import urlencode,unquote
'''
签名算法
'''
# 签名算法
def sign(attributes, payjs_key):
    attributes_new = {k: attributes[k] for k in sorted(attributes.keys())}
    sign_str = "&".join(
        [f"{key}={attributes_new[key]}" for key in attributes_new.keys()]
    )
    return (
        hashlib.md5((sign_str + "&key=" + payjs_key).encode(encoding="utf-8"))
        .hexdigest()
    )

# 用法示例
data = {
    'app_id' : '12345',
    'amount_total' : 1,
    'out_trade_no' : '123123123123'
}

# 面包多支付 app_key
key = 'xxxxxxxxxxx'

sign = sign(data, key)
```

> 本文档参考 payjs 文档


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://doc.mbd.pub/api/qian-ming-suan-fa.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
