Skip to content

代码示例

PHP

PHP
<?php
$componentAppid = "";  // 开放平台提供的APPID
$componentSecret = ""; // 开放平台提供的AppSecret
$domain = "https://partner.isvapi.com/openapi"; // 正式环境域名

//请求接口
getComponentToken();
//getAuthorizerToken();
//getAuthUrl();

/**
 * 查询授权应用authorizer_access_token示例
 */
function getAuthorizerToken()
{
    global $componentAppid, $domain;
    $timestamp = time(); //发起请求时的时间戳(秒)

    $body = [
        'authorizer_appid' => 'wx1f5bef27cc9f956a',
        'return_component_token' => 1
    ];

    //获取签名
    $sign = genSign($timestamp, $body);
    $url = "$domain/wechat/get_authorizer_token?component_appid=$componentAppid&timestamp=$timestamp&sign=$sign";

    //发起请求
    $data = sendPostJson($url, $body);
    var_dump($data);
}

/**
 * 查询开放平台component_access_token示例
 */
function getComponentToken()
{
    global $componentAppid, $domain;
    $timestamp = time(); //发起请求时的时间戳(秒)

    //没有请求参数时
    $body = [];

    //获取签名
    $sign = genSign($timestamp, $body);
    $url = "$domain/wechat/get_component_token?component_appid=$componentAppid&timestamp=$timestamp&sign=$sign";

    //发起请求
    $data = sendPostJson($url, $body);
    var_dump($data);
}

/**
 * 获取授权链接
 */
function getAuthUrl()
{
    global $componentAppid, $domain;
    $timestamp = time(); //发起请求时的时间戳(秒)

    //没有请求参数时
    $body = [];

    //获取签名
    $sign = genSign($timestamp, $body);
    $url = "$domain/wechat/get_auth_url?component_appid=$componentAppid&timestamp=$timestamp&sign=$sign";

    //发起请求
    $data = sendPostJson($url, $body);
    var_dump($data);
}

/**
 * 生成签名
 * @param int $timestamp 时间戳
 * @param array $body 请求参数
 * @return string
 */
function genSign(int $timestamp, array $body)
{
    global $componentAppid, $componentSecret;
    $bodyMd5 = md5(genJsonBody($body));
    return md5("$componentAppid,$bodyMd5,$timestamp,$componentSecret");
}

/**
 * 生成Json格式的body
 * @param array $body
 * @return string
 */
function genJsonBody(array $body)
{
    return (count($body) > 0) ? json_encode($body, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) : '{}';
}

/**
 * 发送请求
 * @param string $url 请求地址
 * @param array $body 请求参数
 * @return array
 */
function sendPostJson(string $url, array $body)
{
    $body = genJsonBody($body);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json; charset=utf-8',
    ]);
    $resp = curl_exec($ch);
    curl_close($ch);

    echo PHP_EOL;
    echo "请求地址:" . $url . PHP_EOL;
    echo "请求参数:" . $body . PHP_EOL;
    echo "请求结果:" . $resp . PHP_EOL;
    echo PHP_EOL;

    return json_decode($resp, true);
}

Python

python
import time
import hashlib
import json
import requests

# 开放平台提供的APPID
componentAppid = ""
# 开放平台提供的AppSecret
componentSecret = ""
# 正式环境域名
domain = "https://partner.isvapi.com/openapi"


def get_authorizer_token():
    """
    查询授权应用authorizer_access_token示例
    """
    global componentAppid, domain
    # 发起请求时的时间戳(秒)
    timestamp = int(time.time())

    body = {
        'authorizer_appid': 'wx1f5bef27cc9f956a',
        'return_component_token': 1
    }

    # 获取签名
    sign = gen_sign(timestamp, body)
    url = f"{domain}/wechat/get_authorizer_token?component_appid={componentAppid}&timestamp={timestamp}&sign={sign}"

    # 发起请求
    send_post_json(url, body)
    # print(data)


def get_component_token():
    """
    查询开放平台component_access_token示例
    """
    global componentAppid, domain
    # 发起请求时的时间戳(秒)
    timestamp = int(time.time())

    # 没有请求参数时
    body = {}

    # 获取签名
    sign = gen_sign(timestamp, body)
    url = f"{domain}/wechat/get_component_token?component_appid={componentAppid}&timestamp={timestamp}&sign={sign}"

    # 发起请求
    data = send_post_json(url, body)
    # print(data)


