365体育备用网址报道16.7.1HTML5网页领取卡券_365体育备用网址官网资讯

HTML5中领取卡券是微信JS SDK接口的一个功能。在生成卡券ID之后,将其传入到HTML5页面中,再使用JS SDK接口来进行领取。

首先定义微信jssdk的类文件

<?PHP

/*
    方倍工作室 http://www.fangbei.org/
    CopyRight 2014 All Rights Reserved
*/

/*
    require_once('weixin.class.php');
    $weixin = new class_weixin();
*/
header("Content-type: text/html; charset=utf-8");
define('APPID',         "wx6bf29f1cb0633d2f"); 
define('APPSECRET',     "");



class class_weixin
{
    var $appid = APPID;
    var $appsecret = APPSECRET;

    //构造函数,猎取Access Token
    public function __construct($appid = NULL, $appsecret = NULL)
    {
        if($appid && $appsecret){
            $this->appid = $appid;
            $this->appsecret = $appsecret;
        }

   

        //3. 本地写入
        $res = file_get_contents('access_token.json');
        $result = json_decode($res, true);
        $this->expires_time = $result["expires_time"];
        $this->access_token = $result["access_token"];

        if (time() > ($this->expires_time + 3600)){
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->appid."&secret=".$this->appsecret;
            $res = $this->http_request($url);
            $result = json_decode($res, true);
            $this->access_token = $result["access_token"];
            $this->expires_time = time();
            file_put_contents('access_token.json', '{"access_token": "'.$this->access_token.'", "expires_time": '.$this->expires_time.'}');
        }

    }


    /*
    *  PART4 JS SDK 签名
    *  PHP仅用于获得签名包,需要配合js一起使用
    */
    // require_once('weixin.class.php');
    // $weixin = new class_weixin();
    // $signPackage = $weixin->GetSignPackage();

    //生成长度16的随机字符串
    public function createNonceStr($length = 16) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }
	
    //获得微信卡券api_ticket
    public function getCardApiTicket()
    {

		
        //2. 写文件,有改动,待测验 20150430
        $res = file_get_contents('cardapi_ticket.json');
        $result = json_decode($res, true);
        $this->cardapi_ticket = $result["cardapi_ticket"];
        $this->cardapi_expire = $result["cardapi_expire"];

        if (time() > ($this->cardapi_expire + 3600)){
            $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=wx_card&access_token=".$this->access_token;
            $res = $this->http_request($url);
            $result = json_decode($res, true);
            $this->cardapi_ticket = $result["ticket"];
            $this->cardapi_expire = time();
            file_put_contents('cardapi_ticket.json', '{"cardapi_ticket": "'.$this->cardapi_ticket.'", "cardapi_expire": '.$this->cardapi_expire.'}');
        }
        return $this->cardapi_ticket;
    }
	
	//cardSign卡券签名
	/*
	$obj['api_ticket']          = "ojZ8YtyVyr30HheH3CM73y";
	$obj['timestamp']           = "1404896688";
	$obj['nonce_str']           = "jonyqin";
	$obj['card_id']             = "pjZ8Yt1XGILfi-FUsewpnnolGgZk";
	$signature  = get_cardsign($obj);
	*/
	public function get_cardsign($bizObj)
	{
		//字典序排序
		asort($bizObj);
		//URL键值对拼成字符串
		$buff = "";
		foreach ($bizObj as $k => $v){
		$buff .= $v;
		}
		//sha1签名
		return sha1($buff);
	}
	
    //获得JS API的ticket
    private function getJsApiTicket() 
    {

		
        //2. 写文件,有改动,待测验 20150430
        $res = file_get_contents('jsapi_ticket.json');
        $result = json_decode($res, true);
        $this->jsapi_ticket = $result["jsapi_ticket"];
        $this->jsapi_expire = $result["jsapi_expire"];

        if (time() > ($this->jsapi_expire + 3600)){
            $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=".$this->access_token;
            $res = $this->http_request($url);
            $result = json_decode($res, true);
            $this->jsapi_ticket = $result["ticket"];
            $this->jsapi_expire = time();
            file_put_contents('jsapi_ticket.json', '{"jsapi_ticket": "'.$this->jsapi_ticket.'", "jsapi_expire": '.$this->jsapi_expire.'}');
        }
        return $this->jsapi_ticket;
    }

    //获得签名包
    public function getSignPackage() {
        $jsapiTicket = $this->getJsApiTicket();
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $url = "$protocol".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].((empty($_SERVER['QUERY_STRING']))?"":("?".$_SERVER['QUERY_STRING']));
        $timestamp = time();
        $nonceStr = $this->createNonceStr();
        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
        $signature = sha1($string);
        $signPackage = array(
                            "appId"     => $this->appid,
                            "nonceStr"  => $nonceStr,
                            "timestamp" => $timestamp,
                            "url"       => $url,
                            "signature" => $signature,
                            "rawString" => $string
                            );
        return $signPackage;
    }
    
    //HTTP要求(撑腰HTTP/HTTPS,撑腰GET/POST)
    protected function http_request($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    //日志记载
    private function logger($log_content)
    {
        if(isset($_SERVER['HTTP_APPNAME'])){   //SAE
            sae_set_display_errors(false);
            sae_debug($log_content);
            sae_set_display_errors(true);
        }else if($_SERVER['REMOTE_ADDR'] != "127.0.0.1"){ //LOCAL
            $max_size = 500000;
            $log_filename = "log.XML";
            if(file_exists($log_filename) and (abs(filesize($log_filename)) > $max_size)){unlink($log_filename);}
            file_put_contents($log_filename, date('Y-m-d H:i:s').$log_content."\r\n", FILE_APPEND);
        }
    }
}

