微信开发(六):微信卡券

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/taotao12312/article/details/77863997

定义变量

<?php
define('APPID', 'w*******8');
define('APPSECRET','8**********4');
$cardid='pMk*****DY';//创建卡券成功获取
$token=getAccessToken();
?>

创建卡券

<?php
///.....微信开发(五)........
/**********1.创建卡券*************/
$card_url="https://api.weixin.qq.com/card/create?access_token=$token";
$data=array (
  'card' =>
     array (
       'card_type' => 'GENERAL_COUPON', //卡券类型:优惠券
       'general_coupon' =>
          array (
            'base_info' =>
               array (
                 'logo_url' => 'http://mmbiz.qpic.cn/mmbiz/iaL1LJM1mF9aRKPZJkmG8xXhiaHqkKSVMMWeN3hLut7X7hicFNjakmxibMLGWpXrEXB33367o7zHN0CwngnQY7zb7g/0',
                 'brand_name' => '橙子优惠券',
                 'code_type' => 'CODE_TYPE_QRCODE', //卡券类型
                 'title' => '优惠券',
                 'sub_title' => '优惠',
                 'color' => 'Color030',//颜色
                 'notice' => '使用时请出示此券', //展示显示的卡券
                 'service_phone' => '15812345698',
                 'date_info' =>
                    array (
                      'type' => 'DATE_TYPE_FIX_TERM', //时间类型
                      'fixed_term' => 90,//有效期限
                      'fixed_begin_term' => 0,//从什么时候开始
                    ),
                 'sku' =>
                    array (
                      'quantity' => '100',//库存
                    ),
                'get_limit' => 100,//每个用户最多可以领取数量
                'bind_openid' => false,//没有绑定领取的用户
                'can_share' => true,//可以分享
                'can_give_friend' => false,//赠送给朋友
                'center_title' => '立即使用1',//中间展示按钮
                'center_sub_title' => '点击立即使用',
                'center_url' => 'https://www.baidu.com/',//跳转地址
                'custom_url_name' => '立即使用2',
                'custom_url' => 'https://www.baidu.com/',//底部跳转入口
                'custom_url_sub_title' => '点击跳转',
             ),
             'default_detail' => '橙子专用优惠券,不可与其他优惠同享'
          ),
     ),
);
$res=httpPost($card_url,json_encode($data,JSON_UNESCAPED_UNICODE));
var_dump($res);
?>

结果:
{
“errcode”:0,
“errmsg”:”ok”,
“card_id”:”pMkQc****rmN_DY”
}

创建卡券成功!!!

投放卡券

<?php
/**********2.投放卡券*************/
//2.1二维码投放
$tf_url="https://api.weixin.qq.com/card/qrcode/create?access_token=$token";
$json='
 {
"action_name": "QR_CARD", 
"expire_seconds": 1800,
"action_info": {
"card": {
"card_id": "pM******k", 
"is_unique_code": false
  }
 }
} 
';
$res=httpPost($tf_url,$json);
var_dump($res);
?>

结果:
{
“errcode”:0,
“errmsg”:”ok”,
“ticket”:”gQGP******AA”,
“expire_seconds”:1800,
“url”:”http://weixi*****4o”,
“show_qrcode_url”:”https://mp*******AwQIBwAA”
}

扫描show_qrcode_url链接显示的二维码!

//2.2 网页投放
<?php
$SignPackage=getSignPackage();
$cardExt = getPutCardExt($cardid,$token);
?>
<button style="width:100px;height:100px;"  id="addCard">领取卡券</button>
<script src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
<script src="http://images.yeecare.com/login/js/jquery.js"></script>
<script>
    wx.config({
        debug: true, // 开启调试模式
        appId: '<?php echo APPID?>', // 必填,公众号的唯一标识
        timestamp: <?php echo $SignPackage['timestamp']?>, // 必填,生成签名的时间戳
        nonceStr: '<?php echo $SignPackage['nonceStr']?>', // 必填,生成签名的随机串
        signature: '<?php echo $SignPackage['signature']?>',// 必填,签名,见附录1
        jsApiList: ['addCard'] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
    });
    document.querySelector('#addCard').onclick = function () {
        wx.addCard({
            cardList: [
                {
                    cardId: '<?php echo $cardid?>',
                    cardExt: '<?php echo json_encode($cardExt)?>'
                },
            ],
            success: function (res) {
                alert('已添加卡券:' + JSON.stringify(res.cardList));
            },
            cancel: function (res) {
                alert('关闭领取:' +JSON.stringify(res))
            }
        });
    };
</script>

拉取适用卡券列表并获取用户选择信息

<?php
$SignPackage=getSignPackage();
$cardExt = getCardExt($token);
?>
<button style="width:100px;height:100px;"  id="chooseCard">选择卡券</button>
<script src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
<script src="http://images.yeecare.com/login/js/jquery.js"></script>
<script>
    wx.config({
        debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
        appId: '<?php echo APPID?>', // 必填,公众号的唯一标识
        timestamp: <?php echo $SignPackage['timestamp']?>, // 必填,生成签名的时间戳
        nonceStr: '<?php echo $SignPackage['nonceStr']?>', // 必填,生成签名的随机串
        signature: '<?php echo $SignPackage['signature']?>',// 必填,签名,见附录1
        jsApiList: ['chooseCard'] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
    });
    document.querySelector('#chooseCard').οnclick=function(){
        wx.chooseCard({
            shopId: '', // 门店Id
            cardType: '', // 卡券类型
            cardId: '', // 卡券Id
            timestamp: <?php echo $cardExt['timestamp']?>, // 卡券签名时间戳
            nonceStr: '<?php echo $cardExt['nonceStr']?>', // 卡券签名随机串
            signType: '<?php echo $cardExt['signType']?>', // 签名方式,默认'SHA1'
            cardSign: '<?php echo $cardExt['cardSign']?>', // 卡券签名
            success: function (res) {
                if (res.errMsg == "chooseCard:ok") {
                    var cardList= res.cardList;
                    alert(cardList);
                };
            }
        });
    };
