微信入口绑定,微信事件处理,微信API全部操作

微信入口绑定,微信事件处理,微信API全部操作包含在这些文件中。
微信支付、微信红包、微信卡券、微信小店。


1. index.php 
  1. <?php
  2. include_once 'lib.inc.php';

  3. $wcObj = new WeChat("YOUKUIYUAN");
  4. $wcObj->wcValid();
复制代码
2. 微信入口类

  1. <?php
  2. /**
  3. * Description of wechat
  4. *
  5. * @author Administrator
  6. */
  7. class WeChat extends WxApi{
  8.     public $token = "";
  9.     //put your code here
  10.     public function __construct($token = "") {
  11.         parent::__construct();
  12.         $this->token = $token;
  13.     }

  14.     public function wcCheckSignature(){
  15.         try{
  16.             if (empty($this->token)) {
  17.                 throw new Exception('TOKEN is not defined!');
  18.             }
  19.              
  20.             $signature = $_GET["signature"];
  21.             $timestamp = $_GET["timestamp"];
  22.             $nonce = $_GET["nonce"];
  23.                  
  24.             $token = $this->token;
  25.             $tmpArr = array($token, $timestamp, $nonce);
  26.             // use SORT_STRING rule
  27.             sort($tmpArr, SORT_STRING);
  28.             $tmpStr = implode( $tmpArr );
  29.             $tmpStr = sha1( $tmpStr );

  30.             if( $tmpStr == $signature ){
  31.                     return true;
  32.             }else{
  33.                     return false;
  34.             }
  35.         } 
  36.         catch (Exception $e) {
  37.             echo 'Message: ' .$e->getMessage();
  38.         }
  39.     }
  40.      
  41.     public function wcValid(){
  42.         $echoStr = isset($_GET["echostr"]) && !empty($_GET["echostr"]) ? addslashes($_GET["echostr"]) : NULL;
  43.         if(is_null($echoStr)){
  44.             $this->wcMsg();
  45.         }
  46.         else{
  47.             //valid signature , option
  48.             if($this->wcCheckSignature()){
  49.                 echo $echoStr;
  50.                 exit;
  51.             }
  52.             else{
  53.                 exit();
  54.             }
  55.         }
  56.     }
  57.      
  58.     public function wcMsg(){
  59.         //get post data, May be due to the different environments
  60.         $postStr = isset($GLOBALS["HTTP_RAW_POST_DATA"]) && !empty($GLOBALS["HTTP_RAW_POST_DATA"]) ? $GLOBALS["HTTP_RAW_POST_DATA"] : "";
  61.         if(!empty($postStr)){
  62.             libxml_disable_entity_loader(true);
  63.             $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
  64.             $this->zcLog(TRUE,$postObj);
  65.              
  66.             $fromUsername = $postObj->FromUserName;
  67.             $toUsername = $postObj->ToUserName;
  68.             $MsgType = $postObj->MsgType;
  69.              
  70.             if($MsgType == 'event'){//执行事件相应
  71.                 $Event = $postObj->Event;
  72.                 switch ($Event) {
  73.                     case 'subscribe'://关注
  74.                         break;
  75.                     case 'unsubscribe'://取消关注
  76.                         break;
  77.                     case 'SCAN'://扫描
  78.                         break;
  79.                     case 'LOCATION'://地址
  80.                         break;
  81.                     case 'CLICK'://点击时间
  82.                         break;
  83.                     case 'VIEW'://跳转
  84.                         break;
  85.                     case 'card_pass_check'://卡券审核通过
  86.                         break;
  87.                     case 'card_not_pass_check'://卡券审核失败
  88.                         break;
  89.                     case 'user_get_card'://用户领取卡券
  90.                         break;
  91.                     case 'user_del_card'://用户删除卡券
  92.                         break;
  93.                     case 'user_view_card'://用户浏览会员卡
  94.                         break;
  95.                     case 'user_consume_card'://用户核销卡券
  96.                         break;
  97.                     case 'merchant_order'://微小店用户下单付款
  98.                         break;
  99.                     default:
  100.                         break;
  101.                 }
  102.             }
  103.             else{
  104.                 switch ($MsgType) {
  105.                     case 'text'://文本格式
  106.                         break;
  107.                     case 'image'://图片格式
  108.                         break;
  109.                     case 'voice'://声音
  110.                         break;
  111.                     case 'video'://视频
  112.                         break;
  113.                     case 'shortvideo'://小视频
  114.                         break;
  115.                     case 'location'://上传地理位置
  116.                         break;
  117.                     case 'link'://链接相应
  118.                         break;
  119.                     default:
  120.                         break;
  121.                 }                
  122.             }
  123.              
  124.             
  125.             $keyword = trim($postObj->Content);
  126.             $time = time();
  127.             $textTpl = "<xml>
  128.                             <ToUserName><![CDATA[%s]]></ToUserName>
  129.                             <FromUserName><![CDATA[%s]]></FromUserName>
  130.                             <CreateTime>%s</CreateTime>
  131.                             <MsgType><![CDATA[%s]]></MsgType>
  132.                             <Content><![CDATA[%s]]></Content>
  133.                             <FuncFlag>0</FuncFlag>
  134.                         </xml>";             
  135.             if(!empty( $keyword )){
  136.                 $msgType = "text";
  137.                 $contentStr = "Welcome to wechat world!";
  138.                 $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
  139.                 echo $resultStr;
  140.             }
  141.             else{
  142.                 echo "Input something...";
  143.             }
  144.             
  145.         }
  146.         else{
  147.             echo "暂时没有任何信息!";
  148.             exit;
  149.         }
  150.     }
  151.      
  152.     //日志LOG
  153.     public function zcLog($errcode , $errmsg){
  154.         $this->returnAy = array();
  155.         $this->returnAy['errcode'] = $errcode;
  156.         $this->returnAy['errmsg'] = $errmsg;
  157.         $this->returnAy['errtime'] = date("Y-m-d H:i:s",time());
  158.         $logfile = fopen("logfile_".date("Ymd",time()).".txt", "a+");
  159.         $txt = json_encode($this->returnAy)."\n";
  160.         fwrite($logfile, $txt);
  161.         fclose($logfile);
  162.         //return $this->returnAy;
  163.     }
  164.      
  165. }