HTML5领取卡券的代码如下所示。

 1 <?php
 2 require_once('wxjssdk.class.php');
 3 $weixin = new class_weixin();
 4 $signPackage = $weixin->GetSignPackage();
 5 $cardapi_ticket =  $weixin->getCardApiTicket();
 6 
 7 $card_id = "piPuduN0wOytmRlSyeNJQToE7BIU";
 8 $obj['api_ticket']  = $cardapi_ticket;
 9 $obj['timestamp']   = strval(time());
10 $obj['nonce_str']   = $weixin->createNonceStr();
11 $obj['card_id']     = $card_id;
12 $signature  = $weixin->get_cardsign($obj);
13 
14 ?>
15 
16 <!DOCTYPE html>
17 <html>
18 <head>
19     <meta http-equiv="Content-Type" content="text/html; charset=gbk" />
20     <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=2.0, minimum-scale=1.0, user-scalable=no" />
21     <meta name="format-detection" content="telephone=no" />
22     <title>微信</title>
23     <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=0">
24     <link rel="stylesheet" href="http://demo.open.weixin.qq.com/jssdk/CSS/style.css">
25 </head>
26 <body ontouchstart="">
27     <h3 id="menu-card">微信卡券接口</h3>
28     <span class="desc">批量添加卡券接口</span>
29     <button class="btn btn_primary" id="addCard">addCard</button>
30 </body>
31 <script src="https://res.wx.qq.com/open/js/jweixin-1.1.0.js"></script>
32 <script>
33     wx.config({
34         debug: false,
35         appId: '<?php echo $signPackage["appId"];?>',
36         timestamp: <?php echo $signPackage["timestamp"];?>,
37         nonceStr: '<?php echo $signPackage["nonceStr"];?>',
38         signature: '<?php echo $signPackage["signature"];?>',
39         // url:'<?php echo $signPackage["url"];?>',
40         jsApiList: [
41             'addCard',
42           ]
43     });
44 </script>
45 <script>
46     wx.ready(function () {
47         //主动执行的
48         wx.checkJsApi({
49             jsApiList: [
50                 'addCard',
51             ],
52             success: function (res) {
53                 // alert(JSON.stringify(res));
54             }
55         });
56 
57         document.querySelector('#addCard').onclick = function () {
58         wx.addCard({
59             cardList: [
60             {
61                 cardId: '<?php echo $obj['card_id'];?>',
62                 cardExt: '{"code":"","openid":"","nonce_str":"<?php echo $obj['nonce_str']?>" ,"timestamp": "<?php echo $obj['timestamp'];?>", "signature":"<?php echo $signature;?>"}'
63             }
64             ],
65             success: function (res) {
66                 alert('已添加卡券:' + JSON.stringify(res.cardList));
67             },
68             cancel: function (res) {
69                 alert(JSON.stringify(res))
70             }
71         });
72         };
73     });
74     
75     wx.error(function (res) {
76         alert(res.errMsg);
77     });
78  </script>
79 </html>

上述代码中,需要注意的地方是卡券的签名部分,读者能够参考微信JS SDK一节的代码实现。

------分隔线----------------------------

公布评论 (141人察看0条评论)
请自觉遵守互联网相关的政策法规,严禁公布色情、暴力、反动的言论。
用户名: 验证码: 点击我更换博盈真人娱乐
最新评论