</script>

检查卡券状态

核销卡券

设置白名单

<?php
//设置测试白名单
$arr=array(
    'openid'=>array('oM*****Ykk'),
);
$url="https://api.weixin.qq.com/card/testwhitelist/set?access_token=$token";
$res=httpPost($url,json_encode($arr,JSON_UNESCAPED_UNICODE));
var_dump($res);
?>

结果:
{
“errcode”:0,
“errmsg”:”ok”,
“white_list_size”:1,
“success_openid”:[
“oM*****Ykk”
],
“success_username”:[ ]
}

公共代码

//(1)生成/获取access_token并写入文件
function getAccessToken() {
    $data = json_decode(file_get_contents("access_token.json"));
    if ($data->expire_time < time()) {
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".APPID."&secret=".APPSECRET;
        $res = json_decode(httpPost($url));
        $access_token = $res->access_token;
        if ($access_token) {
            $data->expire_time = time() + 7000;
            $data->access_token = $access_token;
            $fp = fopen("access_token.json", "w");
            fwrite($fp, json_encode($data));
            fclose($fp);
        }
    } else {
        $access_token = $data->access_token;
    }
    return $access_token;
}
function httpPost($url,$data=''){
    $ch= curl_init();
    curl_setopt($ch, CURLOPT_URL, $url );
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //设置内容是不是返回
    if(!empty($data)){
        curl_setopt($ch, CURLOPT_POST, 1); //设置post提交数据
        curl_setopt($ch,CURLOPT_POSTFIELDS,$data); //设置post提交数据
    }
    //判断当前是不是有post数据的发
    $output=curl_exec($ch);//请求的地址输出了什么数据就会返回什么数据
    if ($output === FALSE) {
        $output="curl 错误信息: " . curl_error($ch);
    }
    curl_close($ch);
    return $output;
}
function httpGet($url) {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_TIMEOUT, 500);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true);
    curl_setopt($curl, CURLOPT_URL, $url);
    $res = curl_exec($curl);
    curl_close($curl);
    return $res;
}
function getSignPackage() {
    $jsapiTicket = getJsApiTicket();
    // 注意 URL 一定要动态获取,不能 hardcode.
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
    $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
    $timestamp = time();
    $nonceStr = createNonceStr();
    // 这里参数的顺序要按照 key 值 ASCII 码升序排序
    $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
    $signature = sha1($string);
    $signPackage = array(
        "appId"     => APPID,
        "nonceStr"  => $nonceStr,
        "timestamp" => $timestamp,
        "url"       => $url,
        "signature" => $signature,
        "rawString" => $string
    );
    return $signPackage;
}
function getJsApiTicket() {
    // jsapi_ticket 应该全局存储与更新,以下代码以写入到文件中做示例
    $data = json_decode(file_get_contents("jsapi_ticket.json"));
    if ($data->expire_time < time()) {
        $accessToken = getAccessToken();
        // 如果是企业号用以下 URL 获取 ticket
        // $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken";
        $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
        $res = json_decode(httpGet($url));
        $ticket = $res->ticket;
        if ($ticket) {
            $data->expire_time = time() + 7000;
            $data->jsapi_ticket = $ticket;
            $fp = fopen("jsapi_ticket.json", "w");
            fwrite($fp, json_encode($data));
            fclose($fp);
        }
    } else {
        $ticket = $data->jsapi_ticket;
    }

    return $ticket;
}
function get_signature($array){
    sort( $array, SORT_STRING );
    return sha1( implode( $array ) );
}
function createNonceStr($length = 32) {
    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    $str = "";
    for ($i = 0; $i < $length; $i++) {
        $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
    }
    return $str;
}
function getPutCardExt($cardid,$accessToken,$openid="")
{
    $api_ticket = getApiTicket($accessToken);
    $timestamp = time();
    $nonce_str = createNonceStr();
    $arr = array(
        "api_ticket" => $api_ticket,
        "timestamp" => $timestamp,
        "card_id" => $cardid,
        "code" =>'',
        "openid" =>'',
        "nonce_str" => $nonce_str,
    );

    $signature = get_signature($arr);
    $cardExt = array(
        "openid" => "$openid",
        "timestamp" => "$timestamp",
        "nonce_str" => "$nonce_str",
        "signature"  => "$signature",
    );
    return $cardExt;
}
function getCardExt($accessToken) {
    $api_ticket = getApiTicket($accessToken);
    $timestamp = time();
    $nonce_str = createNonceStr();
    $array = array(
        "api_ticket" => $api_ticket,
        "timestamp"  => $timestamp,
        "card_type"  => '',
        "nonce_str"  => $nonce_str,
        "app_id"     => APPID,
    );
    $signature = get_signature($array);
    $cardExt = array(
        "api_ticket" => $api_ticket,
        "timestamp" => $timestamp,
        "cardType"  => '',
        "nonceStr"  => $nonce_str,
        "cardSign"  => $signature,
        "signType"  => 'SHA1'
    );
    return $cardExt;
}
function  getApiTicket($accessToken){
        $API_TICKET_URL="https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=wx_card&access_token={$accessToken}";
        $json=file_get_contents($API_TICKET_URL);
        $json = json_decode($json, true);
        $api_ticket = $json['ticket'];
    return $api_ticket;
}
展开阅读全文

没有更多推荐了,返回首页