WxInvoice.php 17.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478
<?php

namespace common\exts\wechat;

use common\exts\Invoice\baiwang\InvoiceApi;
use common\exts\wechat\Log as WxLog;

/**
 * 微信电子发票参考 https://mp.weixin.qq.com/wiki?t=resource/res_main&id=21517918906Epe65
 *
 * 函数参数说明
 * makeOutInvoice的$params
 * 注1:ddh(订单号)需要和拉起授权页时的order_id保持一致,否则会出现未授权订单号的报错
   注2:fpqqlsh(发票请求流水号)为开票的唯一标识,头六位需要和后台的商户识别号保持一致
 * $params = array(
        "invoiceinfo" =>array(
            "wxopenid"=>  $revFromOpenId,"ddh" => $orderId,"fpqqlsh" => $fpqqlsh,
            "nsrsbh" => "91440300MA5ED5C341","nsrmc"=> "深圳市志云天计算机技术有限公司",
            "nsrdz"=> "深圳市南山区南头街道南山数字文化产业基地裙楼2楼3A",
            "nsrdh"=> "4000 361 360","nsrbank"=>  "中国工商银行股份有限公司深圳宝中支行","nsrbankid"=> "4000104009100129368",
            "ghfnsrsbh"=> "","ghfmc"=>  "许可","ghfdz"=> "","ghfdh"=> "","ghfbank"=>  "","ghfbankid"=>"",
            "kpr" =>  "管理员","skr"=>  "管理员","fhr"=> "管理员","jshj"=>  "1.03","hjje"=> "1.00","hjse"=>  "0.03","bz"=> "","hylx"=>  "0",
            "invoicedetail_list" => array(
                array(
                "fphxz"=> "0","spbm"=> "3040201030000000000","xmmc"=> "软件维护服务","dw"=> "","ggxh"=>"","xmsl"=>"1","xmdj"=> "1.00","xmje"=> "1.00","sl"=> "0.03","se"=>"0.03"
                )
            ),
            )
        );
 *
 *
 *  getAuthURL 的$params
 *  $params = array(
        "order_id" => "1234",
        "money" => 11,  // 以分为单位
        "source" => "web",  //	开票来源,app:app开票,web:微信h5开票,wxa:小程序开发票,wap:普通网页开票
        "redirect_url" => "https://mp.weixin.qq.com",
        "type": 1, //授权类型,0:开票授权,1:填写字段开票授权,2:领票授权
        )
 *
 * clearCardTpl 的$params
 *  logo_url 和title 必填
 * $params = array(
            "invoice_info"=> array(
                "base_info"=>array(
                    "logo_url"=> "http://mmbiz.qpic.cn/mmbiz/iaL1LJM1mF9aRKPZJkmG8xXhiaHqkKSVMMWeN3hLut7X7hicFNjakmxibMLGWpXrEXB33367o7zHN0CwngnQY7zb7g/0",
                    "title"=> "xx公司",
                    "custom_url_name"=> "xyz",
                    "custom_url"=> "xyz",
                    "custom_url_sub_title"=>"xyz",
                    "promotion_url_name"=> "puname",
                    "promotion_url"=> "purl",
                    "promotion_url_sub_title"=> "ptitle",
                ),
                "type" => " 广东省增值税普通发票 ",
                "payee" => " 测试 - 收款方 ",
            )
 * )
 *
 *
 *
 *
 * @package common\exts\wechat
 */
class WxInvoice
{
    const INVOICE_API_URL_PREFIX = 'https://api.weixin.qq.com';
    const SET_URL = '/card/invoice/seturl?';
    const SET_CONTACT = '/card/invoice/setbizattr?';
    const GET_AUTH_URL ='/card/invoice/getauthurl?';
    const CREATE_CARD_TPL = '/card/invoice/platform/createcard?';
    const MAKE_INVOICE = '/card/invoice/makeoutinvoice?';
    const CLEAR_OUT_INVOICE = '/card/invoice/clearoutinvoice?';
    const QUERY_INVOICE = '/card/invoice/queryinvoceinfo?';
    const GET_AUTH_DATA  = "/card/invoice/getauthdata?";