复制代码
3. 微信操作类 - 更新了自定义菜单部分

  1. <?php
  2.     /********************************************************
  3.      *      @author Kyler You <QQ:2444756311>
  4.      *      @link http://mp.weixin.qq.com/wiki/home/index.html
  5.      *      @version 2.0.1
  6.      *      @uses $wxApi = new WxApi();
  7.      *      @package 微信API接口 陆续会继续进行更新
  8.      ********************************************************/

  9.     class WxApi {
  10.         //const appId         = "";
  11.         //const appSecret     = "";
  12.         const appId         = "";
  13.         const appSecret     = "";
  14.         //const mchid         = ""; //商户号
  15.         //const privatekey    = ""; //私钥
  16.         public $parameters  = array();

  17.         public function __construct(){

  18.         }

  19.         /****************************************************
  20.          *  微信提交API方法,返回微信指定JSON
  21.          ****************************************************/

  22.         public function wxHttpsRequest($url,$data = null){
  23.                 $curl = curl_init();
  24.                 curl_setopt($curl, CURLOPT_URL, $url);
  25.                 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
  26.                 curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
  27.                 if (!empty($data)){
  28.                         curl_setopt($curl, CURLOPT_POST, 1);
  29.                         curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
  30.                 }
  31.                 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  32.                 $output = curl_exec($curl);
  33.                 curl_close($curl);
  34.                 return $output;
  35.         }

  36.         /****************************************************
  37.          *  微信带证书提交数据 - 微信红包使用
  38.          ****************************************************/

  39.         public function wxHttpsRequestPem($url, $vars, $second=30,$aHeader=array()){
  40.                 $ch = curl_init();
  41.                 //超时时间
  42.                 curl_setopt($ch,CURLOPT_TIMEOUT,$second);
  43.                 curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
  44.                 //这里设置代理,如果有的话
  45.                 //curl_setopt($ch,CURLOPT_PROXY, '10.206.30.98');
  46.                 //curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
  47.                 curl_setopt($ch,CURLOPT_URL,$url);
  48.                 curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
  49.                 curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);

  50.                 //以下两种方式需选择一种

  51.                 //第一种方法,cert 与 key 分别属于两个.pem文件
  52.                 //默认格式为PEM,可以注释
  53.                 curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
  54.                 curl_setopt($ch,CURLOPT_SSLCERT,getcwd().'/apiclient_cert.pem');
  55.                 //默认格式为PEM,可以注释
  56.                 curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
  57.                 curl_setopt($ch,CURLOPT_SSLKEY,getcwd().'/apiclient_key.pem');

  58.                 curl_setopt($ch,CURLOPT_CAINFO,'PEM');
  59.                 curl_setopt($ch,CURLOPT_CAINFO,getcwd().'/rootca.pem');

  60.                 //第二种方式,两个文件合成一个.pem文件
  61.                 //curl_setopt($ch,CURLOPT_SSLCERT,getcwd().'/all.pem');

  62.                 if( count($aHeader) >= 1 ){
  63.                         curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);
  64.                 }

  65.                 curl_setopt($ch,CURLOPT_POST, 1);
  66.                 curl_setopt($ch,CURLOPT_POSTFIELDS,$vars);
  67.                 $data = curl_exec($ch);
  68.                 if($data){
  69.                         curl_close($ch);
  70.                         return $data;
  71.                 }
  72.                 else { 
  73.                         $error = curl_errno($ch);
  74.                         echo "call faild, errorCode:$error\n"; 
  75.                         curl_close($ch);
  76.                         return false;
  77.                 }
  78.         }

  79.         /****************************************************
  80.          *  微信获取AccessToken 返回指定微信公众号的at信息
  81.          ****************************************************/

  82.         public function wxAccessToken($appId = NULL , $appSecret = NULL){
  83.                 $appId          = is_null($appId) ? self::appId : $appId;
  84.                 $appSecret      = is_null($appSecret) ? self::appSecret : $appSecret;
  85.                  
  86.                 $data = json_decode(file_get_contents("access_token.json"));
  87.                 if ($data->expire_time < time()) {
  88.                     //echo $appId,$appSecret;
  89.                     $url            = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appId."&secret=".$appSecret;
  90.                     $result         = $this->wxHttpsRequest($url);
  91.                     //print_r($result);
  92.                     $jsoninfo       = json_decode($result, true);
  93.                     $access_token   = $jsoninfo["access_token"];
  94.                     if ($access_token) {
  95.                         $data->expire_time = time() + 7000;
  96.                         $data->access_token = $access_token;
  97.                         $fp = fopen("access_token.json", "w");
  98.                         fwrite($fp, json_encode($data));
  99.                         fclose($fp);
  100.                     }
  101.                 }
  102.                 else {
  103.                     $access_token = $data->access_token;
  104.                 }
  105.                 return $access_token;
  106.         }

  107.         /****************************************************
  108.          *  微信获取AccessToken 返回指定微信公众号的at信息
  109.          ****************************************************/

  110.         public function wxJsApiTicket($appId = NULL , $appSecret = NULL){
  111.                 $appId          = is_null($appId) ? self::appId : $appId;
  112.                 $appSecret      = is_null($appSecret) ? self::appSecret : $appSecret;
  113.                  
  114.                 $data = json_decode(file_get_contents("jsapi_ticket.json"));
  115.                 if ($data->expire_time < time()) {                
  116.                     $url        = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=".$this->wxAccessToken();
  117.                     $result         = $this->wxHttpsRequest($url);
  118.                     $jsoninfo       = json_decode($result, true);
  119.                     $ticket = $jsoninfo['ticket'];
  120.                     if ($ticket) {
  121.                         $data->expire_time = time() + 7000;
  122.                         $data->jsapi_ticket = $ticket;
  123.                         $fp = fopen("jsapi_ticket.json", "w");
  124.                         fwrite($fp, json_encode($data));
  125.                         fclose($fp);
  126.                     }
  127.                 }
  128.                 else {
  129.                     $ticket = $data->jsapi_ticket;
  130.                 }
  131.                 return $ticket;
  132.         }
  133.          
  134.         /****************************************************
  135.          *  微信通过OPENID获取用户信息,返回数组
  136.          ****************************************************/

  137.         public function wxGetUser($openId){
  138.             $wxAccessToken  = $this->wxAccessToken();
  139.             $url            = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$wxAccessToken."&openid=".$openId."&lang=zh_CN";
  140.             $result         = $this->wxHttpsRequest($url);
  141.             $jsoninfo       = json_decode($result, true);
  142.             return $jsoninfo;
  143.         }        

  144.         /****************************************************
  145.          *  微信生成二维码ticket
  146.          ****************************************************/

  147.         public function wxQrCodeTicket($jsonData){
  148.             $wxAccessToken  = $this->wxAccessToken();
  149.             $url        = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=".$wxAccessToken;
  150.             $result         = $this->wxHttpsRequest($url,$jsonData);
  151.             return $result;
  152.         }
  153.          
  154.         /****************************************************
  155.          *  微信通过ticket生成二维码
  156.          ****************************************************/
  157.         public function wxQrCode($ticket){
  158.             $url    = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" . urlencode($ticket);
  159.             return $url;
  160.         }

  161.         /****************************************************
  162.          *      发送自定义的模板消息
  163.          ****************************************************/

  164.         public function wxSetSend($touser, $template_id, $url, $data, $topcolor = '#7B68EE'){
  165.                 $template = array(
  166.                         'touser' => $touser,
  167.                         'template_id' => $template_id,
  168.                         'url' => $url,
  169.                         'topcolor' => $topcolor,
  170.                         'data' => $data
  171.                 );
  172.                 $jsonData = json_encode($template);
  173.                 $result = $this->wxSendTemplate($jsonData);
  174.                 return $result;
  175.         }

  176.         /****************************************************
  177.          *  微信设置OAUTH跳转URL,返回字符串信息 - SCOPE = snsapi_base //验证时不返回确认页面,只能获取OPENID
  178.          ****************************************************/

  179.         public function wxOauthBase($redirectUrl,$state = "",$appId = NULL){
  180.                 $appId          = is_null($appId) ? self::appId : $appId;
  181.                 $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appId."&redirect_uri=".$redirectUrl."&response_type=code&scope=snsapi_base&state=".$state."#wechat_redirect";
  182.                 return $url;
  183.         }

  184.         /****************************************************
  185.          *  微信设置OAUTH跳转URL,返回字符串信息 - SCOPE = snsapi_userinfo //获取用户完整信息
  186.          ****************************************************/

  187.         public function wxOauthUserinfo($redirectUrl,$state = "",$appId = NULL){
  188.                 $appId          = is_null($appId) ? self::appId : $appId;
  189.                 $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appId."&redirect_uri=".$redirectUrl."&response_type=code&scope=snsapi_userinfo&state=".$state."#wechat_redirect";
  190.                 return $url;
  191.         }

  192.         /****************************************************
  193.          *  微信OAUTH跳转指定URL
  194.          ****************************************************/

  195.         public function wxHeader($url){
  196.                 header("location:".$url);
  197.         }

  198.         /****************************************************
  199.          *  微信通过OAUTH返回页面中获取AT信息
  200.          ****************************************************/

  201.         public function wxOauthAccessToken($code,$appId = NULL , $appSecret = NULL){
  202.                 $appId          = is_null($appId) ? self::appId : $appId;
  203.                 $appSecret      = is_null($appSecret) ? self::appSecret : $appSecret;
  204.                 $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appId."&secret=".$appSecret."&code=".$code."&grant_type=authorization_code";
  205.                 $result         = $this->wxHttpsRequest($url);
  206.                 //print_r($result);
  207.                 $jsoninfo       = json_decode($result, true);
  208.                 //$access_token     = $jsoninfo["access_token"];
  209.                 return $jsoninfo;           
  210.         }

  211.         /****************************************************
  212.          *  微信通过OAUTH的Access_Token的信息获取当前用户信息 // 只执行在snsapi_userinfo模式运行
  213.          ****************************************************/

  214.         public function wxOauthUser($OauthAT,$openId){
  215.                 $url            = "https://api.weixin.qq.com/sns/userinfo?access_token=".$OauthAT."&openid=".$openId."&lang=zh_CN";
  216.                 $result         = $this->wxHttpsRequest($url);
  217.                 $jsoninfo       = json_decode($result, true);
  218.                 return $jsoninfo;           
  219.         }

  220.         /****************************************************
  221.          *  创建自定义菜单
  222.          ****************************************************/

  223.         public function wxMenuCreate($jsonData){
  224.             $wxAccessToken  = $this->wxAccessToken();
  225.             $url            = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" . $wxAccessToken;
  226.             $result         = $this->wxHttpsRequest($url,$jsonData);
  227.             $jsoninfo       = json_decode($result, true);
  228.             return $jsoninfo;           
  229.         }

  230.         /****************************************************
  231.          *  获取自定义菜单
  232.          ****************************************************/

  233.         public function wxMenuGet(){
  234.             $wxAccessToken  = $this->wxAccessToken();
  235.             $url            = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token=" . $wxAccessToken;
  236.             $result         = $this->wxHttpsRequest($url);
  237.             $jsoninfo       = json_decode($result, true);
  238.             return $jsoninfo;
  239.         }

  240.         /****************************************************
  241.          *  删除自定义菜单
  242.          ****************************************************/

  243.         public function wxMenuDelete(){
  244.             $wxAccessToken  = $this->wxAccessToken();
  245.             $url            = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=" . $wxAccessToken;
  246.             $result         = $this->wxHttpsRequest($url);
  247.             $jsoninfo       = json_decode($result, true);
  248.             return $jsoninfo;
  249.         }

  250.         /****************************************************
  251.          *  获取第三方自定义菜单
  252.          ****************************************************/

  253.         public function wxMenuGetInfo(){
  254.             $wxAccessToken  = $this->wxAccessToken();
  255.             $url            = "https://api.weixin.qq.com/cgi-bin/get_current_selfmenu_info?access_token=" . $wxAccessToken;
  256.             $result         = $this->wxHttpsRequest($url);
  257.             $jsoninfo       = json_decode($result, true);
  258.             return $jsoninfo;
  259.         }
  260.                  
  261.         /*****************************************************
  262.          *      生成随机字符串 - 最长为32位字符串
  263.          *****************************************************/
  264.         public function wxNonceStr($length = 16, $type = FALSE) {
  265.             $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  266.             $str = "";
  267.             for ($i = 0; $i < $length; $i++) {
  268.               $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
  269.             }
  270.             if($type == TRUE){
  271.                 return strtoupper(md5(time() . $str));
  272.             }
  273.             else {
  274.                 return $str;
  275.             }
  276.         }
  277.          
  278.         /*******************************************************
  279.          *      微信商户订单号 - 最长28位字符串
  280.          *******************************************************/
  281.          
  282.         public function wxMchBillno($mchid = NULL) {
  283.             if(is_null($mchid)){
  284.                 if(self::mchid == "" || is_null(self::mchid)){
  285.                     $mchid = time();
  286.                 }
  287.                 else{
  288.                     $mchid = self::mchid;
  289.                 }
  290.             }
  291.             else{
  292.                 $mchid = substr(addslashes($mchid),0,10);
  293.             }
  294.             return date("Ymd",time()).time().$mchid;
  295.         }
  296.          
  297.         /*******************************************************
  298.          *      微信格式化数组变成参数格式 - 支持url加密
  299.          *******************************************************/      
  300.          
  301.         public function wxSetParam($parameters){
  302.             if(is_array($parameters) && !empty($parameters)){
  303.                 $this->parameters = $parameters;
  304.                 return $this->parameters;
  305.             }
  306.             else{
  307.                 return array();
  308.             }
  309.         }
  310.          
  311.         /*******************************************************
  312.          *      微信格式化数组变成参数格式 - 支持url加密
  313.          *******************************************************/
  314.          
  315.     public function wxFormatArray($parameters = NULL, $urlencode = FALSE){
  316.             if(is_null($parameters)){
  317.                 $parameters = $this->parameters;
  318.             }
  319.             $restr = "";//初始化空
  320.             ksort($parameters);//排序参数
  321.             foreach ($parameters as $k => $v){//循环定制参数
  322.                 if (null != $v && "null" != $v && "sign" != $k) {
  323.                     if($urlencode){//如果参数需要增加URL加密就增加,不需要则不需要
  324.                         $v = urlencode($v);
  325.                     }
  326.                     $restr .= $k . "=" . $v . "&";//返回完整字符串
  327.                 }
  328.             }
  329.             if (strlen($restr) > 0) {//如果存在数据则将最后“&”删除
  330.                 $restr = substr($restr, 0, strlen($restr)-1);
  331.             }
  332.             return $restr;//返回字符串
  333.     }
  334.          
  335.         /*******************************************************
  336.          *      微信MD5签名生成器 - 需要将参数数组转化成为字符串[wxFormatArray方法]
  337.          *******************************************************/
  338.         public function wxMd5Sign($content, $privatekey){
  339.         try {
  340.                 if (is_null($privatekey)) {
  341.                     throw new Exception("财付通签名key不能为空!");
  342.                 }
  343.                 if (is_null($content)) {
  344.                     throw new Exception("财付通签名内容不能为空");
  345.                 }
  346.                 $signStr = $content . "&key=" . $privatekey;
  347.                 return strtoupper(md5($signStr));
  348.             }
  349.             catch (Exception $e)
  350.             {
  351.                 die($e->getMessage());
  352.             }
  353.         }
  354.          
  355.         /*******************************************************
  356.          *      微信Sha1签名生成器 - 需要将参数数组转化成为字符串[wxFormatArray方法]
  357.          *******************************************************/
  358.         public function wxSha1Sign($content){
  359.             try {
  360.                 if (is_null($content)) {
  361.                     throw new Exception("签名内容不能为空");
  362.                 }
  363.                 //$signStr = $content;
  364.                 return sha1($content);
  365.             }
  366.             catch (Exception $e)
  367.             {
  368.                 die($e->getMessage());
  369.             }
  370.         }
  371.          
  372.         /*******************************************************
  373.          *      微信jsApi整合方法 - 通过调用此方法获得jsapi数据
  374.          *******************************************************/       
  375.         public function wxJsapiPackage(){
  376.             $jsapi_ticket = $this->wxJsApiTicket();
  377.              
  378.             // 注意 URL 一定要动态获取,不能 hardcode.
  379.             $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
  380.             $url = $protocol.$_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"];
  381.              
  382.             $timestamp = time();
  383.             $nonceStr = $this->wxNonceStr();
  384.              
  385.             $signPackage = array(
  386.               "jsapi_ticket" => $jsapi_ticket,
  387.               "nonceStr"  => $nonceStr,
  388.               "timestamp" => $timestamp,
  389.               "url"       => $url
  390.             ); 
  391.              
  392.             // 这里参数的顺序要按照 key 值 ASCII 码升序排序
  393.             $rawString = "jsapi_ticket=$jsapi_ticket&noncestr=$nonceStr×tamp=$timestamp&url=$url";
  394.              
  395.             //$rawString = $this->wxFormatArray($signPackage);
  396.             $signature = $this->wxSha1Sign($rawString);
  397.              
  398.             $signPackage['signature'] = $signature;
  399.             $signPackage['rawString'] = $rawString;
  400.             $signPackage['appId'] = self::appId;
  401.              
  402.             return $signPackage;
  403.         }
  404.          
  405.          
  406.         /*******************************************************
  407.          *      将数组解析XML - 微信红包接口
  408.          *******************************************************/
  409.         public function wxArrayToXml($parameters = NULL){
  410.             if(is_null($parameters)){
  411.                 $parameters = $this->parameters;
  412.             }
  413.              
  414.             if(!is_array($parameters) || empty($parameters)){
  415.                 die("参数不为数组无法解析");
  416.             }
  417.              
  418.             $xml = "<xml>";
  419.             foreach ($arr as $key=>$val)
  420.             {
  421.                 if (is_numeric($val))
  422.                 {
  423.                     $xml.="<".$key.">".$val."</".$key.">"; 
  424.                 }
  425.                 else
  426.                     $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";  
  427.             }
  428.             $xml.="</xml>";
  429.             return $xml; 
  430.         }
  431.          
  432.         /*******************************************************
  433.          *      微信卡券:上传LOGO - 需要改写动态功能
  434.          *******************************************************/
  435.         public function wxCardUpdateImg() {
  436.             $wxAccessToken  = $this->wxAccessToken();
  437.             //$data['access_token'] =  $wxAccessToken;
  438.             $data['buffer']     =  '@D:\\workspace\\htdocs\\yky_test\\logo.jpg';
  439.             $url            = "https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=".$wxAccessToken;
  440.             $result         = $this->wxHttpsRequest($url,$data);
  441.             $jsoninfo       = json_decode($result, true);
  442.             return $jsoninfo;
  443.             //array(1) { ["url"]=> string(121) "http://mmbiz.qpic.cn/mmbiz/ibuYxPHqeXePNTW4ATKyias1Cf3zTKiars9PFPzF1k5icvXD7xW0kXUAxHDzkEPd9micCMCN0dcTJfW6Tnm93MiaAfRQ/0" } 
  444.         }
  445.          
  446.         /*******************************************************
  447.          *      微信卡券:获取颜色
  448.          *******************************************************/
  449.         public function wxCardColor(){
  450.             $wxAccessToken  = $this->wxAccessToken();
  451.             $url                = "https://api.weixin.qq.com/card/getcolors?access_token=".$wxAccessToken;
  452.             $result         = $this->wxHttpsRequest($url);
  453.             $jsoninfo       = json_decode($result, true);
  454.             return $jsoninfo;
  455.         }
  456.          
  457.         /*******************************************************
  458.          *      微信卡券:创建卡券
  459.          *******************************************************/
  460.         public function wxCardCreated($jsonData) {
  461.             $wxAccessToken  = $this->wxAccessToken();
  462.             $url            = "https://api.weixin.qq.com/card/create?access_token=" . $wxAccessToken;
  463.             $result         = $this->wxHttpsRequest($url,$jsonData);
  464.             $jsoninfo       = json_decode($result, true);
  465.             return $jsoninfo;
  466.         }
  467.          
  468.         /*******************************************************
  469.          *      微信卡券:JSAPI 卡券Package - 基础参数没有附带任何值 - 再生产环境中需要根据实际情况进行修改
  470.          *******************************************************/      
  471.         public function wxCardPackage($cardId){
  472.             $timestamp = time();
  473.             $api_ticket = $this->wxJsApiTicket();
  474.             $cardId = $cardId;
  475.             $arrays = array($api_ticket,$timestamp,$cardId);
  476.             sort($arrays);
  477.             $string = sha1(implode("",$arrays));

  478.             $resultArray['card_id'] = $cardId;
  479.             $resultArray['card_ext'] = array();
  480.             $resultArray['card_ext']['openid'] = 'oOmn4s9MiwqHSNNvPn0dBtU23toA';
  481.             $resultArray['card_ext']['timestamp'] = $timestamp;
  482.             $resultArray['card_ext']['signature'] = $string;

  483.             return $resultArray;
  484.         }
  485.          
  486.          
  487.     }
