search
HomeBackend DevelopmentPHP TutorialPHP development WeChat payment enterprise payment example code

Application scenarios of enterprise payment: Public accounts make payments to users who have followed them, such as processing refunds, financial settlements, etc. This article mainly shares with you the example code of developing WeChat payment enterprise payment in PHP, hoping to help everyone.

Instructions

1. The certificate needs to be the certificate from your own merchant (note: the certificate path must be an absolute path. If you use a relative path, the following error will be reported.

unable to use client certificate (no key found or wrong pass phrase?)

2. Just fill in your own appid, secret and key

Let’s talk about the implementation first. Idea:

1. First get the openid, the specific method is as follows

2. Fill in the required parameters, generate a signature, etc., the specific method is as follows

/** 
* API 参数 
* @var array 
* ‘mch_appid’ # 公众号APPID 
* ‘mchid’ # 商户号 
* ‘device_info’ # 设备号 
* ‘nonce_str’ # 随机字符串 
* ‘partner_trade_no’ # 商户订单号 
* ‘openid’ # 收款用户openid 
* ‘check_name’ # 校验用户姓名选项 针对实名认证的用户 
* ‘re_user_name’ # 收款用户姓名 
* ‘amount’ # 付款金额 
* ‘desc’ # 企业付款描述信息 
* ‘spbill_create_ip’ # Ip地址 
* ‘sign’ # 签名 
*/
##.
#Parameter reference: Enterprise payment API documentation

1. Get CODE (index.php page)

<?php //信息回调文件所在的服务器位置$str="http://www.xxx.com/company_pay/getInfo.php";$str_url=urlencode($str);$appid = "xxxx3e5273505e";$url = &#39;https://open.weixin.qq.com/connect/oauth2/authorize?appid=&#39;.$appid.&#39;&redirect_uri=&#39;.$str_url.&#39;&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect&#39;;

header("Location:".$url);?>

2. Information callback page code processing (getInfo.php)

<?php$appid = "wxxxxx3505e";//你的微信公众平台的appid$secret = "fxxxxx71xxx4cda2a671";//你微信公众平台的secret$code = $_GET["code"];$get_token_url = &#39;https://api.weixin.qq.com/sns/oauth2/access_token?appid=&#39;.$appid.&#39;&secret=&#39;.$secret.&#39;&code=&#39;.$code.&#39;&grant_type=authorization_code&#39;;$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$get_token_url);
curl_setopt($ch,CURLOPT_HEADER,0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);$res = curl_exec($ch);
curl_close($ch);$json_obj = json_decode($res,true);//根据openid和access_token查询用户信息$access_token = $json_obj[&#39;access_token&#39;];$openid = $json_obj[&#39;openid&#39;];$get_user_info_url = &#39;https://api.weixin.qq.com/sns/userinfo?access_token=&#39;.$access_token.&#39;&openid=&#39;.$openid.&#39;&lang=zh_CN&#39;;$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$get_user_info_url);
curl_setopt($ch,CURLOPT_HEADER,0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);$res = curl_exec($ch);
curl_close($ch);//解析json$user_obj = json_decode($res,true);//var_dump($user_obj);echo "<br/>"."-----".$openid."*****";$mch_appid=$appid;$mchid=&#39;10000401&#39;;//商户号$nonce_str=&#39;vhmake&#39;.rand(100000, 999999);//随机数$partner_trade_no=&#39;VH&#39;.time().rand(10000, 99999);//商户订单号$openid=$openid;//用户唯一标识$check_name=&#39;NO_CHECK&#39;;//校验用户姓名选项,NO_CHECK:不校验真实姓名 FORCE_CHECK:强校验真实姓名(未实名认证的用户会校验失败,无法转账)OPTION_CHECK:针对已实名认证的用户才校验真实姓名(未实名认证用户不校验,可以转账成功)$re_user_name=&#39;[北京微函工坊科技有限公司](http://www.vhmake.com)&#39;;//用户姓名$amount=100;//金额(以分为单位,必须大于100)$desc=&#39;[北京微函工坊科技有限公司](http://www.vhmake.com)&#39;;//描述$spbill_create_ip=$_SERVER["REMOTE_ADDR"];//请求ip//封装成数据$dataArr=array();$dataArr[&#39;amount&#39;]=$amount;$dataArr[&#39;check_name&#39;]=$check_name;$dataArr[&#39;desc&#39;]=$desc;$dataArr[&#39;mch_appid&#39;]=$mch_appid;$dataArr[&#39;mchid&#39;]=$mchid;$dataArr[&#39;nonce_str&#39;]=$nonce_str;$dataArr[&#39;openid&#39;]=$openid;$dataArr[&#39;partner_trade_no&#39;]=$partner_trade_no;$dataArr[&#39;re_user_name&#39;]=$re_user_name;$dataArr[&#39;spbill_create_ip&#39;]=$spbill_create_ip;require &#39;api.php&#39;;$sign=getSign($dataArr);echo "-----<br/>签名:".$sign."<br/>*****";//die;$data="<xml>
<mch_appid>".$mch_appid."</mch_appid>
<mchid>".$mchid."</mchid>
<nonce_str>".$nonce_str."</nonce_str>
<partner_trade_no>".$partner_trade_no."</partner_trade_no>
<openid>".$openid."</openid>
<check_name>".$check_name."</check_name>
<re_user_name>".$re_user_name."</re_user_name>
<amount>".$amount."</amount>
<desc>".$desc."</desc>
<spbill_create_ip>".$spbill_create_ip."</spbill_create_ip>
<sign>".$sign."</sign>
</xml>";//var_dump($data);$ch = curl_init ();$MENU_URL="https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";
curl_setopt ( $ch, CURLOPT_URL, $MENU_URL );
curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, "POST" );
curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, FALSE );
curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, FALSE );$zs1="/xxxx/xxx/xxxxxx/apiclient_cert.pem";//注意:填写的路径必须为绝对路径,不可以填写相对路径$zs2="/xxxx/xxx/xxxxx/apiclient_key.pem";
curl_setopt($ch,CURLOPT_SSLCERT,$zs1);
curl_setopt($ch,CURLOPT_SSLKEY,$zs2);// curl_setopt($ch, CURLOPT_USERAGENT, &#39;Mozilla/5.0 (compatible; MSIE 5.01;// Windows NT 5.0)&#39;);curl_setopt ( $ch, CURLOPT_FOLLOWLOCATION, 1 );
curl_setopt ( $ch, CURLOPT_AUTOREFERER, 1 );
curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );$info = curl_exec ( $ch );$infos=simplexml_load_string($info);if (curl_errno ( $ch )) {    echo &#39;Errno:::&#39; . curl_error ( $ch );
}