    const COMMERCIAL_ID = '9444ee'; //商户识别号 微信电子发票那里获取
    const S_PAPPID = 'd3hlZGY2OTZlZGRiMGIwM2YwX8c5w43vO9QvbNKSjI2KBuEHMd3vBhSbw4/mGKz7G+VW'; // 微信电子发票那里获取

    static $errcode = 0;
    static $errmsg = '';

    /** 获取微信提供的商品类型
     * @param int $index
     * @return array
     */
    public static function getWxGoodsCode($index = 0)
    {
        $gArray = array(
            0 => array('id'=> "3040201030000000000", 'name' => '软件维护服务', 'rate' => 0.03),
        );
        if ( isset($gArray[$index])) {
            return $gArray[$index];
        } else {
            return $gArray;
        }
    }

    public static function getInvoiceSetUrl($appId, $appSecret)
    {
        $access_token = AccessToken::get($appId, $appSecret);
        if (!$access_token)
            return false;
        $params = '{}';
        $url = self::INVOICE_API_URL_PREFIX. self::SET_URL. "access_token={$access_token}";
        $result = Http::post($url,$params);
        if ($result) {
            $json_arr = json_decode($result, true);
            self::$errcode = $json_arr['errcode'];
            self::$errmsg = $json_arr['errmsg'];
            if (0 == $json_arr['errcode'] && 'ok' == $json_arr['errmsg']) {
                return $json_arr['invoice_url'];
            } else {
                return '';
            }
        }
        return false;
    }

    /** 设置商户联系方式。
     * @param $appId
     * @param $appSecret
     * @param int $expire
     * @return bool
     */
    public static function setContact($appId, $appSecret, $expire = 1800)
    {
        $access_token = AccessToken::get($appId, $appSecret);
        if (!$access_token)
            return false;
        $url = self::INVOICE_API_URL_PREFIX . self::SET_CONTACT."action=set_contact&access_token={$access_token}";
        $params = array('contact' => array("phone" => "4000 361 360", "time_out" => $expire));
        $result = Http::post($url, PHPSDK::json_encode($params));
        if ($result) {
            $json_arr = json_decode($result, true);
            self::$errcode = $json_arr['errcode'];
            self::$errmsg = $json_arr['errmsg'];
            if (0 == $json_arr['errcode'] && 'ok' == $json_arr['errmsg']) {
                return true;
            } else {
                return false;
            }
        }
        return false;
    }

    /** 获取商家联系方式
     * @param $appId
     * @param $appSecret
     * @return bool
     */
    public static function getContact($appId, $appSecret)
    {
        $access_token = AccessToken::get($appId, $appSecret);
        if (!$access_token)
            return false;
        $url = self::INVOICE_API_URL_PREFIX . self::SET_CONTACT."action=get_contact&access_token={$access_token}";

        $result = Http::post($url, '{}');
        if ($result) {
            $json_arr = json_decode($result, true);
            self::$errcode = $json_arr['errcode'];
            self::$errmsg = $json_arr['errmsg'];
            if (0 == $json_arr['errcode'] && 'ok' == $json_arr['errmsg']) {
                return $json_arr['contact'];
            } else {
                return false;
            }
        }
        return false;
    }

    /** 获取授权页
     * @param $appId
     * @param $appSecret
     * @param $params
     * @return bool|string
     */
    public static function getAuthURL($appId, $appSecret, $params)
    {
        $access_token = AccessToken::get($appId, $appSecret);
        if (!$access_token) {
            return false;
        }

        $params['ticket'] = WxTicket::getWxCardTicket($appId, $appSecret);
        $params['s_pappid'] = self::S_PAPPID;
        $params['timestamp'] = time();
        $url = self::INVOICE_API_URL_PREFIX . self::GET_AUTH_URL."access_token={$access_token}";
        $result = Http::post($url, PHPSDK::json_encode($params));
        if ($result) {
            $json_arr = json_decode($result, true);
            self::$errcode = $json_arr['errcode'];
            self::$errmsg = $json_arr['errmsg'];
            if (0 == $json_arr['errcode'] && 'ok' == $json_arr['errmsg']) {
                return $json_arr['auth_url'];
            } else {
                return '';
            }
        }
        return false;
    }

