Home Backend Development PHP Tutorial How to use PHP to implement WeChat payment function on APP

How to use PHP to implement WeChat payment function on APP

Jun 22, 2018 am 09:30 AM
php WeChat Pay

This article mainly introduces PHP to implement the WeChat payment function on the APP side. It is very good and has certain reference value. Friends who need it can refer to it.

I have already written about Alipay payment on the mobile APP, and I will do it again today. Make up for the mobile APP WeChat payment. I won’t go into the preliminary preparations here. You can refer to the WeChat payment development document. Be sure to read the development document carefully to avoid pitfalls. After the preparation is completed, configure the parameters and call Unified ordering interface, three steps of asynchronous callback after payment;

1. I encapsulated a payment class file, removed all redundant things, and put the configuration parameters into this payment class. You only need to modify a few parameters in the Weixinpayandroid method and you can copy and use it directly:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

324

325

326

327

328

329

330

331

332

333

334

335

336

337

class Wxpayandroid

{

 //参数配置

 public $config = array(

    'appid' => "", /*微信开放平台上的应用id*/

    'mch_id' => "", /*微信申请成功之后邮件中的商户id*/

    'api_key' => "", /*在微信商户平台上自己设定的api密钥 32位*/

   );

 //服务器异步通知页面路径(必填)

 public $notify_url = '';

 //商户订单号(必填,商户网站订单系统中唯一订单号)

 public $out_trade_no = '';

 //商品描述(必填,不填则为商品名称)

 public $body = '';

 //付款金额(必填)

 public $total_fee = 0;

 //自定义超时(选填,支持dhmc)

 public $time_expire = '';

 private $WxPayHelper;

 public function Weixinpayandroid($total_fee,$tade_no)

 {

  $this->total_fee = intval($total_fee * 100);//订单的金额 1元

  $this->out_trade_no = $tade_no;// date('YmdHis') . substr(time(), - 5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));//订单号

  $this->body = 'wxpay';//支付描述信息

  $this->time_expire = date('YmdHis', time() + 86400);//订单支付的过期时间(eg:一天过期)

  $this->notify_url = "http://www.ceshi.com/notifyandroid";//异步通知URL(更改支付状态)

  //数据以JSON的形式返回给APP

  $app_response = $this->doPay();

  if (isset($app_response['return_code']) && $app_response['return_code'] == 'FAIL') {

   $errorCode = 100;

   $errorMsg = $app_response['return_msg'];

   $this->echoResult($errorCode, $errorMsg);

  } else {

   $errorCode = 0;

   $errorMsg = 'success';

   $responseData = array(

    'notify_url' => $this->notify_url,

    'app_response' => $app_response,

   );

   $this->echoResult($errorCode, $errorMsg, $responseData);

  }

 }

 //接口输出

 function echoResult($errorCode = 0, $errorMsg = 'success', $responseData = array())

 {

  $arr = array(

   'errorCode' => $errorCode,

   'errorMsg' => $errorMsg,

   'responseData' => $responseData,

  );

   exit(json_encode($arr));  //exit可以正常发送给APP json数据

  // return json_encode($arr); //在TP5中return这个json数据,APP接收到的是null,无法正常吊起微信支付

 }

 function getVerifySign($data, $key)

 {

  $String = $this->formatParameters($data, false);

  //签名步骤二:在string后加入KEY

  $String = $String . "&key=" . $key;

  //签名步骤三:MD5加密

  $String = md5($String);

  //签名步骤四:所有字符转为大写

  $result = strtoupper($String);

  return $result;

 }

 function formatParameters($paraMap, $urlencode)

 {

  $buff = "";

  ksort($paraMap);

  foreach ($paraMap as $k => $v) {

   if($k=="sign"){

    continue;

   }

   if ($urlencode) {

    $v = urlencode($v);

   }

   $buff .= $k . "=" . $v . "&";

  }

  $reqPar;

  if (strlen($buff) > 0) {

   $reqPar = substr($buff, 0, strlen($buff) - 1);

  }

  return $reqPar;

 }

 /**

  * 得到签名

  * @param object $obj

  * @param string $api_key

  * @return string

  */

 function getSign($obj, $api_key)

 {

  foreach ($obj as $k => $v)

  {

   $Parameters[strtolower($k)] = $v;

  }

  //签名步骤一:按字典序排序参数

  ksort($Parameters);

  $String = $this->formatBizQueryParaMap($Parameters, false);

  //签名步骤二:在string后加入KEY

  $String = $String."&key=".$api_key;

  //签名步骤三:MD5加密

  $result = strtoupper(md5($String));

  return $result;

 }

 /**

  * 获取指定长度的随机字符串

  * @param int $length

  * @return Ambigous <NULL, string>

  */

