PHP implementation of WeChat application refund process method

Source: Internet
Author: User
This article mainly introduces the application of PHP implementation refund process, the use of the official SDK in the most important one of the class file WxPay.Api.php provided in the refund () method to achieve, complete everyone reference this article, I hope to help everyone.

Of course, the payment is done, or how to refund, this time or use the official demo. Of course, there may also be a lot of gods on the web to rewrite and encapsulate the demo, perhaps more concise, but I still do not advocate for use, for the following reasons:

(1) may not be complete, perhaps he just realized the payment, but there are applications for refunds, query refunds, order inquiries, cancellation orders and other business functions may be your follow-up needs, if you rely on the great God's SDK convenient, if there is new business needs, you are confused;

(2) Security considerations, involving payment involving money, must be very safe. Official SDK Although I also spit groove, but at least relatively safe, re-rewrite, although temporarily did not see the problem, but in case there is a loophole is not good.

This article is also implemented using the refund () method provided in the most important class file WxPay.Api.php in the official SDK, this method is in line 141th of the WxPay.Api.php file, and the code is as follows:


/** * * Request a refund, Wxpayrefund out_trade_no, transaction_id at least one and * out_refund_no, Total_fee, Refund_fee, op_user_id are required parameters * app  ID, Mchid, spbill_create_ip, nonce_str do not need to be filled in * @param wxpayrefund $INPUTOBJ * @param int $timeOut * @throws wxpayexception * @return Return on success, other throw exception */public static function refund ($INPUTOBJ, $timeOut = 6) {$url = "https://api.mch.weixin.qq.com/  Secapi/pay/refund "; Check for Required parameters if (! $INPUTOBJ->isout_trade_noset () &&! $INPUTOBJ->istransaction_idset ()) {throw new Wxpayexception ("Refund Application interface, OUT_TRADE_NO, transaction_id at least one!")  "); }else if (! $INPUTOBJ->isout_refund_noset ()) {throw new wxpayexception ("Missing required parameters in the refund request interface out_refund_no!  "); }else if (! $INPUTOBJ->istotal_feeset ()) {throw new wxpayexception ("Missing required parameters in the refund request interface total_fee!  "); }else if (! $INPUTOBJ->isrefund_feeset ()) {throw new wxpayexception ("Missing required parameters in the refund request interface refund_fee!  "); }else if (! $INPUTOBJ->isop_user_idset ()) {throw new wxpayexception ("Missing required parameters in the refund request interface op_user_id!  "); } $INPUTOBJ->setappid (WxPAYCONFIG::APPID)///Public account ID $INPUTOBJ->setmch_id (wxpayconfig::mchid);//Merchant number $INPUTOBJ->setnonce_str (self::  Getnoncestr ());//random string $INPUTOBJ->setsign ();//Signature $xml = $INPUTOBJ->toxml ();  $startTimeStamp = Self::getmillisecond ();//Request start time $response = self::p ostxmlcurl ($xml, $url, True, $timeOut);  $result = Wxpayresults::init ($response); Self::reportcosttime ($url, $startTimeStamp, $result);//The escalation request takes time to return $result; }

The official method, written clearly what parameters are required, and some must-have parameters the SDK has helped us, and I'll reseal this method to make it easier to invoke in the project:


/** * Refunds * @param string $order _id Order ID * @return Return on success (array type), other throw exception */function Wxrefund ($order _id) {//My SDK is placed in project root The API directory under Require_once app_root. "  /api/wxpay/lib/wxpay.api.php "; Query the order, according to the data inside the order to refund $order = M (' order ')->where (' id ' = = $order _id, ' Is_refund ' =>2, ' order_status ' =  1))->find ();  $merchid = Wxpayconfig::mchid;  if (! $order) return false;  $input = new Wxpayrefund ();   $input->setout_trade_no ($order [' order_sn ']);  Your order number $input->settransaction_id ($order [' transaction_id ']);   The official generated order serial number, which returns $input->setout_refund_no (Getrand_num (True)) in the payment success;   Refund number $input->settotal_fee ($order [' Total_price ']);   The amount of the order price, in units of $input->setrefund_fee ($order [' Total_price ']);  The total amount of the refund, the total amount of the order, in units of points, only for integers $input->setop_user_id ($merchid); $result = Wxpayapi::refund ($input); Refund operation//This sentence file_put_contents is used to view the refund results returned by the server after the test can be removed//file_put_contents (app_root. '  /api/wxpay/logs/log3.txt ', Arraytoxml ($result), file_append); return $result; }

Here need to spit groove, unexpectedly do not say the type of return value, when the payment is returned by the XML data, here unexpectedly returned is an array, let me unprepared, haha but still return the array is better, can directly judge the processing.

The method invocation is much simpler:


Refund $result = Wxrefund ($order _id); This sentence file_put_contents is used to view the refund results returned by the server after the test can be removed//file_put_contents (app_root. ' /api/wxpay/logs/log4.txt ', Arraytoxml ($result), file_append); if ($result [' Return_code ']== ' SUCCESS ') && ($result [' Result_code ']== ' SUCCESS ')} {  //Refund Successful}else if (($ result[' Return_code ']== ' FAIL ') | | ($result [' Result_code ']== ' FAIL ') {  //Refund failed  //reason  $reason = (Empty ($result [' err_code_des '])? $result [' Return_msg ']: $result [' Err_code_des ' ]); }else{  //Failure}

The refund was successfully returned as follows:

Pro-Test error: This is the integration of the official SDK implementation, if you do not use the SDK, you can use the simpler method, see: PHP Implementation payment (JSAPI payment) and refunds (no integration payment SDK required)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.