1つのPHPファイルは微信の支払いシリーズの企業の支払いを解決します
28355 ワード
ネット上の多くのPHP微信支払いアクセスチュートリアルは複雑で、多くのファイルを配置し、導入する必要があります.本人は整理した後、単一のファイル版を提供します.微信支払いにアクセスしたい人に少し助けと参考になることを望んでいます.
このファイルを直接実行すると、指定した微信ユーザーに振り替えることができます.
注意事項:
コードは次のとおりです.
プロジェクトgitアドレス
PHPファイルは微信の支払いシリーズの企業の支払いを解決します
このファイルを直接実行すると、指定した微信ユーザーに振り替えることができます.
注意事項:
1. , https://pay.weixin.qq.com -> ->API -> ,
2. , -> -> 。
3. :https://pay.weixin.qq.com/wik...
4. :https://pay.weixin.qq.com/wik...
コードは次のとおりです.
/**
*
* 1. , https://pay.weixin.qq.com -> ->API -> , 207 210
* 2. :https://pay.weixin.qq.com/wiki/doc/api/tools/mch_pay.php?chapter=14_2
*/
header('Content-type:text/html; Charset=utf-8');
$mchid = 'xxxxx'; // PartnerID
$appid = 'xxxxx'; // APPID
$appKey = 'xxxxx'; // APP Key
$apiKey = 'xxxxx'; //https://pay.weixin.qq.com - -API -API - API
//①、 openid( , openid)
$wxPay = new WxpayService($mchid,$appid,$appKey,$apiKey);
$openId = $wxPay->GetOpenid(); // openid
if(!$openId) exit(' openid ');
//②、
$outTradeNo = uniqid(); //
$payAmount = 1; // , : 。 1
$trueName = ' '; //
$result = $wxPay->createJsBizPackage($openId,$payAmount,$outTradeNo,$trueName);
echo 'success';
class WxpayService
{
protected $mchid;
protected $appid;
protected $appKey;
protected $apiKey;
public $data = null;
public function __construct($mchid, $appid, $appKey,$key)
{
$this->mchid = $mchid;
$this->appid = $appid;
$this->appKey = $appKey;
$this->apiKey = $key;
}
/**
* openid, :
* 1、 url , https://open.weixin.qq.com/connect/oauth2/authorize
* 2、 redirect_uri , , :code
* @return openid
*/
public function GetOpenid()
{
// code openid
if (!isset($_GET['code'])){
// code
$scheme = $_SERVER['HTTPS']=='on' ? 'https://' : 'http://';
$baseUrl = urlencode($scheme.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].$_SERVER['QUERY_STRING']);
$url = $this->__CreateOauthUrlForCode($baseUrl);
Header("Location: $url");
exit();
} else {
// code , openid
$code = $_GET['code'];
$openid = $this->getOpenidFromMp($code);
return $openid;
}
}
/**
* code openid access_token
* @param string $code code
* @return openid
*/
public function GetOpenidFromMp($code)
{
$url = $this->__CreateOauthUrlForOpenid($code);
$res = self::curlGet($url);
// openid
$data = json_decode($res,true);
$this->data = $data;
$openid = $data['openid'];
return $openid;
}
/**
* open access_toke url
* @param string $code, code
* @return url
*/
private function __CreateOauthUrlForOpenid($code)
{
$urlObj["appid"] = $this->appid;
$urlObj["secret"] = $this->appKey;
$urlObj["code"] = $code;
$urlObj["grant_type"] = "authorization_code";
$bizString = $this->ToUrlParams($urlObj);
return "https://api.weixin.qq.com/sns/oauth2/access_token?".$bizString;
}
/**
* code url
* @param string $redirectUrl url, url
* @return url
*/
private function __CreateOauthUrlForCode($redirectUrl)
{
$urlObj["appid"] = $this->appid;
$urlObj["redirect_uri"] = "$redirectUrl";
$urlObj["response_type"] = "code";
$urlObj["scope"] = "snsapi_base";
$urlObj["state"] = "STATE"."#wechat_redirect";
$bizString = $this->ToUrlParams($urlObj);
return "https://open.weixin.qq.com/connect/oauth2/authorize?".$bizString;
}
/**
*
* @param array $urlObj
* @return
*/
private function ToUrlParams($urlObj)
{
$buff = "";
foreach ($urlObj as $k => $v)
{
if($k != "sign") $buff .= $k . "=" . $v . "&";
}
$buff = trim($buff, "&");
return $buff;
}
/**
*
* @param string $openid 【 】 Openid
* @param float $totalFee
* @param string $outTradeNo
* @param string $orderName
* @param string $notifyUrl url
* @param string $timestamp
* @return string
*/
public function createJsBizPackage($openid, $totalFee, $outTradeNo,$trueName)
{
$config = array(
'mch_id' => $this->mchid,
'appid' => $this->appid,
'key' => $this->apiKey,
);
$unified = array(
'mch_appid' => $config['appid'],
'mchid' => $config['mch_id'],
'nonce_str' => self::createNonceStr(),
'openid' => $openid,
'check_name'=>'FORCE_CHECK', // 。NO_CHECK: ,FORCE_CHECK:
're_user_name'=>$trueName, // ( )
'partner_trade_no' => $outTradeNo,
'spbill_create_ip' => '127.0.0.1',
'amount' => intval($totalFee * 100), //
'desc'=>' ', //
);
$unified['sign'] = self::getSign($unified, $config['key']);
$responseXml = $this->curlPost('https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers', self::arrayToXml($unified));
$unifiedOrder = simplexml_load_string($responseXml, 'SimpleXMLElement', LIBXML_NOCDATA);
if ($unifiedOrder === false) {
die('parse xml error');
}
if ($unifiedOrder->return_code != 'SUCCESS') {
die($unifiedOrder->return_msg);
}
if ($unifiedOrder->result_code != 'SUCCESS') {
die($unifiedOrder->err_code);
}
return true;
}
public static function curlGet($url = '', $options = array())
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
if (!empty($options)) {
curl_setopt_array($ch, $options);
}
//https host
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
public function curlPost($url = '', $postData = '', $options = array())
{
if (is_array($postData)) {
$postData = http_build_query($postData);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_TIMEOUT, 30); // cURL
if (!empty($options)) {
curl_setopt_array($ch, $options);
}
//https host
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
// ,cert key .pem
// PEM,
curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
curl_setopt($ch,CURLOPT_SSLCERT,getcwd().'/cert/apiclient_cert.pem');
// PEM,
curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
curl_setopt($ch,CURLOPT_SSLKEY,getcwd().'/cert/apiclient_key.pem');
// , .pem
// curl_setopt($ch,CURLOPT_SSLCERT,getcwd().'/all.pem');
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
public static function createNonceStr($length = 16)
{
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$str = '';
for ($i = 0; $i < $length; $i++) {
$str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
}
return $str;
}
public static function arrayToXml($arr)
{
$xml = "" ;
foreach ($arr as $key => $val) {
if (is_numeric($val)) {
$xml .= " . $key . ">" . $val . "" . $key . ">";
} else
$xml .= " . $key . "> . $val . "]]>" . $key . ">";
}
$xml .= "";
return $xml;
}
public static function getSign($params, $key)
{
ksort($params, SORT_STRING);
$unSignParaString = self::formatQueryParaMap($params, false);
$signStr = strtoupper(md5($unSignParaString . "&key=" . $key));
return $signStr;
}
protected static function formatQueryParaMap($paraMap, $urlEncode = false)
{
$buff = "";
ksort($paraMap);
foreach ($paraMap as $k => $v) {
if (null != $v && "null" != $v) {
if ($urlEncode) {
$v = urlencode($v);
}
$buff .= $k . "=" . $v . "&";
}
}
$reqPar = '';
if (strlen($buff) > 0) {
$reqPar = substr($buff, 0, strlen($buff) - 1);
}
return $reqPar;
}
}
?>
プロジェクトgitアドレス
PHPファイルは微信の支払いシリーズの企業の支払いを解決します