美文网首页我爱编程
微信JS-SDK投放卡券_踩过的坑

微信JS-SDK投放卡券_踩过的坑

作者: liangxifeng833 | 来源:发表于2018-04-15 16:03 被阅读1676次

微信对于卡券签名规则说的不准确,并且微信自己的签名算法工具:https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=cardsign,签名的顺序是错误的,微信对于这部分的文档,多处说明不一致,所以自己总结如下:

一.概念

  • 属于微信网页开发;
  • 在h5页面中使用js方式,调用微信微信js-sdk包中的批量添加卡券接口;
  • 也就是使用h5的方式投放卡券;
  • 什么是自定义code,什么是预存code模式,什么是可导入code,请查看我的另一篇文章:自定义code卡券

二.准备工作

  • 先登录微信公众平台进入“公众号设置”的“功能设置”里填写“JS接口安全域名”。
    备注:登录后可在“开发者中心”查看对应的接口权限。


    image.png
  • 下载 MP_verify_....txt到开发者服务器;

三.调用微信js-sdk接口

  • 在前台页面通过config接口注入权限验证配置(签名),页面初始化触发
    sample.php内容
  |<?php     
 //加载签名php文件
@|require_once "jssdk.php";
@|$jssdk = new JSSDK("appid", "appsecret");                                        
@|$signPackage = $jssdk->getSignPackage(1);                                                                            
@|?>
@|<!DOCTYPE html>
@|<html lang="en">
@|<head>
@|  <meta charset="UTF-8">
@|  <title>js-sdk-测试</title>
@|  <!-- 添加适应手机端 -->                                                                                            
@|  <meta name="viewport" content="width=device-width,initital-scale-1">                                               
@|</head>
@|<body>                                                                  
@|    <button id="addCard">添加卡券到卡包</button>
@|</body>
@|<script src="https://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>                                               
@|<script>
@|  wx.config({                                                                                                        
@|    debug: true,
@|    appId: '<?php echo $signPackage["appId"];?>',  // 必填,公众号的唯一标识                                                                   
@|    timestamp: <?php echo $signPackage["timestamp"];?>,   // 必填,生成签名的时间戳                                                           
@|    nonceStr: '<?php echo $signPackage["nonceStr"];?>',// 必填,生成签名的随机串
@|    signature: '<?php echo $signPackage["signature"];?>',// 必填,签名
@|    jsApiList: [
@|      // 所有要调用的 API 都要加到这个列表中                                                                         
@|        'addCard' //批量添加卡券接口
@|    ]
@|  });
  //通过ready接口处理成功验证,调用具体的sdk接口
   wx.ready(function () {                                                                                             
@|      //添加卡券到卡包                                                                                               
@|      document.getElementById("addCard").onclick = function()                                                        
@|      {                                                                                                              
@|         alert("添加卡券");                                                                                          
@|          <?php                                                                                                      
@|          //$cardArr['cardId'] = 'pNKvmjugBuDfpV8FyiK9BrFPSvLs';                                                     
@|          $cardArr['cardId'] = 'pNKvmjpkxUXWAtHxdjbE8dvFzNP4';                                                       
@|          $cardArr['code'] = '123456';                                                                               
@|          //微信卡券签名                                                                                             
@|          $cardSign = $jssdk->getSignPackage(2,$cardArr);                                                            
@|          $timestamp = $cardSign["timestamp"];                                                                       
@|          $signature = $cardSign["signature"];                                                                       
@|          $nonceStr = $cardSign["nonceStr"];                                                                         
@|          ?>                                                                                                         
@|          wx.addCard({                                                                                               
@|              cardList:[                                                                                             
@|                  {                                                                                                  
@|                        cardId: 'pNKvmjpkxUXWAtHxdjbE8dvFzNP4',                                                      
@|                        cardExt: '{"code":"123456","timestamp":"<?php  echo $timestamp;?>","signature":"<?php echo $s
@|ignature;?>","nonce_str":"<?php echo $nonceStr;?>"}'                                                                 
@|                  }                                                                                                  
@|              ],                                                                                                     
@|              success: function (res) {                                                                              
@|                          alert('已添加卡券:' + JSON.stringify(res.cardList));                                      
@|              },                                                                                                     
@|              cancel: function (res) {                                                                               
@|                          alert("用户点击取消:"+JSON.stringify(res))                                                 
@|              },                                                                                                     
|              fail: function(res){                                                                                   
@|                  alert("调用失败"+JSON.stringify(res))                                                              
@|              }                                                                                                      
@|          });                                                                                                        
@|      } 
     })
</script>
<html>
  • 以上微信卡券签名:
 $cardArr['cardId'] = 'pNKvmjpkxUXWAtHxdjbE8dvFzNP4';                                                       
          $cardArr['code'] = '123456';   
          $cardSign = $jssdk->getSignPackage(2,$cardArr);                                                            
         $timestamp = $cardSign["timestamp"];                                                                       
         $signature = $cardSign["signature"];                                                                       
          $nonceStr = $cardSign["nonceStr"];                                                                         
         ?>

 cardId: 'pNKvmjpkxUXWAtHxdjbE8dvFzNP4',                                                                                                 
 cardExt: '{"code":"123456","timestamp":"<?php  echo $timestamp;?>","signature":"<?php echo $signature;?>","nonce_str":"<?php echo $nonceStr;?>"}