    /** 查询授权完成状态
     * @param $appId
     * @param $appSecret
     * @param $params = array('order_id' => $order_id); //'s_pappid'=>$s_pappid,
     * @return bool|mixed|string
     *
     * 若用户填入的是个人抬头:
        {
        "errcode": 0,"errmsg": "ok","invoice_status": "auth success","auth_time": 1480342498,
        "user_auth_info": {
                "user_field": {
                    "title": "Dhxhhx ","phone": "5554545","email": "dhxhxhhx@qq.cind",
                    "custom_field": [{"key": "field1","value": "管理理论"}]
                }
            }
        }
        若用户填入的是单位抬头:
        {
            "errcode": 0,"errmsg": "ok","invoice_status": "auth success","auth_time": 1480342897,
            "user_auth_info": {
            "biz_field": {
                "title": "xx公司","tax_no": "6464646766","addr": "xx大厦","phone": "1557548768","bank_type": "xx银行","bank_no": "545454646",
                "custom_field": [{"key": "field2","value": "哈哈哈啊"}]
                }
            }
        }
     *
     */
    public static function getAuthData($appId, $appSecret, $params)
    {
        $access_token = AccessToken::get($appId, $appSecret);
        if (!$access_token) {
            return false;
        }

        $params['s_pappid'] = self::S_PAPPID;
        $url = self::INVOICE_API_URL_PREFIX . self::GET_AUTH_DATA."access_token={$access_token}";
        $result = Http::post($url, PHPSDK::json_encode($params));
        if ($result) {
            $json_arr = json_decode($result, true);
            self::$errcode = $json_arr['errcode'];
            self::$errmsg = $json_arr['errmsg'];
            if ( 0 == $json_arr['errcode'] && 'ok' == $json_arr['errmsg'] ) {
                return $json_arr;
            } else {
                return '';
            }
        }
        return false;
    }

    /**  创建发票模板
     * @param $appId
     * @param $appSecret
     * @param $params
     * @return bool|string
     * return
     * {
        "errcode": 0,
        "errmsg": "ok",
        "card_id": "pjZ8Yt9WoOePThU0NfUKz5-tBEWU"
        }
     * 用户公众号 的logo_url 为[ "media_id" => "OiLrbltmwUcecAs6zkpllIgof83VuKgNYiXvt3HT1ZQ" ,"url" => "http://mmbiz.qpic.cn/mmbiz_jpg/iavrxzR4PicoXWn4lopWic5eiaQVONQhdia5brhEhCgTVq54cVEWKrw7sia8WEKEM4tfobonQo68aPwSXBjrE8ZkNhIA/0?wx_fmt=jpe"】
     */
    public static function createCardTpl($appId, $appSecret, $params)
    {
        $access_token = AccessToken::get($appId, $appSecret);
        if (!$access_token)
            return false;

        $url = self::INVOICE_API_URL_PREFIX . self::CREATE_CARD_TPL."access_token={$access_token}";
        $result = Http::post($url, PHPSDK::json_encode($params));
        if ($result) {
            $json_arr = json_decode($result, true);
            self::$errcode = $json_arr['errcode'];
            self::$errmsg = $json_arr['errmsg'];
            if (0 == $json_arr['errcode'] && 'ok' == $json_arr['errmsg']) {
                return $json_arr['card_id'];
            } else {
                return '';
            }
        }
        return false;
    }

