微信公众号 JSSDK 配置参数生成示例

249次阅读
没有评论

微信官方开发文档:

https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html

<?php

function wx_jump(){
    // 自定义函数,获取当前请求 url
    $url = get_url();  

    $appid = 'wx7d87b13cee****'; // 公众号 appid
    $secret = 'e2dd8b944d9ea8b0490****af4'; // 公众号 secret

    // 1. 获取 access_token
    $api = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret;
    $res = file_get_contents($api);
    $token = json_decode($res,true); // {"access_token":"ACCESS_TOKEN","expires_in":7200}


    // 2. 获取 jsapi_ticket
    $api = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='.$token['access_token'].'&type=jsapi';
    $res = file_get_contents($api);
    $ticket = json_decode($res,true); // {"errcode":0,"errmsg":"ok","ticket":"bxLdikRXVbTPdHSM05e5u5sUoXNKd8-41ZO3MhKoyN5OfkWITDGgnr2fwJ0m9E8NYzWKVZvdVtaUgWvsdshFKA","expires_in":7200}


    $timestamp = time();
    $noncestr = random_string(32); // 自定义函数,生成长度为 32 的随机字符串

    // 3. 生成验签参数
    $str = "jsapi_ticket={$ticket['ticket']}&noncestr={$noncestr}&timestamp={$timestamp}&url={$url}";
    $signature = sha1($str);

    // 4. 组装返回 jssdk 参数
    $data = [
        'appId'=>$appid,
        'timestamp'=>$timestamp,
        'nonceStr'=>$noncestr,
        'signature'=>$signature
    ];

    return $data;
}

$data = wx_jump();

?>

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
</head>
<body>

<script>
    wx.config({
        debug: true, // 开启调试模式, 调用的所有 api 的返回值会在客户端 alert 出来,若要查看传入的参数,可以在 pc 端打开,参数信息会通过 log 打出,仅在 pc 端时才会打印
        appId: '<?php echo $data['appId']; ?>', // 必填,公众号的唯一标识
        timestamp: '<?php echo $data['timestamp']; ?>', // 必填,生成签名的时间戳
        nonceStr: '<?php echo $data['nonceStr']; ?>, // 必填,生成签名的随机串
        signature: '<?php echo $data['signature']; ?>, // 必填,签名
        jsApiList: ["chooseImage"], // 必填,需要使用的 JS 接口列表(此处随意一个接口即可)openTagList: ["wx-open-launch-weapp"], // 可选,需要使用的开放标签列表,例如 ['wx-open-launch-app']
    });
    
    //  其他 wx jssdk 接口调用代码
</script>
</body>
</html>
正文完
有偿技术支持加微信
post-qrcode
 
评论(没有评论)
验证码