复制代码


4. 微信JSAPI 

  1. <?php
  2.     require_once 'lib.inc.php';
  3.     $wx = new WxApi();
  4.     //通过网页获取openid
  5.     //if(!isset($_GET['code'])){
  6.     //    header("location:https://open.weixin.qq.com/connect/oauth2/authorize?appid=".WxApi::appId."&redirect_uri=http://".$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF']."&response_type=code&scope=snsapi_base&state=1#wechat_redirect");
  7.     //}
  8.     //else{
  9.     //    $CODE =  $_GET['code'];
  10.     //    $Info = $wx->wxOauthAccessToken($CODE);
  11.         //print_r($Info);
  12.     //    $openId = $Info['openid'];    
  13.     //}
  14.    

  15.     $signPackage = $wx->wxJsapiPackage();
  16.     //print_r($signPackage);
  17.     $kqInfo = $wx->wxCardPackage("");
  18.     $listInfo = $wx->wxCardListPackage();
  19. ?>
  20. <html>
  21.     <head>
  22.         <title>JSAPI接口测试</title>
  23.         <meta charset="UTF-8">
  24.         <meta name="viewport" content="width=device-width, initial-scale=1.0">
  25.          
  26.         <script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
  27.         <script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
  28.     </head>
  29.     <body>
  30.         <div>
  31.             <input type="button" id="batchAddCard" name="batchAddCard" value="添加卡券" /><br />
  32.             <input type="button" id="openCard" name="openCard" value="拉起卡券库" /><br />
  33.             <input type="button" id="ShareTimeLine" name="ShareTimeLine" value="分享朋友圈" /><br />
  34.             <div id="showInfo">
  35.              
  36.             </div>
  37.         </div>
  38.          
  39.         <script>
  40.             wx.config({
  41.               debug: false,
  42.               appId: '<?php echo $signPackage["appId"];?>',
  43.               timestamp: <?php echo $signPackage["timestamp"];?>,
  44.               nonceStr: '<?php echo $signPackage["nonceStr"];?>',
  45.               signature: '<?php echo $signPackage["signature"];?>',
  46.               jsApiList: [
  47.                 // 所有要调用的 API 都要加到这个列表中
  48.                 'onMenuShareTimeline',
  49.                   'onMenuShareAppMessage',
  50.                   'addCard',
  51.                   'openCard'
  52.               ]
  53.             });
  54.              
  55.             wx.ready(function () {
  56.                 // 在这里调用 API
  57.                 wx.onMenuShareAppMessage({
  58.                     title: '互联网之子',
  59.                     desc: '在长大的过程中,我才慢慢发现,我身边的所有事,别人跟我说的所有事,那些所谓本来如此,注定如此的事,它们其实没有非得如此,事情是可以改变的。更重要的是,有些事既然错了,那就该做出改变。',
  60.                     link: 'http://movie.douban.com/subject/25785114/',
  61.                     imgUrl: 'http://demo.open.weixin.qq.com/jssdk/images/p2166127561.jpg',
  62.                     trigger: function (res) {
  63.                         // 不要尝试在trigger中使用ajax异步请求修改本次分享的内容,因为客户端分享操作是一个同步操作,这时候使用ajax的回包会还没有返回
  64.                         alert('用户点击发送给朋友');
  65.                     },
  66.                     success: function (res) {
  67.                         alert('已分享');
  68.                     },
  69.                     cancel: function (res) {
  70.                         alert('已取消');
  71.                     },
  72.                     fail: function (res) {
  73.                         alert(JSON.stringify(res));
  74.                     }
  75.                 });
  76.                  
  77.             document.querySelector('#ShareTimeLine').onclick = function () {
  78.                 wx.onMenuShareTimeline({
  79.                         title: '互联网之子',
  80.                         link: 'http://movie.douban.com/subject/25785114/',
  81.                         imgUrl: 'http://demo.open.weixin.qq.com/jssdk/images/p2166127561.jpg',
  82.                         trigger: function (res) {
  83.                                 // 不要尝试在trigger中使用ajax异步请求修改本次分享的内容,因为客户端分享操作是一个同步操作,这时候使用ajax的回包会还没有返回
  84.                                 alert('用户点击分享到朋友圈');
  85.                         },
  86.                         success: function (res) {
  87.                                 alert('已分享');
  88.                         },
  89.                         cancel: function (res) {
  90.                                 alert('已取消');
  91.                         },
  92.                         fail: function (res) {
  93.                                 alert(JSON.stringify(res));
  94.                         }
  95.                 });
  96.             };   
  97.              
  98.               document.querySelector('#batchAddCard').onclick = function () {
  99.                 wx.addCard({
  100.                   cardList: [
  101.                     {
  102.                       cardId: 'p7G0Cj_1HGF2nijO4sTlVTzawFhI',
  103.                       cardExt: '{"timestamp":"<?php echo $kqInfo['cardExt']['timestamp'];?>", "signature":"<?php echo $kqInfo['cardExt']['signature'];?>"}'
  104.                     }
  105.                   ],
  106.                   success: function (res) {
  107.                     var cardList = res.cardList; // 添加的卡券列表信息
  108.                     alert(cardList);
  109.                   },
  110.                 cancel: function (res) {
  111.                         alert('已取消');
  112.                 },
  113.                 fail: function (res) {
  114.                         alert(JSON.stringify(res));
  115.                 }
  116.                 });
  117.               };
  118.                
  119.               var shareData = {
  120.                 title: '微信JS-SDK Demo',
  121.                 desc: '微信JS-SDK,帮助第三方为用户提供更优质的移动web服务',
  122.                 link: 'http://demo.open.weixin.qq.com/jssdk/',
  123.                 imgUrl: 'http://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRt8Qia4lv7k3M9J1SKqKCImxJCt7j9rHYicKDI45jRPBxdzdyREWnk0ia0N5TMnMfth7SdxtzMvVgXg/0'
  124.               };
  125.                
  126.               wx.onMenuShareAppMessage(shareData);
  127.                
  128.               wx.onMenuShareTimeline(shareData);
  129.             });

  130.             var readyFunc = function onBridgeReady() {
  131.                 // 绑定关注事件
  132.                 document.querySelector('#openCard').addEventListener('click',
  133.                     function(e) {
  134.                         WeixinJSBridge.invoke('chooseCard', {
  135.                             "app_id": "<?php echo $listInfo['app_id']?>",
  136.                             "location_id ": '',
  137.                             "sign_type": "SHA1",
  138.                             "card_sign": "<?php echo $listInfo['card_sign']?>",
  139.                             "card_id": "<?php echo $listInfo['card_id']?>",
  140.                             "card_type": "<?php echo $listInfo['card_type']?>",
  141.                             "time_stamp": "<?php echo $listInfo['time_stamp']?>",
  142.                             "nonce_str": "<?php echo $listInfo['nonce_str']?>"
  143.                         },
  144.                     function(res) {
  145.                         alert(res.err_msg + res.choose_card_info);
  146.                         $("#showInfo").empty().append(res.err_msg + res.choose_card_info);
  147.                     });
  148.                 });
  149.             }
  150.              
  151.             if (typeof WeixinJSBridge === "undefined") {
  152.                 document.addEventListener('WeixinJSBridgeReady', readyFunc, false);
  153.             } else {
  154.                 readyFunc();
  155.             }

  156.           </script>
  157.     </body>
  158. </html>
