运维开发网

小程序中卡券开发的3个问题

运维开发网 https://www.qedev.com 2020-05-15 09:16 出处:网络
工作中,处理小程序和微信卡券,总结的3个点:access_token和api_ticket的全局存储、上传卡券素材(图片)、卡券的签名算法

工作中,处理小程序和微信卡券,总结的3个点:access_token和api_ticket的全局存储、上传卡券素材(图片)、卡券的签名算法

1. access_token写入文件中,做全局存储

private function getAccessToken() {
    // access_token 应该全局存储与更新,以下代码以写入到文件中做示例
    $data = json_decode($this->get_php_file("access_token.php"));// 优客小程已读取到app/下
    if ($data->expire_time < time()) {
      $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret";
      $res = json_decode($this->httpGet($url));
      $access_token = $res->access_token;
      if ($access_token) {
        $data->expire_time = time() + 7000;
        $data->access_token = $access_token;
        $this->set_php_file("access_token.php", json_encode($data));
      }
    } else {
      $access_token = $data->access_token;
    }
    return $access_token;
}

private function get_php_file($filename) {
   return trim(substr(file_get_contents($filename), 15));
}

private function set_php_file($filename, $content) { $fp = fopen($filename, "w");// w写入方式打开 fwrite($fp, "<?php exit();?>" . $content); fclose($fp); }

 

2.curl上传素材(图片)

//上传卡券图片素材
$url = "https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=".$token[‘access_token‘];
$img = ‘../attachment/‘.$data[‘logo‘];
$file = array("media"=> new CURLFile($img));// php5.5以上
$file = array("media"=> ‘@‘.$img);// php5.5以下
$wechat_logo = api_notice_increment($url,$file);
$wechat_logo = json_decode($wechat_logo,true);

 

3.微信JSSDK签名和微信卡券签名规则不一样

  // 这里参数的顺序要按照 key 值 ASCII 码升序排序
    // $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";//微信jssdk签名生成规则
    //微信卡券签名生成规则
    $sign[‘api_ticket‘] = $jsapiTicket;
    $sign[‘timestamp‘] = $timestamp;
    $sign[‘nonce_str‘] = $nonceStr;
    $sign[‘card_id‘] = $this->card_id;
    sort($sign, SORT_STRING);
    $string = ‘‘;
    foreach($sign as $v){
      $string.= $v;
    }

    $signature = sha1($string);

 

4.在小程序前端调用 wx.addCard()

wx.addCard({
   cardList: [
    {
      cardId: ‘pWG6R0_zV_nmXSPkg4Wy9mrOx2LA‘,
      cardExt: ‘{"nonce_str": "‘+data.data.nonceStr+‘", "timestamp": "‘+data.data.timestamp + ‘", "signature":"‘ + data.data.signature+‘"}‘
    }
   ],
   success(res) {
    console.log(res.cardList) // 卡券添加结果
   }
})

小程序中卡券开发的3个问题

0

精彩评论

暂无评论...
验证码 换一张
取 消