curl_close ( $ch );echo "-----<br/>请求返回值:";echo $infos->return_code;echo "<br/>*****";?>

3. Generate the signature function file (api.php)

<?php/**
 *  作用:格式化参数,签名过程需要使用
 */function formatBizQueryParaMap($paraMap, $urlencode){
    $buff = "";
    ksort($paraMap);    foreach ($paraMap as $k => $v)
    {        if($urlencode)
        {            $v = urlencode($v);
        }        $buff .= $k . "=" . $v . "&";
    }    if (strlen($buff) > 0)
    {        $reqPar = substr($buff, 0, strlen($buff)-1);
    }    return $reqPar;
}/**
 *  作用:生成签名
 */function getSign($Obj){
    foreach ($Obj as $k => $v)
    {        $Parameters[$k] = $v;
    }    //签名步骤一:按字典序排序参数
    ksort($Parameters);    $String = formatBizQueryParaMap($Parameters, false);    //echo &#39;【string1】&#39;.$String.&#39;</br>&#39;;
    //签名步骤二:在string后加入KEY
    $String = $String."&key=vhmake666vhmake666vhmake666vhmak";    //echo "【string2】".$String."</br>";
    //签名步骤三:MD5加密
    $String = md5($String);    //echo "【string3】 ".$String."</br>";
    //签名步骤四:所有字符转为大写
    $result_ = strtoupper($String);    //echo "【result】 ".$result_."</br>";
    return $result_;
}

Return the return parameters in xml format after success (please refer to the development documentation for details)

<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[]]></return_msg><mch_appid><![CDATA[wxec38b8ff840bd989]]></mch_appid><mchid><![CDATA[10013274]]></mchid><device_info><![CDATA[]]></device_info><nonce_str><![CDATA[lxuDzMnRjpcXzxLx0q]]></nonce_str><result_code><![CDATA[SUCCESS]]></result_code><partner_trade_no><![CDATA[10013574201505191526582441]]></partner_trade_no><payment_no><![CDATA[1000018301201505190181489473]]></payment_no><payment_time><![CDATA[2015-05-19 15:26:59]]></payment_time></xml>

Related recommendations:

Detailed explanation of the PHP backend interface of App WeChat payment

Research and sharing on WeChat payment interface

Use PHP to implement APP Example analysis of WeChat payment

The above is the detailed content of PHP development WeChat payment enterprise payment example code. 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
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools