Home  >  Article  >  Backend Development  >  PHP: Things related to the development of WeChat payment service providers

PHP: Things related to the development of WeChat payment service providers

步履不停
步履不停Original
2019-07-02 17:56:463829browse

PHP: Things related to the development of WeChat payment service providers

Project background

It is not a big project. We use WeChat service provider to manage multiple sub-merchant, and use the service provider’s interface to replace the sub-merchant. Only after placing an order can the service provider's background receive a callback.

The usage scenario is web scan code payment

Preparation

The domain name should belong to the service provider Set the "webpage authorized domain name" in the official account (I wonder if this operation is required?)

Set the callback address in the payment service provider's background (sub-merchant should not need to set it)

Project use apache php is the background service, download the official paid php demo (native)

We will play directly according to the directory structure of the demo, and directly put the decompressed example and lib directories into the server root directory

In the example directory, create the cert directory, go to the service provider's backend-account center-api security, download the certificate, and put it in this directory

In the example directory, create the logs directory for WeChat payment Log class writes log files

Since WeChat payment requires https, check the access log in the logs directory under the apache directory, the ssl_request.txt file, and at the bottom, you can see whether the callback address has been requested

Note

The official demo has two ways to scan the QR code to pay. The first method is no longer available, so the second one is used.

The official demo , there will be a bug that cannot display the QR code. The example page is native.php

print print_r($result); This will display errors, mainly about curl errors, which can be solved by Baidu yourself

Configuration

Add a public method to the interface object in WxPay.Config.Interface.php public abstract function GetSubMchId(); //Get the sub-merchant id in WxPay.Config In .php, configure the required parameters, use Baidu by yourself, and add a method public function GetSubMchId(){ return '8888888888'; //Return the sub-merchant number by vbyzc } In lib/WxPay.Api.php, under the unified In the single method unifiedOrder, add $inputObj->SetSub_mch_id($config->GetSubMchId());//Sub-merchant number by vbyzc in each place where the order needs to be queried, and the payment page will be called back in real time This method must be used to set the sub-merchant id on the request page that detects the order payment status:
$input->SetSub_mch_id($config->GetSubMchId()); Note that there may be no $config object in some places. Please introduce WxPay.Config.php and initialize: $config = new WxPayConfig();

Part of the code

Scan code page: native.php

SetBody("test_body");
$input->SetAttach("test_Attach");//成功支付的回调里会返回这个
$input->SetOut_trade_no($out_trade_no);//自定义订单号
$input->SetTotal_fee("1"); // 金额
$input->SetTime_start(date("YmdHis"));
// $input->SetTime_expire(date("YmdHis", time() + 500));
$input->SetGoods_tag("test_goodsTag");
$input->SetNotify_url("https://service.ktfqs.com/example/wx_pay_callback.php");
$input->SetTrade_type("NATIVE");
$input->SetProduct_id("123456789"); //此id为二维码中包含的商品ID,商户自行定义。

$result = $notify->GetPayUrl($input);
$url2 = $result["code_url"];

echo "
这是返回:$url2
"; print_r($result); ?> 扫码支付
扫描支付模式二

订单编号
模式二扫码支付
支付提示:WAITING...

Query and return the order status page: orderqueryajax.php

SetOut_trade_no($out_trade_no);
    $input->SetSub_mch_id($config->GetSubMchId());//子商户号 by vbyzc
    $result = WxPayApi::orderQuery($config, $input);
    if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS'){//返回查询结果
        echo $result['trade_state'];
    }else{
        echo "FAIL";
    }
}
?>

Callback page: notify.php

SetTransaction_id($transaction_id);
        $input->SetSub_mch_id($config->GetSubMchId()); //设置子商户号  by vbyzc
        $result = WxPayApi::orderQuery($config, $input);
        Log::DEBUG("query:" . json_encode($result));
        if(array_key_exists("return_code", $result)
            && array_key_exists("result_code", $result)
            && $result["return_code"] == "SUCCESS"
            && $result["result_code"] == "SUCCESS")
        {
            return true;
        }
        return false;
    }

    /**
    *
    * 回包前的回调方法
    * 业务可以继承该方法,打印日志方便定位
    * @param string $xmlData 返回的xml参数
    *
    **/
    public function LogAfterProcess($xmlData)
    {
        Log::DEBUG("call back, return xml:" . $xmlData);
        return;
    }
    
    //重写回调处理函数
    /**
     * @param WxPayNotifyResults $data 回调解释出的参数
     * @param WxPayConfigInterface $config
     * @param string $msg 如果回调处理失败,可以将错误信息输出到该方法
     * @return true回调出来完成不需要继续回调,false回调处理未完成需要继续回调
     */
    public function NotifyProcess($objData, $config, &$msg)
    {
        $data = $objData->GetValues();
        //TODO 1、进行参数校验
        if(!array_key_exists("return_code", $data) 
            ||(array_key_exists("return_code", $data) && $data['return_code'] != "SUCCESS")) {
            //TODO失败,不是支付成功的通知
            //如果有需要可以做失败时候的一些清理处理,并且做一些监控
            $msg = "异常异常";
            return false;
        }
        if(!array_key_exists("transaction_id", $data)){
            $msg = "输入参数不正确";
            return false;
        }

        //TODO 2、进行签名验证
        try {
            $checkResult = $objData->CheckSign($config);
            if($checkResult == false){
                //签名错误
                Log::ERROR("签名错误...");
                return false;
            }
        } catch(Exception $e) {
            Log::ERROR(json_encode($e));
        }

        //TODO 3、处理业务逻辑
        Log::DEBUG("call back JSON:" . json_encode($data));
        $notfiyOutput = array();
        /* 返回的格式 
        {
            "appid": "wxa664cef2fee1b641", //调用接口提交的公众账号ID
            "attach": "test",//附加数据,在查询API和支付通知中原样返回,该字段主要用于商户携带订单的自定义数据 (使用SetAttach设置的)
            "bank_type": "LQT",//不知什么鬼东西
            "cash_fee": "1",// 金额
            "fee_type": "CNY",//货币类型
            "is_subscribe": "N",//不知什么鬼东西
            "mch_id": "154133502151",// 商户号(服务商)
            "nonce_str": "jw0bvddz275qyvxnpdfoaam55h3dw6uk",//微信返回的随机字符串
            "openid": "opnVE5pDPx2hWAoLLxyQW5KQt8GA",// 用户openid(应该是对于绑定的公从号)
            "out_trade_no": "vbyzc_for_jstx20190701010509",// 发起订单时自定义订单号
            "result_code": "SUCCESS",// 业务结果
            "return_code": "SUCCESS",// 此字段是通信标识,非交易标识,交易是否成功需要查看result_code来判断
            "sign": "80E46C6CC50C25E6B5099AE4E03DA3C6FEFD5B172A99B03A56FAC4A9E11EC8F3",//
            "sub_mch_id": "154172463171",// 子商户id
            "time_end": "20190701090530",// 交易结束时间??
            "total_fee": "1",// 总金额
            "trade_type": "NATIVE",// 支付方式
            "transaction_id": "4200000301201907011310094985" // 微信支付单号
        }
        */
        //查询订单,判断订单真实性
        if(!$this->Queryorder($data["transaction_id"])){
            $msg = "订单查询失败";
            Log::DEBUG("vbyzc run to here : order querySelect faild!!!!!" );
            return false;
        }
        // 根据微信官方原代码的业务流程,应该是如下:
        // 支会成功后微信会不断请求回调,在上面的代码 应该是包函了回调回应的代码,
        // 如果成功回应,微信支付应该就停止请求回调,才能执行下面的代码 
        Log::DEBUG("vbyzc run to here :<<<<<<<<<<<<<>>>>>>>>>" );
        return true;
    }
}

$config = new WxPayConfig();
Log::DEBUG("begin notify");
$notify = new PayNotifyCallBack();
$notify->Handle($config, false);


?>

For more PHP related technical articles, please visit PHP Tutorial Column for learning!

The above is the detailed content of PHP: Things related to the development of WeChat payment service providers. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn