ThinkPay’s latest WeChat payment official account payment driver sharing
Let’s share the WeChat payment driver of ThinkPay for everyone’s convenience. If you have any questions, please join the QQ group discussion 105108204 // +-------------------------------------------------- -----------------------
// | Zero Cloud [Simple, Efficient and Excellent]
// +-------------------------------------------------- -----------------------
// | Copyright (c) 2016 http://www.lingyun.net All rights reserved.
// +-------------------------------------------------- -----------------------
// | Author: jry <598821125@qq.com>
// +-------------------------------------------------- -----------------------
namespace AddonsPayThinkPayPayDriver;
/**
* WeChat payment driver
*/
class Wxpay extends AddonsPayThinkPayPayPay
{
Protected $gateway = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
Protected $orderquery = 'https://api.mch.weixin.qq.com/pay/orderquery';
protected $config = array(
'appsecret' => '',
‘mchid’ => '',
);
Public function check()
{
if (!$this->config['appid'] || !$this->config['appsecret'] || !$this->config['mchid'] || !$this-> config['key']) {
E("WeChat payment settings are wrong!");
}
return true;
}
Public function buildRequestForm($pay_data)
{
// APP payment
If (C('IS_API')) {
$param = array(
'appid' since 'mch_id' since 'nonce_str' because 'body' because 'out_trade_no' 'total_fee' 'spbill_create_ip' => $_SERVER['REMOTE_ADDR'],
'Notify_url' = & gt; $ this-& gt; config ['notify_url'],
'trade_type' because);
$param['sign'] = $this->MakeSign($param);
$result = $this->FromXml($this->postXmlCurl($xml_param, $this->gateway));
If ($result['return_code'] === 'SUCCESS') {
If ($this->CheckSign($result)) {
// The unified ordering interface returns the normal prepay_id, and then regenerates the signature according to the signature specification, and then transmits the data to the APP.
// Participate in the signature field is appid, partnerid, prepayid, noncestr, timestamp, package. Note: The value format of package is Sign=WXPay
$prepayparams = array();
$prepayparams['appid'] $prepayparams['partnerid'] = $result['mch_id'];
$prepayparams['prepayid'] = $result['prepay_id'];
$prepayparams['noncestr'] = $result['nonce_str'];
$prepayparams['package'] $prepayparams['timestamp'] = time();
$prepayparams['sign'] $return['json'] Return }
}
else {
// Obtain user openId, WeChat public account JSAPI payment is required
$openId = $this->GetOpenid();
$param = array(
'appid' since 'mch_id' since 'nonce_str' => $this->getNonceStr(),
'body' => $pay_data['body'],
'out_trade_no' => $pay_data['out_trade_no'],
'total_fee' => $pay_data['money'] * 100,
'spbill_create_ip' => $_SERVER['REMOTE_ADDR'],
'notify_url' => $this->config['notify_url'],
'trade_type' => 'JSAPI',
'openid' => $openId,
);
// 签名
$param['sign'] = $this->MakeSign($param);
$xml_param = $this->ToXml($param);
$result = $this->FromXml($this->postXmlCurl($xml_param, $this->gateway));
if ($result['return_code'] === 'SUCCESS') {
if ($this->CheckSign($result)) {
// 获取JSAPI所需参数
$jsApiParameters = $this->GetJsApiParameters($result);
$pay_page = <<
该笔订单支付金额为{$pay_data['money']}元
EOF;
}
} else {
E("WeChat order error!" . $result['return_msg']);
}
}
}
/**
* * Asynchronous notification verification
*/
Public function verifyNotify($notify)
{
//Get notification data
If ($notify['return_code'] === 'SUCCESS') {
If (!array_key_exists("transaction_id", $notify)) {
E("The input parameters are incorrect!");
}
$param['transaction_id'] = $notify["transaction_id"];
$param['appid'] $param['mch_id'] $param['nonce_str'] $param['sign'] $xml_param $result = $this->FromXml($this->postXmlCurl($xml_param, $this->orderquery));
If ($this->CheckSign($result)) {
$result['status'] = ($result['result_code'] == 'SUCCESS') ? true : false;
$result['money'] = $result['total_fee'] / 100;
$this->info return true;
}
else {
E('Notification error');
}
}
/**
*
* Get the parameters of jsapi payment
* @param array $UnifiedOrderResult Data returned by the unified payment interface
* @throws WxPayException
*
* @return json数据,可直接填入js函数作为参数
*/
public function GetJsApiParameters($UnifiedOrderResult)
{
if (!array_key_exists("appid", $UnifiedOrderResult)
|| !array_key_exists("prepay_id", $UnifiedOrderResult)
|| $UnifiedOrderResult['prepay_id'] == "") {
E("参数错误");
}
$jsapi['appId'] = $UnifiedOrderResult["appid"];
$jsapi['timeStamp'] = (string) time();
$jsapi['nonceStr'] = $this->getNonceStr();
$jsapi['appId'] = $UnifiedOrderResult["appid"];
$jsapi['package'] = "prepay_id=" . $UnifiedOrderResult['prepay_id'];
$jsapi['signType'] = 'MD5';
$jsapi['paySign'] = $this->MakeSign($jsapi);
$parameters = json_encode($jsapi);
return $parameters;
}
/**
* Submit xml to the corresponding interface url in post mode
*
* @param string $xml XML data required for post
* @param string $url url
* @param bool $useCert Whether a certificate is required, not required by default
* @param int $second URL execution timeout, default 30s
* @throws WxPayException
*/
private static function postXmlCurl($xml, $url, $useCert = false, $second = 30)
{
$ch = curl_init();
//设置超时
curl_setopt($ch, CURLOPT_TIMEOUT, $second);
//如果有配置代理这里就设置代理
// if(WxPayConfig::CURL_PROXY_HOST != "0.0.0.0"
// && WxPayConfig::CURL_PROXY_PORT != 0){
// curl_setopt($ch,CURLOPT_PROXY, WxPayConfig::CURL_PROXY_HOST);
// curl_setopt($ch,CURLOPT_PROXYPORT, WxPayConfig::CURL_PROXY_PORT);
// }
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); //严格校验
//设置header
curl_setopt($ch, CURLOPT_HEADER, false);
//要求结果为字符串且输出到屏幕上
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if ($useCert == true) {
to set up the certificate
//Use certificate: cert and key belong to two .pem files respectively
curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');
curl_setopt($ch, CURLOPT_SSLCERT, WxPayConfig::SSLCERT_PATH);
curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');
curl_setopt($ch, CURLOPT_SSLKEY, WxPayConfig::SSLKEY_PATH);
}
//Post submission method
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
//Run curl
$data = curl_exec($ch);
//Return the result
if ($data) {
curl_close($ch);
return $data;
else {
$error = curl_errno($ch);
curl_close($ch);
E("curl error, error code: $error");
}
}
/*
* * Generate a random string, no longer than 32 bits
* @param int $length
* * @return Random string generated
*/
Public static function getNonceStr($length = 32)
{
$chars = "abcdefghijklmnopqrstuvwxyz0123456789";
$str for ($i = 0; $i < $length; $i++) {
$str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
}
Return $ Str;
}
/**
* Generate signature
* @return Signature, this function does not cover the sign member variable. If you want to set the signature, you need to call the SetSign method to assign a value
*/
Public function MakeSign($param)
{
//Signature step 1: Sort parameters in dictionary order
ksort($param);
$string = $this->ToUrlParams($param);
//Signature step 2: Add KEY after the string
$string = $string . "&key=" . $this->config['key'];
//Signature step three: MD5 encryption
$string = md5($string);
//Signature step 4: Convert all characters to uppercase
$result = strtoupper($string);
Return $ result;
}
/**
*
* 检测签名
*/
public function CheckSign($param)
{
$sign = $this->MakeSign($param);
if ($param['sign'] == $sign) {
return true;
} else {
E("签名错误!");
}
}
/**
*
* * Splicing signature string
* @param array $urlObj
*
* @return Returns the concatenated string
*/
public function ToUrlParams($param)
{
$buff = "";
foreach ($param as $k => $v) {
if ($k != "sign" && $v != "" && !is_array($v)) {
$buff .= $k . "=" . $v . "&";
}
}
$buff = trim($buff, "&");
return $buff;
}
/**
* Output xml characters
* @throws WxPayException
**/
public function ToXml($param)
{
if (!is_array($param)
|| count($param) <= 0) {
E("数组数据异常!");
}
$xml = "
foreach ($param as $key => $val) {
if (is_numeric($val)) {
$xml .= "<" . $key . ">" . $val . "" . $key . ">";
} else {
$xml .= "<" . $key . ">" . $key . ">";
}
}
$xml .= "
return $xml;
}
/**
* Convert xml to array
* * @param string $xml
* @throws WxPayException
*/
public function FromXml($xml)
{
if (!$xml) {
E("xml数据异常!");
}
//Convert XML to array
//It is forbidden to reference external xml entities
libxml_disable_entity_loader(true);
$this->values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
return $this->values;
}
/**
*
* Get the user’s openid through jump. The jump process is as follows:
* 1. Set the URL and other parameters you need to call back, and jump to the WeChat server https://open.weixin.qq.com/connect/oauth2/authorize
* 2. After the WeChat service processing is completed, it will jump back to the user redirect_uri address. At this time, some parameters will be brought, such as: code
*
* @return User’s openid
*/
Public function GetOpenid()
{
//Get openid through code
If (!isset($_GET['code'])) {
//Trigger WeChat return code
$baseUrl = urlencode('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
$url Header("Location: $url");
exit();
else {
to get the code to get the openid
$code $openid = $this->getOpenidFromMp($code);
return $openid;
}
}
/**
*
* Get the openid machine access_token from the work platform through code
* @param string $code The code brought back by WeChat
*
* * @return openid
*/
Public function GetOpenidFromMp($code)
{
$url = $this->__CreateOauthUrlForOpenid($code);
//Initialize curl
$ch = curl_init();
//Set timeout
curl_setopt($ch, CURLOPT_TIMEOUT, $this->curl_timeout);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
///if(WxPayConfig::CURL_PROXY_HOST != "0.0.0.0"
curl_setopt($ch,CURLOPT_PROXY, WxPayConfig::CURL_PROXY_HOST);
// curl_setopt($ch,CURLOPT_PROXYPORT, WxPayConfig::CURL_PROXY_PORT);
// }
//运行curl,结果以jason形式返回
$res = curl_exec($ch);
curl_close($ch);
//取出openid
$data = json_decode($res, true);
$this->data = $data;
$openid = $data['openid'];
return $openid;
}
/**
*
* Construct the url connection to obtain the code
* @param string $redirectUrl The url that the WeChat server bounces back, requires url encoding
*
* @return Return the constructed url
*/
private function __CreateOauthUrlForCode($redirectUrl)
{
$urlObj["appid"] = $this->config['appid'];
$urlObj["redirect_uri"] = "$redirectUrl";
$urlObj["response_type"] = "code";
$urlObj["scope"] = "snsapi_base";
$urlObj["state"] = "#wechat_redirect";
$bizString = $this->ToUrlParams($urlObj);
return "https://open.weixin.qq.com/connect/oauth2/authorize?" . $bizString;
}
/**
*
* Construct to obtain the url address of open and access_toke
* @param string $code, the code brought back by WeChat jump
*
* @return requested url
*/
private function __CreateOauthUrlForOpenid($code)
{
$urlObj["appid"] = $this->config['appid'];
$urlObj["secret"] = $this->config['appsecret'];
$urlObj["code"] = $code;
$urlObj["grant_type"] = "authorization_code";
$bizString = $this->ToUrlParams($urlObj);
return "https://api.weixin.qq.com/sns/oauth2/access_token?" . $bizString;
}
}