要保持code和cardId一致,并且cardExt=字符串方式,在卡券创建时候使用的是预存或非自定义code的时候,code参数无需指定,否则签名失败

四.签名说明

  • 本例中在 jssdk.php中做的签名(也是官方的demo)
  • 我在签名方法 getSignPackage中添加了两个参数,type=1:普通js_sdk,2:微信卡券js_sdk,
  • 因为调用微信js-sdk卡券接口,需要有额外的签名,也就是说调用普通的js-sdk接口只需要在页面初始化的时候使用wx.config签名即可,但是如果调用js-sdk微信卡券接口,需要在调用的时候做一次针对微信卡券接口的签名;
  • 所以调用微信js-sdk卡券接口,需要做两次签名
    第一次:js-sdk签名
    第二次:微信卡券js-sdk签名
    因为两次的签名算法不一样
  1 <?php                                                                                         
  2 class JSSDK {                                                                                 
  3   private $appId;                                                                             
  4   private $appSecret;                                                                         
  5                                                                                               
  6   public function __construct($appId, $appSecret) {                                           
  7     $this->appId = $appId;                                                                    
  8     $this->appSecret = $appSecret;                                                            
  9   }                                                                                           
 10                                                                                               
 11   /**                                                                                         
 12   * type 1:普通js_sdk,2:微信卡券js_sdk                                                        
 13   */                                                                                          
 14   public function getSignPackage($type,$cardArrs=array()) {                                   
 15     $jsapiTicket = $this->getJsApiTicket($type);                                              
 16                                                                                               
 17     // 注意 URL 一定要动态获取,不能 hardcode.                                                
 18     $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "httt
    ps://" : "http://";
 19     $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";                               
 20                                                                                               
 21     $timestamp = time();                                                                      
 22     $nonceStr = $this->createNonceStr();                                                      
 23                                                                                               
 24     if($type==1)                                                                              
 25     {                                                                                         
 26         // 普通js-jsk签名规则                                   
 27         $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
 28     }else                                                                                     
 29     {
30         // 微信卡券接口签名规,自定义code,无需导入自定义code
 31         $string = $cardArrs['code'].$timestamp.$nonceStr.$jsapiTicket.$cardArrs['cardId'];
     // 微信卡券接口签名规,自定义code(预存模式)或非自定义code
 32         //$string = $timestamp.$nonceStr.$jsapiTicket.$cardArrs['cardId'];
 33     }
 34 
 35     $signature = sha1($string);
 36 
 37     $signPackage = array(
 38       "appId"     => $this->appId,
 39       "nonceStr"  => $nonceStr,
 40       "timestamp" => $timestamp,
 41       "url"       => $url,
 42       "signature" => $signature,
 43       "rawString" => $string
 44     );
 45     return $signPackage;
 46   }
 47 
 48   private function createNonceStr($length = 16) {
 49     $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
 50     $str = "";
 51     for ($i = 0; $i < $length; $i++) {
 52       $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
 53     }
 54     return $str;
 55   }
 56   //type=1获取普通js-sdk的jsapi_ticket,存放到jsapi_ticket.php中
      //type=2获取微信卡券js-sdk的api_ticket,存放到wxcardapi_ticket.php中
 57   private function getJsApiTicket($type) {
 58     if($type == 1)
 59     {
60          $typeNew = "jsapi";
 61          $phpFile = "jsapi_ticket.php";
 62     }else
 63     {
 64          $typeNew = "wx_card";
 65          $phpFile = "wxcardapi_ticket.php";
 66     }
 67     // jsapi_ticket 应该全局存储与更新,以下代码以写入到文件中做示例
 68     $data = json_decode($this->get_php_file($phpFile));
 69     if ($data->expire_time < time()) {
 70       $accessToken = $this->getAccessToken();
 71       // 如果是企业号用以下 URL 获取 ticket
 72       // $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken";
 73       $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=".$typeNew."&access_token=$accessToken";
 74 
 75 /*
 76         if($type==2)
 77         {
 78                 echo $url;
 79         }
 80 */
 81       $res = json_decode($this->httpGet($url));
 82       $ticket = $res->ticket;
 83       if ($ticket) {
 84         $data->expire_time = time() + 7000;
 85         $data->jsapi_ticket = $ticket;
 86         $this->set_php_file($phpFile, json_encode($data));
 87       }
 88     } else {
89       $ticket = $data->jsapi_ticket;
 90     }
 91 
 92     return $ticket;
 93   }
 94 
 95   private function getAccessToken() {
 96     // access_token 应该全局存储与更新,以下代码以写入到文件中做示例
 97     $data = json_decode($this->get_php_file("access_token.php"));
 98     if ($data->expire_time < time()) {
 99       // 如果是企业号用以下URL获取access_token
100       // $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->appId&corpsecret=$this->appSecret";
101       $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this--
    >appSecret";
102       $res = json_decode($this->httpGet($url));
103       $access_token = $res->access_token;
104       if ($access_token) {
105         $data->expire_time = time() + 7000;
106         $data->access_token = $access_token;
107         $this->set_php_file("access_token.php", json_encode($data));
108       }
109     } else {
110       $access_token = $data->access_token;
111     }
112     return $access_token;
113   }
114 
115     function httpGet($url, $data = null)
116     {
117         $curl = curl_init();
118         curl_setopt($curl, CURLOPT_URL, $url);
119         curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
120         curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
121         if (!empty($data))//data非空 则是post请求
122         {
123             curl_setopt($curl, CURLOPT_POST, 1);
124             curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
125         }
126         curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
127         $output = curl_exec($curl);
128         curl_close($curl);
129         return $output;
130     }
131 
132   private function get_php_file($filename) {
133     return trim(substr(file_get_contents($filename), 15));
134   }
135   private function set_php_file($filename, $content) {
136     $fp = fopen($filename, "w");
137     fwrite($fp, "<?php exit();?>" . $content);
138     fclose($fp);
139   }
140 }