 function getRandChar($length){

  $str = null;

  $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";

  $max = strlen($strPol)-1;

  for($i=0;$i<$length;$i++){

   $str.=$strPol[rand(0,$max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数

  }

  return $str;

 }

 /**

  * 数组转xml

  * @param array $arr

  * @return string

  */

 function arrayToXml($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;

 }

 /**

  * 以post方式提交xml到对应的接口url

  *

  * @param string $xml 需要post的xml数据

  * @param string $url url

  * @param bool $useCert 是否需要证书,默认不需要

  * @param int $second url执行超时时间,默认30s

  * @throws WxPayException

  */

 function postXmlCurl($xml, $url, $second=30, $useCert=false, $sslcert_path=&#39;&#39;, $sslkey_path=&#39;&#39;)

 {

  $ch = curl_init();

  //设置超时

  curl_setopt($ch, CURLOPT_TIMEOUT, $second);

  curl_setopt($ch,CURLOPT_URL, $url);

  //设置header

  curl_setopt($ch, CURLOPT_HEADER, FALSE);

  //要求结果为字符串且输出到屏幕上

  curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

  curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);

  curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);

  if($useCert == true){

   curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,TRUE);

   curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,2);//严格校验

   //设置证书

   //使用证书:cert 与 key 分别属于两个.pem文件

   curl_setopt($ch,CURLOPT_SSLCERTTYPE,&#39;PEM&#39;);

   curl_setopt($ch,CURLOPT_SSLCERT, $sslcert_path);

   curl_setopt($ch,CURLOPT_SSLKEYTYPE,&#39;PEM&#39;);

   curl_setopt($ch,CURLOPT_SSLKEY, $sslkey_path);

  }

  //post提交方式

  curl_setopt($ch, CURLOPT_POST, TRUE);

  curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);

  //运行curl

  $data = curl_exec($ch);

  //返回结果

  if($data){

   curl_close($ch);

   return $data;

  } else {

   $error = curl_errno($ch);

   curl_close($ch);

   return false;

  }

 }

 /**

  * 获取当前服务器的IP

  * @return Ambigous <string, unknown>

  */

 function get_client_ip()

