Jssdk.php 12.2 KB
<?php
/**
 * tpshop
 * ============================================================================
 * 版权所有 2015-2027 深圳搜豹网络科技有限公司,并保留所有权利。
 * 网站地址: http://www.tp-shop.cn
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件!您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * Author: IT宇宙人
 * Date: 2015-09-09
 * 参考地址 http://www.cnblogs.com/txw1958/p/weixin-js-sharetimeline.html
 * http://mp.weixin.qq.com/wiki/7/aaa137b55fb2e0456bf8dd9148dd613f.html  微信JS-SDK说明文档
 */
namespace app\mobile\logic;

use think\image\Exception;
use think\Model;
use think\Db;

/**
 * 分类逻辑定义
 * Class CatsLogic
 * @package Home\Logic
 */
class Jssdk extends Model
{

    private $appId;
    private $appSecret;
    public function __construct($appId, $appSecret)
    {
        $this->appId = $appId;
        $this->appSecret = $appSecret;
    }

    // 签名
    public function getSignPackage($url = '')
    {
        $jsapiTicket = $this->getJsApiTicket();

        // 注意 URL 一定要动态获取,不能 hardcode.
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $url = empty($url) ? "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]" : $url;

        $timestamp = time();
        $nonceStr = $this->createNonceStr();

        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";

        $signature = sha1($string);

        $signPackage = array(
            "appId" => $this->appId,
            "nonceStr" => $nonceStr,
            "timestamp" => $timestamp,
            "url" => $url,
            "rawString" => $string,
            "signature" => $signature

        );
        return $signPackage;
    }

    // wx_card签名
    public function getSignPackage_card($cardid="",$code,$openid)
    {
        $jsapiTicket = $this->getJsApiTicket('wx_card');

        $timestamp = time();
        $nonceStr = $this->createNonceStr();

        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
      // $string = "$code$timestamp$jsapiTicket$nonceStr$openid$cardid";


        //$signature = sha1($string);

        $signPackage = array(
            "appId" => $this->appId,
            "code" => $code,
            "nonceStr" => $nonceStr,
            "openid" => $openid,
            "jsapiTicket" => $jsapiTicket,
            "cardid" => $cardid,
            "timestamp" => $timestamp
          //  "rawString" => $string,
          //  "signature" => $signature

        );
        return $signPackage;
    }

    // 随机字符串
    private 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;
    }

    /**
     * 根据 access_token 获取 icket
     * @return type
     */
    public function getJsApiTicket($type='jsapi')
    {
        $ticket = S('ticket_'.$type. $this->appId);
        if (!empty($ticket))
            return $ticket;

        $wat=M('wx_user')->where("appid",$this->appId)->find();
        //$access_token = $this->get_access_token();
        $access_token =m_get_access_token($wat,$wat['store_id']);
        $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={$access_token}&type=".$type;
        $return = httpRequest($url, 'GET');
        $return = json_decode($return, 1);
        S('ticket_'.$type. $this->appId, $return['ticket'], 7000);
        return $return['ticket'];
    }




    /**
     * 获取 网页授权登录access token
     * @return type
     */
    public function getAccessToken()
    {
        //判断是否过了缓存期
        /*----
        $access_token = S('access_token'. $this->appId);
        if (!empty($access_token))
            return $access_token;

        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appId}&secret={$this->appSecret}";
        $return = httpRequest($url, 'GET');
        $return = json_decode($return, 1);
        S('access_token'. $this->appId, $return['access_token'], 7000);
        return $return['access_token'];--*/
        $wechat = M('wx_user')->where(array('appid' => $this->appId))->find();
        return m_get_access_token($wechat,$wechat['store_id']);

    }

    // 获取一般的 access_token
    public function get_access_token()
    {
        //判断是否过了缓存期
        /*---
        $wechat = M('wx_user')->where(array('appid' => $this->appId))->find();
        mlog($this->appId, "Jssk");
        $expire_time = $wechat['web_expires'];
        if ($expire_time > time()) {
            //return $wechat['web_access_token'];
        }
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$wechat['appid']}&secret={$wechat['appsecret']}";
        $return = httpRequest($url, 'GET');
        mlog($return,'getacctk');


        $return = json_decode($return, 1);
        $web_expires = time() + 7000; // 提前200秒过期
        M('wx_user')->where(array('id' => $wechat['id']))->save(array('web_access_token' => $return['access_token'], 'web_expires' => $web_expires));
        return $return['access_token'];--*/
        $wechat = M('wx_user')->where(array('appid' => $this->appId))->find();
        return m_get_access_token($wechat,$wechat['store_id']);

    }

    /*
     * 向用户推送普通消息
     */
    public function push_msg($openid, $content)
    {
        $access_token = $this->get_access_token();
        $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={$access_token}";
        $post_arr = array(
            'touser' => $openid,
            'msgtype' => 'text',
            'text' => array(
                'content' => $content,
            )
        );
        $post_str = json_encode($post_arr, JSON_UNESCAPED_UNICODE);
        $return = httpRequest($url, 'POST', $post_str);
        //mlog($return,'push_msg');
        $return = json_decode($return, true);
        return $return;
    }

