收藏
回答

微信支付native接入问题,一直报401

Python写的代码,用官网的验签工具是正确的,但一直报401:代码如下:

def generate_signature(timestamp, nonce_str, body):
        signature_string = f"GET\n/v3/certificates\n{timestamp}\n{nonce_str}\n{body}\n"
    hash_message = SHA256.new(signature_string.encode('utf-8'))
    signature = pkcs1_15.new(private_key_pem).sign(hash_message)
    
    return base64.b64encode(signature).decode('utf-8')
  
  
@app.route('/api/v0/create-order', methods=['POST'])
def create_order():
    result = request.json
    data = result.get('data')
    print('data:', data)

    description = data['description']
    out_trade_no = data['out_trade_no']
    total_fee = data['total_fee']


    # 构建请求参数
    params = {
        "appid": os.getenv('APP_ID'),
        "mchid": os.getenv('MCH_ID'),
        "description": description,
        "out_trade_no": out_trade_no,
        "notify_url": os.getenv('NOTIFY_URL'),
        "amount": {
            "total": total_fee,
            "currency": "CNY"
        }
    }

    # 生成请求头
    timestamp = str(int(time.time()))
    nonce_str = generate_nonce_str()
    body=''
    signature = generate_signature(timestamp, nonce_str, body)

    # print('signature:', signature)

    headers = {
        "Authorization": f"WECHATPAY2-SHA256-RSA2048 mchid=\"{os.getenv('MCH_ID')}\",nonce_str=\"{nonce_str}\",signature=\"{signature}\",timestamp=\"{timestamp}\",serial_no=\"{os.getenv('CERT_SERIAL_NO')}\"",
        "Accept": "application/json",
        "Content-Type": "application/json"
    }

    # 发送请求
    response = requests.post('https://api.mch.weixin.qq.com/v3/pay/transactions/native', headers=headers, data=json.dumps(params))

    print('weixin_response:', response)

    if response.status_code == 200:
        code_url = response.json().get('code_url')
        order_status[out_trade_no] = '待支付'
        print('code_url:', code_url)
        return jsonify({'code_url': code_url, 'out_trade_no': out_trade_no,'code': 200}), 200
    else:
        print('创建订单失败:', response.json)
        return jsonify({'error': '创建订单失败', 'response': response.json(),'code': 500}), 500


回答关注问题邀请回答
收藏

1 个回答

  • Memory
    Memory
    09-27

    09-27
    有用
    回复
登录 后发表内容