We know that WeChat Pay’s enterprise payment to change function is widely used, such as WeChat red envelope rewards, business settlement, etc. Make payments to individuals through businesses, and the payment funds will go directly into the user's WeChat change. So how do we implement this feature?
1. Activation conditions
(Free learning video tutorial sharing: php video tutorial)
Payment funds
Enterprises pay to change funds using the balance of the merchant number.
According to the account opening status of the merchant number, the actual withdrawal account is different:
◆ By default, the enterprise uses the balance of the basic account (or balance account) of the merchant number to pay in change. If the merchant account has opened an operating account, the enterprise can use the funds in the operating account to pay the change.
◆ The source of funds for the basic account (or other withdrawal accounts mentioned above) may be transaction settlement funds (basic account only), or funds to recharge the account. When the balance of the withdrawal account is insufficient, the payment will fail due to insufficient balance.
Payment Rules
Payment Method
◆ Support API interface or web page operation, payment to target users.
Specification of payment user identity
◆Specify the payment user through APPID OPENID.
◆ The APPID needs to be the APPID used when applying for a merchant account, or be bound to the merchant account.
◆ How to obtain OPENID, please refer to: https://developers.weixin.qq.com/doc/offiaccount/User_Management/Get_users_basic_information_UnionID.html#UinonId
Payment limit
◆ Payment to non-real-name users is not supported
◆ Payment to the same real-name user has a single daily limit of 2W/2W
◆ The total payment limit for a merchant on the same day is 100W
Note: The limits of 20,000 and 1,000,000 in the above rules are not completely accurate due to the relationship between calculation rules and risk control strategies. The amount is only For reference, please do not rely on this amount for system processing. The actual return and query results of the interface should prevail. Please know.
Payment User Identity Verification
◆ Provide the function of verifying the real name of the target user for payment
Query payment status
◆ For paid records, enterprises can check the corresponding data through enterprise payment query, or query the merchant account's capital flow.
Payment frequency
◆ By default, payments can be made to the same user up to 10 times a day, which can be set in the merchant platform--API security
Other notes
◆The payment amount must be less than or equal to the merchant’s current available balance;
2. Interface address
Interface link: https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers
Request parameters:
For details, please refer to the official enterprise payment Development document description
1. Basic configuration
//公众账号appid $data["mch_appid"] = 'appid'; //商户号 $data["mchid"] = ''; //随机字符串 $data["nonce_str"] = 'suiji'.mt_rand(100,999); //商户订单号 $data["partner_trade_no"]=date('YmdHis').mt_rand(1000,9999); //金额 用户输入的提现金额需要乘以100 $data["amount"] = $money; //企业付款描述 $data["desc"] = '企业付款到个人零钱'; //用户openid $data["openid"] = $openid; //不检验用户姓名 $data["check_name"] = 'NO_CHECK'; //获取IP $data['spbill_create_ip']=$_SERVER['SERVER_ADDR']; //商户密钥 $data['key']=''; //商户证书 商户平台的API安全证书下载 $data['apiclient_cert.pem'] $data['apiclient_key.pem']
2. PHP code
/** **开始支付 / public function userpay(){ $money = ‘用户输入提现金额'; $info['money'] = ‘用户余额'; if ($this->openid && $money){ if ($money>$info['money'] ){ echo json_encode([ 'status' => 1, 'message' => '余额不足,不能提现!', 'code'=>'余额不足,不能提现!' ]); }elseif ($money<1){ echo json_encode([ 'status' => 2, 'message' => '提现金额不能小于1元', 'code'=>'提现金额太低' ]); }else{ $openid = $this->openid; $trade_no = date('YmdHis').mt_rand(1000,9999); $res = $this->pay($openid,$trade_no,$money*100,'微信提现'); //结果打印 if($res['result_code']=="SUCCESS"){ echo json_encode([ 'status' => 3, 'message' => '提现成功!', ]); }elseif ($res['err_code']=="SENDNUM_LIMIT"){ echo json_encode([ 'status' => 4, 'message' => '提现失败!', 'code'=>'每日仅能提现一次', ]); }else{ echo json_encode([ 'status' => 5, 'message' => '提现失败!', 'code'=>$res['err_code'], ]); } } }else{ echo json_encode([ 'status' => 5, 'message' => '未检测到您当前微信账号~', ]); } }
Payment method:
/** *支付方法 / public function pay($openid,$trade_no,$money,$desc){ $params["mch_appid"]=''; $params["mchid"] = ''; $params["nonce_str"]= 'suiji'.mt_rand(100,999); $params["partner_trade_no"] = $trade_no; $params["amount"]= $money; $params["desc"]= $desc; $params["openid"]= $openid; $params["check_name"]= 'NO_CHECK'; $params['spbill_create_ip'] = $_SERVER['SERVER_ADDR']; //生成签名 $str = 'amount='.$params["amount"].'&check_name='.$params["check_name"].'&desc='.$params["desc"].'&mch_appid='.$params["mch_appid"].'&mchid='.$params["mchid"].'&nonce_str='.$params["nonce_str"].'&openid='.$params["openid"].'&partner_trade_no='.$params["partner_trade_no"].'&spbill_create_ip='.$params['spbill_create_ip'].'&key=商户密钥'; //md5加密 转换成大写 $sign = strtoupper(md5($str)); //生成签名 $params['sign'] = $sign; //构造XML数据 $xmldata = $this->array_to_xml($params); //数组转XML $url='https://api.mch.weixin.qq.com/mmpaymkttransfers/prom otion/transfers'; //发送post请求 $res = $this->curl_post_ssl($url, $xmldata); //curl请求 if(!$res){ return array('status'=>1, 'msg'=>"服务器连接失败" ); } //付款结果分析 $content = $this->xml_to_array($res); //xml转数组 return $content; }
curl request
/** * curl请求 / public function curl_post_ssl($url, $xmldata, $second=30,$aHeader=array()){ $ch = curl_init(); //超时时间 curl_setopt($ch,CURLOPT_TIMEOUT,$second); curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1); //这里设置代理,如果有的话 //curl_setopt($ch,CURLOPT_PROXY, '10.206.30.98'); //curl_setopt($ch,CURLOPT_PROXYPORT, 8080); curl_setopt($ch,CURLOPT_URL,$url); curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false); curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false); //默认格式为PEM,可以注释 curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM'); //绝对地址可使用 dirname(__DIR__)打印,如果不是绝对地址会报 58 错误 curl_setopt($ch,CURLOPT_SSLCERT,' 绝对地址/apiclient_cert.pem'); curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM'); curl_setopt($ch,CURLOPT_SSLKEY,'绝对地址/apiclient_key.pem'); if( count($aHeader) >= 1 ){ curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader); } curl_setopt($ch,CURLOPT_POST, 1); curl_setopt($ch,CURLOPT_POSTFIELDS,$xmldata); $data = curl_exec($ch); if($data){ curl_close($ch); return $data; } else { $error = curl_errno($ch); echo "call faild, errorCode:$error\n"; die(); curl_close($ch); return false; } }
Generate signature
/** * array 转 xml * 用于生成签名 */ public function array_to_xml($arr){ $xml = "<xml>"; foreach ($arr as $key => $val) { if (is_numeric($val)) { $xml .= "<" .$key.">".$val."</".$key.">"; } else $xml .= "<".$key."><![CDATA[".$val."]]></".$key.">"; } $xml .= "</xml>"; return $xml; } /** * xml 转化为array */ public function xml_to_array($xml){ //禁止引用外部xml实体 libxml_disable_entity_loader(true); $values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true); return $values; }
The result is as shown in the figure:
Related Recommended article tutorials: php tutorial
The above is the detailed content of PHP realizes WeChat enterprise payment to change. For more information, please follow other related articles on the PHP Chinese website!

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

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.

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

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

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

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.

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

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


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 Linux new version
SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software