/// <summary>
    /// 微信消息模板方法   ------手店线下ERP接口(使用中)
    /// </summary>
    /// <param name="stoid">商户ID</param>
    /// <param name="OpenId">消息模板推送客户微信id</param>
    /// <param name="typeid">模板类型,例:1001、1002</param>
    /// <param name="backurl">消息模版点击跳转url地址   为空取值数据库</param>
    /// <param name="htmlurl">消息推送后微信方返回详细结果接收网址,如不需要详细可随意传值</param>
    /// <param name="$Object">模板参数集合,务必根据模板参数的顺序传入对应的值</param>
    /// <param name="$wxsendlist">模板列表值</param>
    /// <param name="$wxsendtype">模板参数值</param>
    ///  <param name="$number">批次号</param>
    ///  <param name="$mob">手机号</param>
    public function WeiXin_MassageModelSend($stoid, $OpenId, $typeid, $backurl, $Object,$wxsendlist=null,$wxsendtype=null,$number='',$mob='',$str_WeiXinAccessToken='')
    {
        //根据方法获取微信参数Access_token
        //$str_WeiXinAccessToken = $this->get_access_token();

        if (empty($str_WeiXinAccessToken)) {
            $str_WeiXinAccessToken = m_get_access_token(null, $stoid);
        }

        //组合要发送的微信接口地址
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$str_WeiXinAccessToken;
        if ($wxsendlist)
        {
            $res = $wxsendlist;
        }
        else {
            $res = M("wx_sendlist")->where("store_id", $stoid)->where("typeid", $typeid)->find();
        }
        if ($res && !empty($res["template_id"])) {
            //$IsBackMessage;
            //模版消息跳转地址获取原则   若接口有传入url参数 则取接口url值 若没有参数参数取数据库设置url值
            $defaulturl=curHostURL()."/mobile/User/index/stoid/".$stoid;
            if (empty($backurl)) $backurl = empty($res["htmlurl"]) ? $defaulturl : $res["htmlurl"];


            /*--获取发报的内容--*/
            mlog("批次号:".$number."[".$OpenId."]:".json_encode($Object),"send_res/".$stoid);
            $strPost =$this->GetWeiXinMessageModelStr($typeid, $OpenId, $res["template_id"], $backurl, $Object,$wxsendtype,$res['template_type']);
            mlog("批次号:".$number."[".$OpenId."]:".$strPost,"send_res/".$stoid);


            if(!empty($strPost)){
                $return = httpRequest($url, 'POST', $strPost,array(),false,1);
                mlog("结果:批次号".$number."[".$OpenId."]".$return,"send_res/".$stoid);
                $data = json_decode($return,true);
                //{"errcode":0,"errmsg":"ok","msgid":202582287}
                if (!empty($data) && $data["errcode"] ==0) {
                    return ['wxcode'=>0,'msg'=>'ok'];
                } else if(!empty($data) && $data["errcode"] != 0 ) {
                    $result = "发送失败,报文错误:".(empty($data["errmsg"])?"":$data["errmsg"]);
                    return ['wxcode'=>$data["errcode"],'msg'=>$result];
                }else{
                    $result = "发送失败,报文获取失败";
                    return ['wxcode'=>-9999,'msg'=>$result];
                }
            }else{
                $result = "发送失败,报文获取失败";
                return ['wxcode'=>-9999,'msg'=>$result];
            }

        }else{
            $result = "发送失败,商户未选择该模板";
            return ['wxcode'=>-9999,'msg'=>$result];
        }
        //return $result;
    }
    /// <summary>
    /// 获取微信发送报文
    /// </summary>
    /// <param name="typeid">模板本地id</param>
    /// <param name="openid">发送方openid</param>
    /// <param name="template_id">模板微信id</param>
    /// <param name="url">获取信息url</param>
    /// <param name="$Object">其他参数</param>
    /// <param name="$wx_sendtype">对应值 </param>
    /// <param name="$template_type">该类型的格式</param>
    /// <returns></returns>
    public function GetWeiXinMessageModelStr($typeid, $openid, $template_id, $url, $Object,$wx_sendtype=null,$template_type=1)
    {

        $result = "";
        mlog(json_encode($Object),"GetWeiXinMessageModelStr/".$typeid);
        if ($Object['colorlist'])
        {
            $arrcolor = explode('|', urldecode($Object['colorlist']));
        }
        else
        {
            $arrcolor = ["#f00", "#173177", "#173177", "#173177", "#173177", "#173177", "#f00", "#f00"];
        }
//        if (count($Object) > 7) {
//            $Object[7]=urldecode($Object[7]);
//            $arrcolor = explode('|', $Object[7]);
//        } else
//            $arrcolor = ["#f00", "#173177", "#173177", "#173177", "#173177", "#173177", "#f00", "#f00"];

        $post_arr['touser']=$openid;
        $post_arr['template_id']=$template_id;
        $post_arr['url']=$url;
        $post_arr['topcolor']=$arrcolor[0];
        if ($wx_sendtype)
        {
            $rs =$wx_sendtype;
        }
        else {

            if ($template_type>1)
            {
                $rs = M("wx_sendtypelist")->where(array('typeid'=>$typeid,'ordid'=>$template_type))->find();
            }
            else
            {
                $rs = M("wx_sendtype")->where("typeid", $typeid)->find();
            }

        }

        if($rs['myremark']) {
            $renarr=explode(",",$rs['myremark']);
            foreach ($renarr as $k=>$v){
                $post_arr['data'][$v]['value']=$Object[$k];
                $post_arr['data'][$v]['color']=$arrcolor[$k];
            }
            try {
                $result = json_encode($post_arr, JSON_UNESCAPED_UNICODE);
            }catch (Exception $e){
                mlog("转码失败","send_res");
            }
            return $result;
        }
        return $result;
    }
}