 {

  if (isset($_SERVER[&#39;REMOTE_ADDR&#39;])) {

   $cip = $_SERVER[&#39;REMOTE_ADDR&#39;];

  } elseif (getenv("REMOTE_ADDR")) {

   $cip = getenv("REMOTE_ADDR");

  } elseif (getenv("HTTP_CLIENT_IP")) {

   $cip = getenv("HTTP_CLIENT_IP");

  } else {

   $cip = "127.0.0.1";

  }

  return $cip;

 }

 /**

  * 将数组转成uri字符串

  * @param array $paraMap

  * @param bool $urlencode

  * @return string

  */

 function formatBizQueryParaMap($paraMap, $urlencode)

 {

  $buff = "";

  ksort($paraMap);

  foreach ($paraMap as $k => $v)

  {

   if($urlencode)

   {

    $v = urlencode($v);

   }

   $buff .= strtolower($k) . "=" . $v . "&";

  }

  $reqPar;

  if (strlen($buff) > 0)

  {

   $reqPar = substr($buff, 0, strlen($buff)-1);

  }

  return $reqPar;

 }

 /**

  * XML转数组

  * @param unknown $xml

  * @return mixed

  */

 function xmlToArray($xml)

 {

  //将XML转为array

  $array_data = json_decode(json_encode(simplexml_load_string($xml, &#39;SimpleXMLElement&#39;, LIBXML_NOCDATA)), true);

  return $array_data;

 }

 public function chkParam()

 {

  //用户网站订单号

  if (empty($this->out_trade_no)) {

   die(&#39;out_trade_no error&#39;);

  }

  //商品描述

  if (empty($this->body)) {

   die(&#39;body error&#39;);

  }

  if (empty($this->time_expire)){

   die(&#39;time_expire error&#39;);

  }

  //检测支付金额

  if (empty($this->total_fee) || !is_numeric($this->total_fee)) {

   die(&#39;total_fee error&#39;);

  }

  //异步通知URL

  if (empty($this->notify_url)) {

   die(&#39;notify_url error&#39;);

  }

  if (!preg_match("#^http:\/\/#i", $this->notify_url)) {

   $this->notify_url = "http://" . $_SERVER[&#39;HTTP_HOST&#39;] . $this->notify_url;

  }

  return true;

 }

 /**

  * 生成支付(返回给APP)

  * @return boolean|mixed

  */

 public function doPay() {

  //检测构造参数

  $this->chkParam();

  return $this->createAppPara();

 }

 /**

  * APP统一下单

  */

 private function createAppPara()

 {

  $url = "https://api.mch.weixin.qq.com/pay/unifiedorder";

  $data["appid"]  = $this->config[&#39;appid&#39;];//微信开放平台审核通过的应用APPID

  $data["body"]   = $this->body;//商品或支付单简要描述

  $data["mch_id"]  = $this->config[&#39;mch_id&#39;];//商户号

  $data["nonce_str"] = $this->getRandChar(32);//随机字符串

  $data["notify_url"] = $this->notify_url;//通知地址

  $data["out_trade_no"] = $this->out_trade_no;//商户订单号

  $data["spbill_create_ip"] = $this->get_client_ip();//终端IP

  $data["total_fee"]  = $this->total_fee;//总金额

  $data["time_expire"]  = $this->time_expire;//交易结束时间

  $data["trade_type"]  = "APP";//交易类型

  $data["sign"]    = $this->getSign($data, $this->config[&#39;api_key&#39;]);//签名

  $xml  = $this->arrayToXml($data);

  $response = $this->postXmlCurl($xml, $url);

  //将微信返回的结果xml转成数组

  $responseArr = $this->xmlToArray($response);

  if(isset($responseArr["return_code"]) && $responseArr["return_code"]==&#39;SUCCESS&#39;){

   return $this->getOrder($responseArr[&#39;prepay_id&#39;]);

  }

  return $responseArr;

 }

 /**

  * 执行第二次签名,才能返回给客户端使用

  * @param int $prepayId:预支付交易会话标识

  * @return array

  */

 public function getOrder($prepayId)

 {

  $data["appid"]  = $this->config[&#39;appid&#39;];

  $data["noncestr"] = $this->getRandChar(32);

  $data["package"] = "Sign=WXPay";

  $data["partnerid"] = $this->config[&#39;mch_id&#39;];

  $data["prepayid"] = $prepayId;

  $data["timestamp"] = time();

  $data["sign"]  = $this->getSign($data, $this->config[&#39;api_key&#39;]);

  $data["packagestr"] = "Sign=WXPay";

  return $data;

 }

 /**

  * 异步通知信息验证

  * @return boolean|mixed

  */

 public function verifyNotify()

 {

  $xml = isset($GLOBALS[&#39;HTTP_RAW_POST_DATA&#39;]) ? $GLOBALS[&#39;HTTP_RAW_POST_DATA&#39;] : &#39;&#39;;

  if(!$xml){

   return false;

  }

  $wx_back = $this->xmlToArray($xml);

  if(empty($wx_back)){

   return false;

  }

  $checkSign = $this->getVerifySign($wx_back, $this->config[&#39;api_key&#39;]);

  if($checkSign=$wx_back[&#39;sign&#39;]){

   return $wx_back;

  }else{

   return false;

  }

 }

}

Copy after login

2. Create a controller to define a unified order interface and asynchronous payment after payment Callback interface:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

//异步通知接口

 public function notifyandroid()

 {

  $wxpayandroid = new \Wxpayandroid;  //实例化微信支付类

  $verify_result = $wxpayandroid->verifyNotify();

  if ($verify_result[&#39;return_code&#39;]==&#39;SUCCESS&#39; && $verify_result[&#39;result_code&#39;]==&#39;SUCCESS&#39;) {

    //商户订单号

    $out_trade_no = $verify_result[&#39;out_trade_no&#39;];

    //交易号

    $trade_no  = $verify_result[&#39;transaction_id&#39;];

    //交易状态

    $trade_status = $verify_result[&#39;result_code&#39;];

    //支付金额

    $total_fee = $verify_result[&#39;total_fee&#39;]/100;

    //支付过期时间

    $pay_date  = $verify_result[&#39;time_end&#39;];

    $order = new Order();

    $ret = $order->getOrderN2($out_trade_no); //获取订单信息

    $total_amount=$ret[&#39;money&#39;];

    if ($total_amount==$total_fee) {

     // 验证成功 修改数据库的订单状态等 $result[&#39;out_trade_no&#39;]为订单号

     //此处写自己的逻辑代码

    }

   exit(&#39;<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>&#39;);

  }else{

   exit(&#39;<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[ERROR]]></return_msg></xml>&#39;);

  }

 }

  

 //调用统一下单接口生成预支付订单并把数据返回给APP

 public function wxpayandroid(Request $request)

 {

  $param = $request->param(); //接收值

  

  $tade_no = $param[&#39;orderCode&#39;];

  $order = new Order(); //实例化订单

  $ret = $order->getOrderN2($tade_no); //查询订单信息

  $total_fee = $ret[&#39;money&#39;]; //订单总金额

   

  $wxpayandroid = new \Wxpayandroid;  //实例化微信支付类

  $res = $wxpayandroid->Weixinpayandroid($total_fee,$tade_no); //调用weixinpay方法

   

 }

Copy after login

Encapsulate a payment class file, put the configuration parameters into the payment class, and then define the controller to create two methods, so two steps You can use the mobile APP WeChat payment.

The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

php How to implement WeChat enterprise account payment for individuals

PHP implements WeChat public platform enterprise account verification interface

The above is the detailed content of How to use PHP to implement WeChat payment function on APP. 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 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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

What is Cross-Site Request Forgery (CSRF) and how do you implement CSRF protection in PHP? What is Cross-Site Request Forgery (CSRF) and how do you implement CSRF protection in PHP? Apr 07, 2025 am 12:02 AM

In PHP, you can effectively prevent CSRF attacks by using unpredictable tokens. Specific methods include: 1. Generate and embed CSRF tokens in the form; 2. Verify the validity of the token when processing the request.

See all articles