复制代码
5. 创建卡券

  1. $kqinfo = array("card" => array());
  2. $kqinfo['card']['card_type'] = 'GENERAL_COUPON';
  3. $kqinfo['card']['general_coupon'] = array('base_info' => array(), 'default_detail' => array());
  4. $kqinfo['card']['general_coupon']['base_info']['logo_url'] = 'URL';
  5. $kqinfo['card']['general_coupon']['base_info']['code_type'] = 'CODE_TYPE_QRCODE';
  6. $kqinfo['card']['general_coupon']['base_info']['brand_name'] = '';
  7. $kqinfo['card']['general_coupon']['base_info']['title'] = '测试卡券';
  8. $kqinfo['card']['general_coupon']['base_info']['color'] = 'Color030';
  9. $kqinfo['card']['general_coupon']['base_info']['notice'] = '测试测试测试';
  10. $kqinfo['card']['general_coupon']['base_info']['description'] = '这是一张优惠券';
  11. $kqinfo['card']['general_coupon']['base_info']['date_info']['type'] = 1;
  12. $kqinfo['card']['general_coupon']['base_info']['date_info']['begin_timestamp'] = time();
  13. $kqinfo['card']['general_coupon']['base_info']['date_info']['end_timestamp'] = time() + 100 * 24 * 3600;
  14. $kqinfo['card']['general_coupon']['base_info']['sku']['quantity'] = 100000;
  15. $kqinfo['card']['general_coupon']['default_detail'] = '测试数据\n测试数据\n测试数据';

  16. //var_dump($kqinfo);
  17. //$kqinfo = json_encode($kqinfo);
  18. $kqinfo = C::enJson($kqinfo);

  19. //print_r( $kqinfo);
  20. //$resultData = $wx->wxCardCreated($kqinfo);
复制代码
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值