    /** 统一开票接口-开具蓝票
     * @param $appId
     * @param $appSecret
     * @param $params
     * @return bool|mixed
     */
    private static function makeInvoiceApi($appId, $appSecret, $params)
    {
        $access_token = AccessToken::get($appId, $appSecret);
        if (!$access_token) {
            return false;
        }

        $url = self::INVOICE_API_URL_PREFIX . self::MAKE_INVOICE."access_token={$access_token}";
        $result = Http::post($url, PHPSDK::json_encode($params));WxLog::init();WxLog::DEBUG('===  makeInvoiceApi  ===:'.$result);
        if ($result) {
            $json_arr = json_decode($result, true);
            self::$errcode = $json_arr['errcode'];
            self::$errmsg = $json_arr['errmsg'];
            if (0 == $json_arr['errcode']) {
                return true;
            } else {
                return $json_arr;
            }
        }
        return false;
    }

    /** 开蓝票接口
     * @param $appId
     * @param $appSecret
     * @param $params = array('openid'=> '', 'orderId'=>'', 'ghfmc'=> '', 'ghfnsrsbh' => 'jshj'=>'', 'fpqqlsh'=>'',)
     *  公司 'ghfmc' 和 'ghfnsrsbh' 必填
     * @return \stdClass
     */
    public static function makeInvoice($appId, $appSecret, $params)
    {
        WxLog::init();
        $e = new \stdClass();
        $e->success = false;
        $e->error = 'ok';
        $e->fpqqlsh = null;
        $tt = time();

        if ( !isset($params['fpqqlsh']) || empty($params['fpqqlsh']) ) {
            $params['fpqqlsh'] = self::COMMERCIAL_ID . $tt . mt_rand(1,1000);
        } else {
            $pre = substr($params['fpqqlsh'], 0, 6);
            if (self::COMMERCIAL_ID != $pre ) {
                $params['fpqqlsh'] = self::COMMERCIAL_ID . $params['fpqqlsh'];
            }
        }

        if (empty($params['ghfmc']) || !isset($params['ghfmc'])) {
            $e->error = 'ghfmc';
            return $e;
        }

        if (empty($params['jshj']) || !isset($params['jshj'])) {
            $e->error = 'jshj';
            return $e;
        }

        if ($params['jshj'] < 0) {
            $e->error = '-jshj';
            return $e;
        }

        $goods = self::getWxGoodsCode();

        $params['ghfnsrsbh'] = isset($params['ghfnsrsbh'])?$params['ghfnsrsbh']:'';
        $params['ghfdz'] = isset($params['ghfdz'])?$params['ghfdz']:'';
        $params['ghfdh'] = isset($params['ghfdh'])?$params['ghfdh']:'';
        $params['ghfbank'] = isset($params['ghfbank'])?$params['ghfbank']:'';
        $params['ghfbankid'] = isset($params['ghfbankid'])?$params['ghfbankid']:'';
        $params['bz'] = isset($params['bz'])?$params['bz']:'';

        $hjje = round($params['jshj']/(1+$goods['rate']),2);
        $hjse = $params['jshj'] - $hjje;
        $apiParams = array(
                "invoiceinfo"   => array(
                "wxopenid"  =>  $params['openid'],
                "ddh"       => $params['orderId'],
                "fpqqlsh"   => $params['fpqqlsh'],
                "nsrsbh"    => InvoiceApi::SELF_COMPANY_TAX_ID,
                "nsrmc"     => InvoiceApi::SELF_COMPANY_NAME,
                "nsrdz"     => InvoiceApi::SELF_COMPANY_ADDRESS,
                "nsrdh"     => InvoiceApi::SELF_COMPANY_TEL,
                "nsrbank"   => InvoiceApi::SELF_COMPANY_BANK_NAME,
                "nsrbankid" => InvoiceApi::SELF_COMPANY_BANK_ID,
                "ghfnsrsbh" => $params['ghfnsrsbh'],
                "ghfmc"     => $params['ghfmc'],
                "ghfdz"     => $params['ghfdz'],
                "ghfdh"     => $params['ghfdh'],
                "ghfbank"   => $params['ghfbank'],
                "ghfbankid" => $params['ghfbankid'],
                "kpr"       => "管理员",
                "skr"       => "管理员",
                "fhr"       => "管理员",
                "jshj"      => sprintf("%.2f", round($params['jshj'], 2)),
                "hjje"      => sprintf("%.2f", $hjje),
                "hjse"      => sprintf("%.2f", $hjse),
                "bz"        => $params['bz'],
                "hylx"      => "0",
                "invoicedetail_list" => array(
                    array(
                        "fphxz" => "0",
                        "spbm" => $goods['id'],
                        "xmmc" => $goods['name'],
                        "dw" => "",
                        "ggxh" => "",
                        "xmsl" => "1",
                        "xmdj" => sprintf("%.2f", $hjje),
                        "xmje" => sprintf("%.2f", $hjje),
                        "sl" => $goods['rate'],
                        "se" => sprintf("%.2f", $hjse)
                    )
                ),
            )
        );
        $result = self::makeInvoiceApi($appId, $appSecret, $apiParams);
        //WxLog::DEBUG('make out invoice data '. json_encode($params));
        $e->success = true;
        $e->fpqqlsh = $params['fpqqlsh'];
        $e->result = $result;
        return $e;
    }