签名不稳定

  • 使用以上方式签名通过后,应用到自己的开发项目中,发现在调用wx.addCard,接口的时候,偶尔出现"签名错误"的情况,同样的配置,同样的代码,测试10次,大概会出现4-5次的"签名错误";

  • 我们的页面有很多卡券,如下:


    image.png
  • 我们签名方式试了两种:

    • 第一:每点击一次 "领券" 签名一次;
      只要满足创建卡券时候每个用户可领张数,用户就可以重复的点击领取;
    • 第二:在页面初始化的时候,将该页面中所有卡券循环签名;
      用户在该页面每中卡券只能领取一次,再次点击会提示"已领取",如果想再次领取,则必须刷新当前页面,统一再次签名一次;
  • "签名错误" 这个不稳定问题,目前还没有解决;

总结

  • 微信网页jsapi_ticket和微信卡券api_ticket不同,获取方式分别是:

    //微信网页jsapi_ticket
    https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken
    //微信卡券api_ticket
    https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=wx_card&access_token=$accessToken
    
  • 调用微信卡券js-sdk需要两次签名
    第一次普通js-sdk签名规则:

        //jssdTiken+随机字符串+时间戳+本页面url
        $string = "sapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url"
        sha1($string)
    

    第二次微信卡券js-sdk签名规则:

        //自定义code,无需导入自定义code
        //sha1(code码+时间戳+随机串+卡券apiTicket+cardId)
        $string = "$cardArrs['code'].$timestamp.$nonceStr.$jsapiTicket.$cardArrs['cardId'];"
        sha1($string)
        //如果是自定义code(预存模式)或非自定义code,无需传入code
        //sha1(时间戳+随机串+卡券apiTicket+cardId)
        //$string = "$timestamp.$nonceStr.$jsapiTicket.$cardArrs['cardId'];"
        sha1($string)
    
  • 微信卡券签名或参数错误请查看文档:https://mp.weixin.qq.com/s/WhYpWmfuhUBw2wseTXdt2A

  • 点击查看测试代码

相关文章

  • 微信JS-SDK投放卡券_踩过的坑

    微信对于卡券签名规则说的不准确,并且微信自己的签名算法工具:https://mp.weixin.qq.com/de...

  • 小程序微信卡券

    最近做的小程序项目需要打通微信会员卡模块,就仔细研究了卡券这一块,踩了很多的坑,网上能查到的东西也是比较少,因此在...

  • 微信js-sdk踩坑集合

    总算没事了,打算自己弄个公众号,在wx.config的时候一直报invalid signature,我弄这个的时候...

  • 自定义code卡券

    一.概念 自定义code卡券 = 卡券上的码是商户自己生成,与微信无关; 二.创建自定义卡券 点击查看微信创建卡券...

  • 2021-05-12

    微信分享跳转2次,微信分享跳转微信正在连接,分享微信没反应 这几天搞微信分享,还是有一些坑在里面的,记录踩过的坑;...

  • 微信卡券 H5 投放卡券 Java 代码

    java 代码 js public StringwxCard(String cardId){ String url...

  • 微信开发踩过的坑

    微信浏览器的缓存 可怕的页面缓存,微信中点后退不会重新发请求,但页面却会重新渲染,应该是从缓存中加载了,导致一些异...

  • 微信支付 code -2 首查位置推荐

    前言 说到微信相关,相信很多开发者都或多或少的踩过坑,如果没有记录甚至很容易二次踩坑,特此记录,留作纪念 ,嘿嘿...

  • 一、创建卡券

    创建卡券分两种: 定向卡券:将卡券发给已经微信注册的指定人 不定向卡券:将卡券插入在图文,任意人进入图文就可以领取...

  • 微信开发--配置篇

    近段时间在做微信相关开发,因为之前做的笔记丢失,原来踩过的坑又踩了一遍,所以这次准备记录下来,避免以后重复踩坑,本...

网友评论

    本文标题:微信JS-SDK投放卡券_踩过的坑

    本文链接:https://www.haomeiwen.com/subject/gavdkftx.html