With the development of mobile Internet, WeChat has become an indispensable part of people's lives, and more and more merchants choose to conduct business on the WeChat platform. Implementing WeChat payment function is very necessary for merchants. This article will introduce how to use PHP to implement JSAPI payment.
First of all, we need to understand what JSAPI payment is. JSAPI is a kind of payment function of WeChat official account. It calls WeChat payment interface through JS to realize payment. The advantage of JSAPI payment is that users only need to pay in WeChat without jumping to other pages, which is more convenient.
Next, we need to make some preparations:
After completing the above preparations, we need to download WeChat Unification For the PHP SDK of the payment API, you can search for "wechatpay-GuzzleHttp" on GitHub, download it and put it in the root directory of the project.
Next, we need to write PHP code to implement JSAPI payment. First, you need to introduce the file:
require_once 'wechatpay-GuzzleHttp/autoload.php'; use WeChatPayGuzzleMiddlewareUtilPemUtil; use WeChatPayGuzzleMiddlewareWeChatPayMiddleware; use GuzzleHttpClient; use GuzzleHttpHandlerStack;
Then, you need to set the relevant parameters and create the GuzzleHttpClient object:
// 设置相关参数 $appid = "xxxxxxxxx"; // 微信支付的应用ID(APPID) $mchid = "xxxxxxxxx"; // 商户号(MCHID) $apiKey = "xxxxxxxxx"; // APISecret密钥 $notifyUrl = "http://example.com/notify.php"; // 异步通知URL // 创建GuzzleHttpClient对象 $stack = HandlerStack::create(); $privateKey = PemUtil::loadPrivateKey('file://path/to/your/key.pem'); // 加载私钥文件 $wechatpayMiddleware = WeChatPayMiddleware::builder() ->withMerchant($appid, $mchid, $apiKey) ->withNotifyUrl($notifyUrl) ->withKey($privateKey) ->build(); $stack->push($wechatpayMiddleware, 'wechatpay'); $client = new Client(['handler' => $stack, 'verify' => false]);
In the above code, we use a third-party PHP library "wechatpay-GuzzleHttp", It encapsulates the WeChat payment API and implements request and response processing through middleware.
Then, we need to write code to obtain the user's openid:
// 获取用户的openid $code = $_GET['code']; // 通过微信OAuth2.0授权获取的code $accessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appid}&secret={$secret}&code={$code}&grant_type=authorization_code"; $accessTokenResponse = $client->get($accessTokenUrl); $accessTokenBody = $accessTokenResponse->getBody()->getContents(); $accessToken = json_decode($accessTokenBody, true)['access_token']; $openid = json_decode($accessTokenBody, true)['openid'];
In the above code, we obtain the user's access_token and openid through OAuth2.0 authorization, which will be used in the subsequent payment process. openid.
Finally, we need to write the JSAPI payment code:
// 支付 $request = $client->request('POST', 'https://api.mch.weixin.qq.com/pay/unifiedorder', [ 'xml' => [ 'body' => '商品描述', 'out_trade_no' => '商户订单号', 'fee_type' => 'CNY', 'total_fee' => '1', 'spbill_create_ip' => $_SERVER['REMOTE_ADDR'], 'notify_url' => $notifyUrl, 'trade_type' => 'JSAPI', 'openid' => $openid, 'sign_type' => 'MD5', 'nonce_str' => uniqid(), 'appid' => $appid, 'mch_id' => $mchid, ], ]); $response = $request->getBody()->getContents(); $xml = simplexml_load_string($response, 'SimpleXMLElement', LIBXML_NOCDATA); $resultCode = json_decode(json_encode($xml), true)['result_code']; if ($resultCode == 'SUCCESS') { $prepayId = json_decode(json_encode($xml), true)['prepay_id']; $jsapiConfig = [ 'appId' => $appid, 'timestamp' => time(), 'nonceStr' => uniqid(), 'package' => "prepay_id={$prepayId}", 'signType' => 'MD5', ]; $jsapiConfig['paySign'] = sign($jsapiConfig, $apiKey); // 生成签名 $jsapiConfig['debug'] = true; // 开启调试模式 $jsapiConfigJson = json_encode($jsapiConfig); $jsapi = <<<EOF <script> wx.config({}); // 微信JS-SDK配置 wx.ready(function() { wx.chooseWXPay({ timestamp: '{$jsapiConfig['timestamp']}', nonceStr: '{$jsapiConfig['nonceStr']}', package: '{$jsapiConfig['package']}', signType: '{$jsapiConfig['signType']}', paySign: '{$jsapiConfig['paySign']}', success: function(res) { // 支付成功调用的函数 }, fail: function(res) { // 支付失败调用的函数 } }); }); </script> EOF; echo $jsapi; // 输出JSAPI支付代码 } // 生成签名 function sign($data, $apiKey) { ksort($data); $query = urldecode(http_build_query($data) . "&key={$apiKey}"); return strtoupper(md5($query)); }
In the above code, we use the "chooseWXPay" function in WeChat JS-SDK to implement the payment function. Specifically, we obtain the prepayment transaction session ID (prepay_id) by calling the WeChat Pay unified order API, and then pass the generated jsapi parameters into the chooseWXPay function to call up the WeChat payment interface for payment.
So far, we have successfully implemented JSAPI payment. To summarize, the following steps need to be completed to implement JSAPI payment:
Hope this article The introduction can help PHP developers quickly implement JSAPI payment functions.
The above is the detailed content of PHP WeChat development: How to implement JSAPI payment. For more information, please follow other related articles on the PHP Chinese website!