def get_auth_url():
    """
    获取授权链接
    """
    global componentAppid, domain
    # 发起请求时的时间戳(秒)
    timestamp = int(time.time())

    # 没有请求参数时
    body = {}

    # 获取签名
    sign = gen_sign(timestamp, body)
    url = f"{domain}/wechat/get_auth_url?component_appid={componentAppid}&timestamp={timestamp}&sign={sign}"

    # 发起请求
    data = send_post_json(url, body)
    # print(data)


def gen_sign(timestamp, body):
    """
    生成签名
    :param timestamp: 时间戳
    :param body: 请求参数
    :return: 签名
    """
    global componentAppid, componentSecret
    body_md5 = hashlib.md5(gen_json_body(body).encode('utf-8')).hexdigest()
    sign_str = f"{componentAppid},{body_md5},{timestamp},{componentSecret}"
    return hashlib.md5(sign_str.encode('utf-8')).hexdigest()


def gen_json_body(body):
    """
    生成Json格式的body
    :param body: 请求参数
    :return: Json字符串
    """
    if body:
        return json.dumps(body, ensure_ascii=False, separators=(',', ':'))
    return '{}'


def send_post_json(url, body):
    """
    发送请求
    :param url: 请求地址
    :param body: 请求参数
    :return: 响应结果
    """
    body = gen_json_body(body)
    headers = {
        'Content-Type': 'application/json; charset=utf-8'
    }
    try:
        response = requests.post(url, data=body, headers=headers, verify=True)
        resp = response.text
    except requests.RequestException as e:
        resp = str(e)

    print(f"请求地址:{url}")
    print(f"请求参数:{body}")
    print(f"请求结果:{resp}")
    print()

    return response.json()


if __name__ == "__main__":
    # 请求接口
    get_component_token()
    # get_authorizer_token()
    # get_auth_url()

Java

java
package com.example;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

import com.google.gson.Gson;

public class WechatApiClient {
    // 开放平台提供的 APPID
    private static final String COMPONENT_APPID = "";
    // 开放平台提供的 AppSecret
    private static final String COMPONENT_SECRET = "";
    // 正式环境域名
    private static final String DOMAIN = "https://partner.isvapi.com/openapi";

    public static void main(String[] args) {
        // 请求接口
        getComponentToken();
        // getAuthorizerToken();
        // getAuthUrl();
    }

    /**
     * 查询授权应用 authorizer_access_token 示例
     */
    public static void getAuthorizerToken() {
        long timestamp = System.currentTimeMillis() / 1000;

        Map<String, Object> body = new HashMap<>();
        body.put("authorizer_appid", "wx1f5bef27cc9f956a");
        body.put("return_component_token", 1);

        // 获取签名
        String sign = genSign(timestamp, body);
        String url = DOMAIN + "/wechat/get_authorizer_token?component_appid=" + COMPONENT_APPID + "&timestamp=" + timestamp + "&sign=" + sign;

        // 发起请求
        String data = sendPostJson(url, body);
        System.out.println(data);
    }

    /**
     * 查询开放平台 component_access_token 示例
     */
    public static void getComponentToken() {
        long timestamp = System.currentTimeMillis() / 1000;

        // 没有请求参数时
        Map<String, Object> body = new HashMap<>();

        // 获取签名
        String sign = genSign(timestamp, body);
        String url = DOMAIN + "/wechat/get_component_token?component_appid=" + COMPONENT_APPID + "&timestamp=" + timestamp + "&sign=" + sign;

        // 发起请求
        String data = sendPostJson(url, body);
        System.out.println(data);
    }

    /**
     * 获取授权链接
     */
    public static void getAuthUrl() {
        long timestamp = System.currentTimeMillis() / 1000;

        // 没有请求参数时
        Map<String, Object> body = new HashMap<>();

        // 获取签名
        String sign = genSign(timestamp, body);
        String url = DOMAIN + "/wechat/get_auth_url?component_appid=" + COMPONENT_APPID + "&timestamp=" + timestamp + "&sign=" + sign;

        // 发起请求
        String data = sendPostJson(url, body);
        System.out.println(data);
    }

    /**
     * 生成签名
     *
     * @param timestamp 时间戳
     * @param body      请求参数
     * @return 签名
     */
    public static String genSign(long timestamp, Map<String, Object> body) {
        String bodyMd5 = md5(genJsonBody(body));
        return md5(COMPONENT_APPID + "," + bodyMd5 + "," + timestamp + "," + COMPONENT_SECRET);
    }

