Home Backend Development PHP Tutorial PHP realizes WeChat enterprise payment to change

PHP realizes WeChat enterprise payment to change

Jan 29, 2020 pm 08:29 PM
php Payment enterprise WeChat

PHP realizes WeChat enterprise payment to change

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

PHP realizes WeChat enterprise payment to change

(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

PHP realizes WeChat enterprise payment to change

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']
Copy after login

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([
   &#39;status&#39; => 2,
   &#39;message&#39; => &#39;提现金额不能小于1元&#39;,
   &#39;code&#39;=>&#39;提现金额太低&#39;
  ]);
  }else{
 $openid = $this->openid;
 $trade_no = date(&#39;YmdHis&#39;).mt_rand(1000,9999);
 $res = $this->pay($openid,$trade_no,$money*100,&#39;微信提现&#39;);

 //结果打印
 if($res[&#39;result_code&#39;]=="SUCCESS"){

   echo json_encode([
   &#39;status&#39; => 3,
   &#39;message&#39; => &#39;提现成功!&#39;,
   ]);
  }elseif ($res[&#39;err_code&#39;]=="SENDNUM_LIMIT"){
   echo json_encode([
   &#39;status&#39; => 4,
   &#39;message&#39; => &#39;提现失败!&#39;,
   &#39;code&#39;=>&#39;每日仅能提现一次&#39;,
   ]);
  }else{
   echo json_encode([
   &#39;status&#39; => 5,
   &#39;message&#39; => &#39;提现失败!&#39;,
   &#39;code&#39;=>$res[&#39;err_code&#39;],
   ]);
  }
  }
 }else{
  echo json_encode([
  &#39;status&#39; => 5,
  &#39;message&#39; => &#39;未检测到您当前微信账号~&#39;,

  ]);
 }
 }
Copy after login

Payment method:

/**
*支付方法
/
public function pay($openid,$trade_no,$money,$desc){
 $params["mch_appid"]=&#39;&#39;; 
 $params["mchid"] = &#39;&#39;; 
 $params["nonce_str"]= &#39;suiji&#39;.mt_rand(100,999); 
 $params["partner_trade_no"] = $trade_no;  
 $params["amount"]= $money;  
 $params["desc"]= $desc;  
 $params["openid"]= $openid;  
 $params["check_name"]= &#39;NO_CHECK&#39;; 
 $params[&#39;spbill_create_ip&#39;] = $_SERVER[&#39;SERVER_ADDR&#39;]; 

 //生成签名
 $str = &#39;amount=&#39;.$params["amount"].&#39;&check_name=&#39;.$params["check_name"].&#39;&desc=&#39;.$params["desc"].&#39;&mch_appid=&#39;.$params["mch_appid"].&#39;&mchid=&#39;.$params["mchid"].&#39;&nonce_str=&#39;.$params["nonce_str"].&#39;&openid=&#39;.$params["openid"].&#39;&partner_trade_no=&#39;.$params["partner_trade_no"].&#39;&spbill_create_ip=&#39;.$params[&#39;spbill_create_ip&#39;].&#39;&key=商户密钥&#39;;

 //md5加密 转换成大写
 $sign = strtoupper(md5($str));
 //生成签名
 $params[&#39;sign&#39;] = $sign;

 //构造XML数据
 $xmldata = $this->array_to_xml($params); //数组转XML
 $url=&#39;https://api.mch.weixin.qq.com/mmpaymkttransfers/prom otion/transfers&#39;;

 //发送post请求
 $res = $this->curl_post_ssl($url, $xmldata); //curl请求 
 if(!$res){
 return array(&#39;status&#39;=>1, 
   &#39;msg&#39;=>"服务器连接失败" );
 }

 //付款结果分析
 $content = $this->xml_to_array($res); //xml转数组
 return $content;
 }
Copy after login

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, &#39;10.206.30.98&#39;);
 //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,&#39;PEM&#39;);
//绝对地址可使用 dirname(__DIR__)打印,如果不是绝对地址会报 58 错误
 curl_setopt($ch,CURLOPT_SSLCERT,&#39; 绝对地址/apiclient_cert.pem&#39;);
 curl_setopt($ch,CURLOPT_SSLKEYTYPE,&#39;PEM&#39;);
 curl_setopt($ch,CURLOPT_SSLKEY,&#39;绝对地址/apiclient_key.pem&#39;);
 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;
 }
 }
Copy after login

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, &#39;SimpleXMLElement&#39;, LIBXML_NOCDATA)), true);
 return $values;
 }
Copy after login

The result is as shown in the figure:

PHP realizes WeChat enterprise payment to change

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!

Statement of this Website
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

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

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1670
14
PHP Tutorial
1274
29
C# Tutorial
1256
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

The Continued Use of PHP: Reasons for Its Endurance The Continued Use of PHP: Reasons for Its Endurance Apr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

The latest news APP ranking recommendation in the currency circle (authoritative release in 2025) The latest news APP ranking recommendation in the currency circle (authoritative release in 2025) Apr 21, 2025 pm 09:33 PM

The best cryptocurrency trading and analysis platforms include: 1. OKX: the world's number one in trading volume, supports multiple transactions, provides AI market analysis and on-chain data monitoring. 2. Binance: The world's largest exchange, providing in-depth market conditions and new currency first-time offerings. 3. Sesame Open Door: Known for spot trading and OTC channels, it provides automated trading strategies. 4. CoinMarketCap: an authoritative market data platform, covering 20,000 currencies. 5. CoinGecko: Known for community sentiment analysis, it provides DeFi and NFT trend monitoring. 6. Non-small account: a domestic market platform, providing analysis of linkage between A-shares and currency markets. 7. On-chain Finance: Focus on blockchain news and update in-depth reports every day. 8. Golden Finance: 24 small

The Compatibility of IIS and PHP: A Deep Dive The Compatibility of IIS and PHP: A Deep Dive Apr 22, 2025 am 12:01 AM

IIS and PHP are compatible and are implemented through FastCGI. 1.IIS forwards the .php file request to the FastCGI module through the configuration file. 2. The FastCGI module starts the PHP process to process requests to improve performance and stability. 3. In actual applications, you need to pay attention to configuration details, error debugging and performance optimization.

See all articles