    /** 统一开票接口-发票冲红
     * @param $appId
     * @param $appSecret
     * @param $params = array('invoiceinfo'=>array("wxopenid"=>"os92LxEDbiOw7kWZanRN_Bb3Q45I", "fpqqlsh"=>"test20160511000400", "yfpdm"=>"050003521100","yfphm"=>"30329969")) //"nsrsbh"=>"110109500321654","nsrmc"=>"百旺电子测试1",
     * @return bool|mixed
     */
    public static function clearOutInvoice($appId, $appSecret, $params)
    {
        $access_token = AccessToken::get($appId, $appSecret);
        if (!$access_token)
            return false;
        $params['nsrmc'] = InvoiceApi::SELF_COMPANY_NAME;
        $params['nsrsbh'] = InvoiceApi::SELF_COMPANY_TAX_ID;
        $url = self::INVOICE_API_URL_PREFIX . self::CLEAR_OUT_INVOICE."access_token={$access_token}";
        $result = Http::post($url, PHPSDK::json_encode($params));
        if ($result) {
            $json_arr = json_decode($result, true);
            self::$errcode = $json_arr['errcode'];
            self::$errmsg = $json_arr['errmsg'];
            if (0 == $json_arr['errcode']) {
                return true;
            } else {
                return $json_arr;
            }
        }
        return false;
    }

    /**  统一开票接口-查询已开发票
     * @param $appId
     * @param $appSecret
     * @param $fpqqlsh 发票请求流水号,唯一查询发票的流水号
     * @param $nsrsbh 纳税人识别码
     * @return bool|mixed
     *
     * {"errcode": 0,"errmsg": "发票数据获取成功",
        "invoicedetail": {
        "fpqqlsh": "14574d75004451097845","fpdm": "088978450417","fphm": "21590001","jym": "59004166725791147047","kprq": "20171204172159","pdfurl": "http://weixin.com"
        }
        }
     */
    public static function queryInvoice($appId, $appSecret, $fpqqlsh, $nsrsbh)
    {
        $access_token = AccessToken::get($appId, $appSecret);
        if (!$access_token)
            return false;
        $params = array('fpqqlsh'=> $fpqqlsh, 'nsrsbh' => $nsrsbh);
        $url = self::INVOICE_API_URL_PREFIX . self::QUERY_INVOICE."access_token={$access_token}";
        $result = Http::post($url, PHPSDK::json_encode($params));
        if ($result) {
            $json_arr = json_decode($result, true);
            self::$errcode = $json_arr['errcode'];
            self::$errmsg = $json_arr['errmsg'];
            if (0 == $json_arr['errcode'] ) {
                return $json_arr;
            } else {
                return false;
            }
        }
        return false;
    }
}