    /**
     * 生成 Json 格式的 body
     *
     * @param body 请求参数
     * @return Json 字符串
     */
    public static String genJsonBody(Map<String, Object> body) {
        Gson gson = new Gson();
        return body.isEmpty() ? "{}" : gson.toJson(body);
    }

    /**
     * 发送请求
     *
     * @param url  请求地址
     * @param body 请求参数
     * @return 请求结果
     */
    public static String sendPostJson(String url, Map<String, Object> body) {
        String jsonBody = genJsonBody(body);
        StringBuilder response = new StringBuilder();

        try {
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            con.setRequestMethod("POST");
            con.setRequestProperty("Content-Type", "application/json; charset=utf-8");
            con.setDoOutput(true);

            try (OutputStream os = con.getOutputStream()) {
                byte[] input = jsonBody.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            try (BufferedReader br = new BufferedReader(
                    new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8))) {
                String responseLine;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine.trim());
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("请求地址:" + url);
        System.out.println("请求参数:" + jsonBody);
        System.out.println("请求结果:" + response.toString());
        System.out.println();

        return response.toString();
    }

    /**
     * 生成 MD5 哈希值
     *
     * @param input 输入字符串
     * @return MD5 哈希值
     */
    public static String md5(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageDigest = md.digest(input.getBytes());
            StringBuilder hexString = new StringBuilder();
            for (byte b : messageDigest) {
                String hex = Integer.toHexString(0xFF & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }
}

Go

go
package main

import (
    "crypto/md5"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
    "strings"
    "time"
)

// 开放平台提供的 APPID
const componentAppid = ""
// 开放平台提供的 AppSecret
const componentSecret = ""
// 正式环境域名
const domain = "https://partner.isvapi.com/openapi"

func main() {
    // 请求接口
    getComponentToken()
    getAuthorizerToken()
    getAuthUrl()
}

// 查询授权应用 authorizer_access_token 示例
func getAuthorizerToken() {
    timestamp := time.Now().Unix()

    body := map[string]interface{}{
        "authorizer_appid":       "wx1f5bef27cc9f956a",
        "return_component_token": 1,
    }

    // 获取签名
    sign := genSign(timestamp, body)
    url := fmt.Sprintf("%s/wechat/get_authorizer_token?component_appid=%s&timestamp=%d&sign=%s", domain, componentAppid, timestamp, sign)

    // 发起请求
    data := sendPostJson(url, body)
    fmt.Println(data)
}

// 查询开放平台 component_access_token 示例
func getComponentToken() {
    timestamp := time.Now().Unix()

    // 没有请求参数时
    body := map[string]interface{}{}

    // 获取签名
    sign := genSign(timestamp, body)
    url := fmt.Sprintf("%s/wechat/get_component_token?component_appid=%s&timestamp=%d&sign=%s", domain, componentAppid, timestamp, sign)

    // 发起请求
    data := sendPostJson(url, body)
    fmt.Println(data)
}

// 获取授权链接
func getAuthUrl() {
    timestamp := time.Now().Unix()

    // 没有请求参数时
    body := map[string]interface{}{}

    // 获取签名
    sign := genSign(timestamp, body)
    url := fmt.Sprintf("%s/wechat/get_auth_url?component_appid=%s&timestamp=%d&sign=%s", domain, componentAppid, timestamp, sign)

    // 发起请求
    data := sendPostJson(url, body)
    fmt.Println(data)
}

// 生成签名
func genSign(timestamp int64, body map[string]interface{}) string {
    bodyMd5 := md5Hash(genJsonBody(body))
    signStr := fmt.Sprintf("%s,%s,%d,%s", componentAppid, bodyMd5, timestamp, componentSecret)
    return md5Hash(signStr)
}

// 生成 Json 格式的 body
func genJsonBody(body map[string]interface{}) string {
    if len(body) == 0 {
        return "{}"
    }
    jsonData, err := json.Marshal(body)
    if err != nil {
        fmt.Println("JSON 编码错误:", err)
        return "{}"
    }
    return string(jsonData)
}

// 发送请求
func sendPostJson(url string, body map[string]interface{}) string {
    jsonBody := genJsonBody(body)
    req, err := http.NewRequest("POST", url, nil)
    if err != nil {
        fmt.Println("创建请求错误:", err)
        return ""
    }
    req.Header.Set("Content-Type", "application/json; charset=utf-8")
    req.Body = io.NopCloser(strings.NewReader(jsonBody))

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        fmt.Println("发送请求错误:", err)
        return ""
    }
    defer resp.Body.Close()

    respBody, err := io.ReadAll(resp.Body)
    if err != nil {
        fmt.Println("读取响应错误:", err)
        return ""
    }

    fmt.Println()
    fmt.Println("请求地址:", url)
    fmt.Println("请求参数:", jsonBody)
    fmt.Println("请求结果:", string(respBody))
    fmt.Println()

    return string(respBody)
}

// 生成 MD5 哈希值
func md5Hash(input string) string {
    hash := md5.Sum([]byte(input))
    return fmt.Sprintf("%x", hash)
}

Javascript

javascript
const axios = require('axios');
const crypto = require('crypto');

// 开放平台提供的 APPID
const componentAppid = "";
// 开放平台提供的 AppSecret
const componentSecret = "604cf7409d1ace34a1fb8226cef89c30";
// 正式环境域名
const domain = "https://partner.isvapi.com/openapi";

// 请求接口
getComponentToken();
getAuthorizerToken();
getAuthUrl();

/**
 * 查询授权应用 authorizer_access_token 示例
 */
async function getAuthorizerToken() {
    const timestamp = Math.floor(Date.now() / 1000);

    const body = {
        authorizer_appid: 'wx1f5bef27cc9f956a',
        return_component_token: 1
    };

    // 获取签名
    const sign = genSign(timestamp, body);
    const url = `${domain}/wechat/get_authorizer_token?component_appid=${componentAppid}&timestamp=${timestamp}&sign=${sign}`;

    // 发起请求
    const data = await sendPostJson(url, body);
    // console.log(data);
}

/**
 * 查询开放平台 component_access_token 示例
 */
async function getComponentToken() {
    const timestamp = Math.floor(Date.now() / 1000);

    // 没有请求参数时
    const body = {};

    // 获取签名
    const sign = genSign(timestamp, body);
    const url = `${domain}/wechat/get_component_token?component_appid=${componentAppid}&timestamp=${timestamp}&sign=${sign}`;

    // 发起请求
    const data = await sendPostJson(url, body);
    // console.log(data);
}

/**
 * 获取授权链接
 */
async function getAuthUrl() {
    const timestamp = Math.floor(Date.now() / 1000);

    // 没有请求参数时
    const body = {};

    // 获取签名
    const sign = genSign(timestamp, body);
    const url = `${domain}/wechat/get_auth_url?component_appid=${componentAppid}&timestamp=${timestamp}&sign=${sign}`;

    // 发起请求
    const data = await sendPostJson(url, body);
    // console.log(data);
}

/**
 * 生成签名
 * @param {number} timestamp 时间戳
 * @param {object} body 请求参数
 * @returns {string}
 */
function genSign(timestamp, body) {
    const bodyMd5 = md5(genJsonBody(body));
    return md5(`${componentAppid},${bodyMd5},${timestamp},${componentSecret}`);
}

/**
 * 生成 Json 格式的 body
 * @param {object} body
 * @returns {string}
 */
function genJsonBody(body) {
    return Object.keys(body).length > 0 ? JSON.stringify(body) : '{}';
}

/**
 * 发送请求
 * @param {string} url 请求地址
 * @param {object} body 请求参数
 * @returns {Promise<object>}
 */
async function sendPostJson(url, body) {
    const jsonBody = genJsonBody(body);
    try {
        const response = await axios.post(url, jsonBody, {
            headers: {
                'Content-Type': 'application/json; charset=utf-8'
            },
            httpsAgent: new (require('https').Agent)({
                rejectUnauthorized: false
            })
        });

        console.log();
        console.log(`请求地址:${url}`);
        console.log(`请求参数:${jsonBody}`);
        console.log(`请求结果:${JSON.stringify(response.data)}`);
        console.log();

        return response.data;
    } catch (error) {
        console.log();
        console.log(`请求地址:${url}`);
        console.log(`请求参数:${jsonBody}`);
        console.log(`请求结果:${error.message}`);
        console.log();

        return null;
    }
}

/**
 * 生成 MD5 哈希值
 * @param {string} input 输入字符串
 * @returns {string} MD5 哈希值
 */
function md5(input) {
    return crypto.createHash('md5').update(input).digest('hex');
}